IceCubesApp/Packages/AppAccount/Sources/AppAccount/AppAccountsManager.swift

58 lines
1.8 KiB
Swift
Raw Normal View History

2023-01-08 09:22:52 +00:00
import Env
import Models
2023-01-17 10:36:01 +00:00
import Network
import SwiftUI
2022-12-01 08:05:26 +00:00
@MainActor
public class AppAccountsManager: ObservableObject {
@AppStorage("latestCurrentAccountKey", store: UserPreferences.sharedDefault)
2023-01-17 10:36:01 +00:00
public static var latestCurrentAccountKey: String = ""
@Published public var currentAccount: AppAccount {
2022-12-01 08:05:26 +00:00
didSet {
2022-12-30 07:36:22 +00:00
Self.latestCurrentAccountKey = currentAccount.id
2022-12-01 08:05:26 +00:00
currentClient = .init(server: currentAccount.server,
oauthToken: currentAccount.oauthToken)
}
}
2023-01-17 10:36:01 +00:00
@Published public var availableAccounts: [AppAccount]
@Published public var currentClient: Client
2023-01-17 10:36:01 +00:00
public var pushAccounts: [PushNotificationsService.PushAccounts] {
2023-01-17 10:36:01 +00:00
availableAccounts.filter { $0.oauthToken != nil }
.map { .init(server: $0.server, token: $0.oauthToken!) }
2023-01-08 09:22:52 +00:00
}
2023-01-17 10:36:01 +00:00
public static var shared = AppAccountsManager()
2023-01-17 10:36:01 +00:00
internal init() {
var defaultAccount = AppAccount(server: AppInfo.defaultServer, oauthToken: nil)
2023-01-08 09:22:52 +00: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 07:36:22 +00:00
}
2022-12-01 08:05:26 +00:00
currentAccount = defaultAccount
currentClient = .init(server: defaultAccount.server, oauthToken: defaultAccount.oauthToken)
}
2023-01-17 10:36:01 +00:00
public func add(account: AppAccount) {
2022-12-01 08:05:26 +00:00
do {
try account.save()
2022-12-30 07:36:22 +00:00
availableAccounts.append(account)
2022-12-30 07:58:32 +00:00
currentAccount = account
2023-01-17 10:36:01 +00:00
} catch {}
2022-12-01 08:05:26 +00:00
}
2023-01-17 10:36:01 +00:00
public func delete(account: AppAccount) {
2022-12-30 07:36:22 +00:00
availableAccounts.removeAll(where: { $0.id == account.id })
2022-12-01 08:05:26 +00:00
account.delete()
2022-12-30 07:36:22 +00:00
if currentAccount.id == account.id {
currentAccount = availableAccounts.first ?? AppAccount(server: AppInfo.defaultServer, oauthToken: nil)
2022-12-30 07:36:22 +00:00
}
2022-12-01 08:05:26 +00:00
}
}