Tusker/Tusker/Controllers/MastodonController.swift

69 lines
2.1 KiB
Swift
Raw Normal View History

2018-08-16 11:46:19 +00:00
//
// MastodonController.swift
// Tusker
//
// Created by Shadowfacts on 8/15/18.
// Copyright © 2018 Shadowfacts. All rights reserved.
//
import Foundation
import MastodonKit
2018-08-16 22:55:40 +00:00
class MastodonController {
2018-08-16 11:46:19 +00:00
2018-08-16 22:55:40 +00:00
static let shared = MastodonController()
2018-08-16 11:46:19 +00:00
var client: Client!
2018-08-31 02:30:19 +00:00
var account: Account!
2018-08-16 11:46:19 +00:00
private init() {
}
2018-08-20 21:23:35 +00:00
func createClient() {
2018-08-19 20:14:04 +00:00
guard let url = LocalData.shared.instanceURL else { fatalError("Can't connect without instance URL") }
2018-08-16 11:46:19 +00:00
2018-08-19 20:14:04 +00:00
client = Client(baseURL: url)
2018-08-20 21:23:35 +00:00
if let accessToken = LocalData.shared.accessToken {
client.accessToken = accessToken
2018-08-16 22:55:40 +00:00
}
}
2018-08-20 21:23:35 +00:00
func registerApp(completion: @escaping () -> Void) {
2018-08-19 20:14:04 +00:00
guard LocalData.shared.clientID == nil,
LocalData.shared.clientSecret == nil else {
2018-08-17 00:11:56 +00:00
completion()
2018-08-19 20:14:04 +00:00
return
}
let registerRequest = Clients.register(clientName: "Tusker", redirectURI: "tusker://oauth", scopes: [.read, .write, .follow])
client.run(registerRequest) { result in
guard case let .success(application, _) = result else { fatalError() }
LocalData.shared.clientID = application.clientID
LocalData.shared.clientSecret = application.clientSecret
completion()
2018-08-16 22:55:40 +00:00
}
2018-08-17 00:11:56 +00:00
}
2018-08-19 20:14:04 +00:00
func authorize(authorizationCode: String, completion: @escaping () -> Void) {
2018-08-20 21:23:35 +00:00
let authorizeRequest = Login.authorize(code: authorizationCode, clientID: LocalData.shared.clientID!, clientSecret: LocalData.shared.clientSecret!, redirectURI: "tusker://oauth")
2018-08-19 20:14:04 +00:00
client.run(authorizeRequest) { result in
guard case let .success(settings, _) = result else { fatalError() }
LocalData.shared.accessToken = settings.accessToken
self.client.accessToken = settings.accessToken
completion()
2018-08-16 11:46:19 +00:00
}
}
2018-08-31 02:30:19 +00:00
func getOwnAccount() {
let req = Accounts.currentUser()
client.run(req) { result in
guard case let .success(account, _) = result else { fatalError() }
self.account = account
}
}
2018-08-16 11:46:19 +00:00
}