IceCubes/IceCubesApp/App/AppAccounts/AppAccountsManager.swift

54 lines
1.7 KiB
Swift
Raw Normal View History

2022-12-01 09:05:26 +01:00
import SwiftUI
import Network
2023-01-08 10:22:52 +01:00
import Env
2022-12-01 09:05:26 +01:00
class AppAccountsManager: ObservableObject {
2022-12-30 08:36:22 +01:00
@AppStorage("latestCurrentAccountKey") static public var latestCurrentAccountKey: String = ""
2022-12-01 09:05:26 +01:00
@Published var currentAccount: AppAccount {
didSet {
2022-12-30 08:36:22 +01:00
Self.latestCurrentAccountKey = currentAccount.id
2022-12-01 09:05:26 +01:00
currentClient = .init(server: currentAccount.server,
oauthToken: currentAccount.oauthToken)
}
}
2022-12-29 07:00:00 +01:00
@Published var availableAccounts: [AppAccount]
2022-12-01 09:05:26 +01:00
@Published var currentClient: Client
2023-01-08 14:16:43 +01:00
var pushAccounts: [PushNotificationsService.PushAccounts] {
2023-01-08 10:22:52 +01:00
availableAccounts.filter{ $0.oauthToken != nil}
.map{ .init(server: $0.server, token: $0.oauthToken!) }
}
static var shared = AppAccountsManager()
private init() {
2022-12-01 09:05:26 +01:00
var defaultAccount = AppAccount(server: IceCubesApp.defaultServer, oauthToken: nil)
2023-01-08 10:22:52 +01:00
let keychainAccounts = AppAccount.retrieveAll()
availableAccounts = keychainAccounts
if let currentAccount = keychainAccounts.first(where: { $0.id == Self.latestCurrentAccountKey }) {
defaultAccount = currentAccount
} else {
defaultAccount = keychainAccounts.last ?? defaultAccount
2022-12-30 08:36:22 +01:00
}
2022-12-01 09:05:26 +01:00
currentAccount = defaultAccount
currentClient = .init(server: defaultAccount.server, oauthToken: defaultAccount.oauthToken)
}
func add(account: AppAccount) {
do {
try account.save()
2022-12-30 08:36:22 +01:00
availableAccounts.append(account)
2022-12-30 08:58:32 +01:00
currentAccount = account
2022-12-01 09:05:26 +01:00
} catch { }
}
func delete(account: AppAccount) {
2022-12-30 08:36:22 +01:00
availableAccounts.removeAll(where: { $0.id == account.id })
2022-12-01 09:05:26 +01:00
account.delete()
2022-12-30 08:36:22 +01:00
if currentAccount.id == account.id {
currentAccount = availableAccounts.first ?? AppAccount(server: IceCubesApp.defaultServer, oauthToken: nil)
}
2022-12-01 09:05:26 +01:00
}
}