Files
Thorgathis acd50280bc Yandex Music client for Apple TV
tvOS 17+ SwiftUI client for the unofficial Yandex Music API: rotor stations
with feedback, library, search, artist and album pages, synced lyrics, and
system Now Playing integration.
2026-09-17 20:38:19 +03:00

52 lines
1.5 KiB
Swift

import Foundation
import SwiftUI
@MainActor
final class AppState: ObservableObject {
@Published var token: String?
@Published var accountName: String = ""
@Published var isBooting = true
var isAuthorized: Bool { token != nil }
init() {
token = Keychain.get("token")
}
func boot() async {
isBooting = true
defer { isBooting = false }
guard let token else { return }
await YMClient.shared.setToken(token)
do {
let status = try await YMClient.shared.accountStatus()
accountName = status.account.displayName
?? status.account.fullName
?? status.account.login
?? "Аккаунт"
await PlayerController.shared.refreshLikes()
} catch {
log.error("boot: \(error.localizedDescription)")
// A dead token should not trap the user on a broken screen.
if case let YMError.http(status, _) = error, status == 401 || status == 403 {
signOut()
}
}
}
func signIn(with token: String) async {
let trimmed = token.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
Keychain.set(trimmed, for: "token")
self.token = trimmed
await boot()
}
func signOut() {
Keychain.set(nil, for: "token")
token = nil
accountName = ""
Task { await YMClient.shared.setToken(nil) }
}
}