Tusker/Tusker/Controllers/MastodonController.swift

75 lines
2.4 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()
var userDefaults = UserDefaults()
2018-08-16 11:46:19 +00:00
var client: Client!
2018-08-17 00:11:56 +00:00
lazy var clientID: String? = self.userDefaults.string(forKey: "clientID")
lazy var clientSecret: String? = self.userDefaults.string(forKey: "clientSecret")
lazy var accessToken: String? = self.userDefaults.string(forKey: "accessToken")
2018-08-16 22:55:40 +00:00
2018-08-16 11:46:19 +00:00
private init() {
}
2018-08-16 22:55:40 +00:00
func connect() {
2018-08-16 11:46:19 +00:00
let url = ProcessInfo.processInfo.environment["mastodon_url"]!
2018-08-17 00:11:56 +00:00
if let accessToken = accessToken {
client = Client(baseURL: url, accessToken: accessToken)
} else {
client = Client(baseURL: url)
2018-08-16 22:55:40 +00:00
2018-08-17 00:11:56 +00:00
login()
2018-08-16 22:55:40 +00:00
}
}
private func register(completion: @escaping () -> Void) {
2018-08-17 00:11:56 +00:00
if clientID != nil,
clientSecret != nil {
2018-08-16 22:55:40 +00:00
completion()
2018-08-17 00:11:56 +00:00
} else {
let registerRequest = Clients.register(clientName: "Tusker", scopes: [.read, .write, .follow])
client.run(registerRequest) { result in
guard case let .success(application, _) = result else { fatalError() }
self.clientID = application.clientID
self.clientSecret = application.clientSecret
self.userDefaults.set(self.clientID, forKey: "clientID")
self.userDefaults.set(self.clientSecret, forKey: "clientSecret")
completion()
}
2018-08-16 22:55:40 +00:00
}
2018-08-17 00:11:56 +00:00
}
private func login() {
// TODO: OAuth
let username = ProcessInfo.processInfo.environment["mastodon_username"]!
let password = ProcessInfo.processInfo.environment["mastodon_password"]!
2018-08-16 22:55:40 +00:00
2018-08-17 00:11:56 +00:00
register() {
let loginReq = Login.silent(clientID: self.clientID!, clientSecret: self.clientSecret!, scopes: [.read, .write, .follow], username: username, password: password)
self.client.run(loginReq) { result in
guard case let .success(loginSettings, _) = result else { fatalError() }
self.accessToken = loginSettings.accessToken
self.userDefaults.set(self.accessToken, forKey: "accessToken")
}
2018-08-16 11:46:19 +00:00
}
}
}