import Foundation import Observation import RastrilloApple /// The app's state above any one screen: the paired team, if any, its /// session, and pairing when there is none; and its pushes: permission is /// asked once there is a team, never before, and the registration follows /// the session. @MainActor @Observable public final class EquipoAppModel { public let accounts: DeviceAccounts public private(set) var session: EquipoSession? public let pairing: PairingModel public let oficina: EquipoOficinaID public private(set) var showingPairing: Bool private var started = false private var isForeground = false private var endingSession = false private let makeTransport: @Sendable (URL) -> EquipoTransport /// Set when the server ended the session, so pairing can say why. public private(set) var endedTeam: String? /// Where a tapped notification or Live Activity asked to go, until the /// screens have gone there. public var destination: Destination? let notificationActions = NotificationDispatcher.live() @ObservationIgnored public let push: PushRegistrar @ObservationIgnored let notifications: NotificationSystem? #if os(iOS) @ObservationIgnored public let liveActivities: LiveActivities #endif public init(store: SecretStore = KeychainSecretStore(), notifications: NotificationSystem? = nil, push: PushRegistrar = PushRegistrar(), oficinaModel: OficinaIDModel? = nil, makeTransport: @escaping @Sendable (URL) -> EquipoTransport = { URLSessionTransport(origin: $0) }, now: @escaping @Sendable () -> Date = Date.init, deviceLabel: (() -> String)? = nil) { self.makeTransport = makeTransport accounts = DeviceAccounts(store: store) pairing = PairingModel(accounts: accounts, makeTransport: makeTransport) let old = accounts.all().first { $0.oficinaIdentity == nil && $0.isUsable() } let route = accounts.signInRoute showingPairing = route.map { $0 == "pairing" } ?? (old != nil) oficina = EquipoOficinaID(model: oficinaModel ?? .live(configuration: EquipoOficinaID.configuration, appGroup: EquipoOficinaID.appGroup), accounts: accounts, makeTransport: makeTransport, now: now, label: deviceLabel ?? { PairingView.deviceLabel }) self.notifications = notifications self.push = push #if os(iOS) liveActivities = LiveActivities(registrar: push) #endif notificationActions.onRoute = { [weak self] route in self?.open(route) } oficina.suspended = showingPairing oficina.onAccount = { [weak self] account, transport, lifetime in self?.adopt(account, transport: transport, lifetime: lifetime) } oficina.onLeave = { [weak self] in guard let self, !self.showingPairing else { return } self.sessionEnded(serverEnded: false) } if showingPairing, let account = old { // Written again so a slice 1 credential becomes readable after // first unlock, for Live Activity tokens sent in the background. try? accounts.commit(.save(account), lifetime: accounts.lifetimes.current) session = EquipoSession(account: account, accounts: accounts, transport: makeTransport(account.origin)) sessionStarted() } } public var needsPairing: Bool { session == nil || session?.status == .signedOut } public func start() async { guard !started else { return } started = true await oficina.start() } /// The view's task cancels this clock when its scene goes away. A scene /// that stays open still renews daily, without waiting for a foreground. public func runRenewals(sleep: @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }) async { await start() while !Task.isCancelled { do { try await sleep(.seconds(24 * 60 * 60)) } catch { return } await oficina.renewIfNeeded() } } public func otherWays() { showingPairing = true oficina.pause() session?.invalidate(); session = nil pairing.cancel() let lifetime = accounts.lifetimes.begin() try? accounts.commit(.route("pairing"), lifetime: lifetime) forgetPushes() } public func useOficinaID() async { showingPairing = false pairing.cancel() await oficina.resume() } /// After pairing approves this device. public func paired() { guard let account = pairing.account, let lifetime = pairing.handoff() else { return } adopt(account, transport: makeTransport(account.origin), lifetime: lifetime) foreground() } func adopt(_ account: DeviceAccount, transport: EquipoTransport? = nil, lifetime: SignInLifetime? = nil) { let lifetime = lifetime ?? (session == nil ? accounts.lifetimes.current : accounts.lifetimes.begin()) guard lifetime.isActive else { return } endedTeam = nil if let session, session.lifetime === lifetime, !session.isInvalidated, account.oficinaIdentity != nil, session.account.oficinaIdentity == account.oficinaIdentity, session.account.oficinaTeam == account.oficinaTeam, session.origin == account.origin, let transport { session.renew(account, transport: transport) } else { session?.invalidate() session = EquipoSession(account: account, accounts: accounts, transport: transport, lifetime: lifetime) } sessionStarted() } /// There is a team: ask to notify (the system asks once), register with /// APNs, and register this device with the team's server. private func sessionStarted() { if isForeground { session?.startLive() } notifications?.askAndRegister() guard let session else { return } notificationActions.attach(session: session, selection: accounts.notificationSelection) let client = session.client, lifetime = session.lifetime let push = self.push let bindingID = accounts.notificationSelection?.id Task { guard lifetime.isActive else { return } await push.attach(client, lifetime: lifetime, bindingID: bindingID) } } /// Leave the conversation. Only a server-ended session names the team /// in the pairing notice; kit sign-out and replacement are local choices. public func sessionEnded(serverEnded: Bool = true) { guard !endingSession else { return } endingSession = true defer { endingSession = false } let departing = session endedTeam = serverEnded ? departing?.teamName : nil session = nil // Remove through the still-current lifetime before ending it. The // coordinator's onLeave can call back here; session is already nil. if let departing, departing.account.oficinaIdentity != nil { oficina.sessionEnded(lifetime: departing.lifetime) } departing?.invalidate() pairing.cancel() forgetPushes() } public func signOut() async { if session?.account.oficinaIdentity != nil || !showingPairing { oficina.signOut() return } let departing = session session = nil endedTeam = nil pairing.cancel() if departing == nil { accounts.lifetimes.current.end() } forgetPushes() await departing?.signOut() } /// No team: nothing more is registered, no badge, no task on the Lock Screen. private func forgetPushes() { notificationActions.clear() let push = self.push Task { [weak self] in guard self?.session == nil else { return } await push.attach(nil) } notifications?.setBadge(0) // Even if the server never heard of the sign-out, this device stops // receiving the team's notifications; pairing again registers anew. notifications?.unregister() #if os(iOS) let live = liveActivities Task { await live.endAll() } #endif } public func notificationResponse(_ response: NotificationResponse) { Task { await notificationActions.receive(response) } } public func notificationBindingChanged() { guard let session else { return } notificationActions.attach(session: session, selection: accounts.notificationSelection) let binding = accounts.notificationSelection?.id Task { await push.attach(session.client, lifetime: session.lifetime, bindingID: binding) } } /// Where a tapped notification or Live Activity goes. public func open(_ route: PushRoute) { destination = route.destination } /// The app badge is the Needs you count, once known: unknown is not zero. public func needsYouChanged(_ count: Int?) { guard let count, session != nil else { return } notifications?.setBadge(count) } public func foreground() { isForeground = true if let session { session.previews.checkExpiry() Task { await session.previews.foreground(client: session.client) } } NativeConnectivity.shared.foregrounded() let push = self.push Task { await push.sync() } let lifetime = accounts.lifetimes.current Task { await start() guard lifetime.isActive else { return } await oficina.renewIfNeeded() guard lifetime.isActive else { return } if isForeground { session?.startLive() } } } public func background() { isForeground = false; session?.previews.background(); session?.stopLive() } }