1
0
mirror of https://github.com/yattee/yattee.git synced 2024-12-14 06:10:32 +05:30
yattee/Model/Accounts/AccountsModel.swift

90 lines
2.1 KiB
Swift
Raw Normal View History

2021-10-17 04:18:58 +05:30
import Combine
import Defaults
import Foundation
final class AccountsModel: ObservableObject {
2021-10-21 03:51:50 +05:30
@Published private(set) var current: Account!
2021-10-17 04:18:58 +05:30
2021-10-21 03:51:50 +05:30
@Published private var invidious = InvidiousAPI()
@Published private var piped = PipedAPI()
2021-10-17 04:18:58 +05:30
private var cancellables = [AnyCancellable]()
2021-10-21 03:51:50 +05:30
var all: [Account] {
Defaults[.accounts]
}
2021-10-21 03:51:50 +05:30
var lastUsed: Account? {
guard let id = Defaults[.lastAccountID] else {
return nil
}
return AccountsModel.find(id)
2021-10-17 04:18:58 +05:30
}
2021-10-21 03:51:50 +05:30
var app: VideosApp {
current?.instance.app ?? .invidious
}
var api: VideosAPI {
app == .piped ? piped : invidious
}
2021-10-18 04:36:00 +05:30
var isEmpty: Bool {
current.isNil
2021-10-18 04:36:00 +05:30
}
2021-10-17 04:18:58 +05:30
var signedIn: Bool {
!isEmpty && !current.anonymous
2021-10-17 04:18:58 +05:30
}
init() {
cancellables.append(
invidious.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() }
)
cancellables.append(
piped.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() }
)
}
2021-10-21 03:51:50 +05:30
func setCurrent(_ account: Account! = nil) {
guard account != current else {
2021-10-17 04:18:58 +05:30
return
}
current = account
2021-10-17 04:18:58 +05:30
2021-10-18 04:36:00 +05:30
guard !account.isNil else {
return
}
2021-10-17 04:18:58 +05:30
switch account.instance.app {
case .invidious:
invidious.setAccount(account)
case .piped:
piped.setAccount(account)
}
Defaults[.lastAccountID] = account.anonymous ? nil : account.id
Defaults[.lastInstanceID] = account.instanceID
}
2021-10-21 03:51:50 +05:30
static func find(_ id: Account.ID) -> Account? {
Defaults[.accounts].first { $0.id == id }
}
2021-10-21 03:51:50 +05:30
static func add(instance: Instance, name: String, sid: String) -> Account {
2021-10-28 02:41:38 +05:30
let account = Account(instanceID: instance.id, name: name, url: instance.apiURL, sid: sid)
Defaults[.accounts].append(account)
return account
}
2021-10-21 03:51:50 +05:30
static func remove(_ account: Account) {
if let accountIndex = Defaults[.accounts].firstIndex(where: { $0.id == account.id }) {
Defaults[.accounts].remove(at: accountIndex)
}
2021-10-17 04:18:58 +05:30
}
}