forked from shadowfacts/Tusker
77 lines
2.4 KiB
Swift
77 lines
2.4 KiB
Swift
//
|
|
// MastodonController.swift
|
|
// Tusker
|
|
//
|
|
// Created by Shadowfacts on 8/15/18.
|
|
// Copyright © 2018 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
import Pachyderm
|
|
|
|
class MastodonController {
|
|
|
|
static var client: Client!
|
|
|
|
static var account: Account!
|
|
static var instance: Instance!
|
|
|
|
private init() {}
|
|
|
|
static func createClient() {
|
|
guard let url = LocalData.shared.instanceURL else { fatalError("Can't connect without instance URL") }
|
|
|
|
client = Client(baseURL: url)
|
|
|
|
client.clientID = LocalData.shared.clientID
|
|
client.clientSecret = LocalData.shared.clientSecret
|
|
client.accessToken = LocalData.shared.accessToken
|
|
}
|
|
|
|
static func registerApp(completion: @escaping () -> Void) {
|
|
guard LocalData.shared.clientID == nil,
|
|
LocalData.shared.clientSecret == nil else {
|
|
completion()
|
|
return
|
|
}
|
|
|
|
client.registerApp(name: "Tusker", redirectURI: "tusker://oauth", scopes: [.read, .write, .follow]) { response in
|
|
guard case let .success(app, _) = response else { fatalError() }
|
|
LocalData.shared.clientID = app.clientID
|
|
LocalData.shared.clientSecret = app.clientSecret
|
|
completion()
|
|
}
|
|
}
|
|
|
|
static func authorize(authorizationCode: String, completion: @escaping () -> Void) {
|
|
client.getAccessToken(authorizationCode: authorizationCode, redirectURI: "tusker://oauth") { response in
|
|
guard case let .success(settings, _) = response else { fatalError() }
|
|
LocalData.shared.accessToken = settings.accessToken
|
|
completion()
|
|
}
|
|
}
|
|
|
|
static func getOwnAccount(completion: ((Account) -> Void)? = nil) {
|
|
if account != nil {
|
|
completion?(account)
|
|
} else {
|
|
let request = client.getSelfAccount()
|
|
client.run(request) { response in
|
|
guard case let .success(account, _) = response else { fatalError() }
|
|
self.account = account
|
|
MastodonCache.add(account: account)
|
|
completion?(account)
|
|
}
|
|
}
|
|
}
|
|
|
|
static func getOwnInstance() {
|
|
let request = client.getInstance()
|
|
client.run(request) { (response) in
|
|
guard case let .success(instance, _) = response else { fatalError() }
|
|
self.instance = instance
|
|
}
|
|
}
|
|
|
|
}
|