88 lines
2.8 KiB
Swift
88 lines
2.8 KiB
Swift
//
|
|
// MastodonController.swift
|
|
// Tusker
|
|
//
|
|
// Created by Shadowfacts on 8/15/18.
|
|
// Copyright © 2018 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
import Pachyderm
|
|
|
|
class MastodonController {
|
|
|
|
@available(*, deprecated, message: "Use dependency injection to obtain an instance")
|
|
static let shared = MastodonController()
|
|
|
|
private(set) lazy var cache = MastodonCache(mastodonController: self)
|
|
|
|
private var client: Client!
|
|
|
|
var account: Account!
|
|
var instance: Instance!
|
|
|
|
var accessToken: String? {
|
|
client?.accessToken
|
|
}
|
|
|
|
func createClient(instanceURL: URL = LocalData.shared.instanceURL!) {
|
|
client = Client(baseURL: instanceURL)
|
|
|
|
if instanceURL == LocalData.shared.instanceURL {
|
|
client.clientID = LocalData.shared.clientID
|
|
client.clientSecret = LocalData.shared.clientSecret
|
|
client.accessToken = LocalData.shared.accessToken
|
|
}
|
|
}
|
|
|
|
func run<Result>(_ request: Request<Result>, completion: @escaping Client.Callback<Result>) {
|
|
client.run(request, completion: completion)
|
|
}
|
|
|
|
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()
|
|
}
|
|
}
|
|
|
|
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()
|
|
}
|
|
}
|
|
|
|
func getOwnAccount(completion: ((Account) -> Void)? = nil) {
|
|
if account != nil {
|
|
completion?(account)
|
|
} else {
|
|
let request = Client.getSelfAccount()
|
|
run(request) { response in
|
|
guard case let .success(account, _) = response else { fatalError() }
|
|
self.account = account
|
|
self.cache.add(account: account)
|
|
completion?(account)
|
|
}
|
|
}
|
|
}
|
|
|
|
func getOwnInstance() {
|
|
let request = Client.getInstance()
|
|
run(request) { (response) in
|
|
guard case let .success(instance, _) = response else { fatalError() }
|
|
self.instance = instance
|
|
}
|
|
}
|
|
|
|
}
|