import Foundation /// Keeps the server's push registration for this device current: the APNs /// token, its gateway, and on iPhone the Live Activity push-to-start token, /// sent with the paired device's bearer; then each running Live Activity's /// own token. Something is sent again when it changes, when another team's /// session takes over, or after it could not be sent (on the next `sync`, /// when the app comes to the front). Tokens are never logged. @MainActor public final class PushRegistrar { public let environment: APNsEnvironment? public let platform: PushPlatform public private(set) var deviceToken: String? public private(set) var startToken: String? private var bindingID: String? private var actionsEnabled = false private var capabilityRead = false private var client: EquipoClient? private var lifetime: SignInLifetime? /// The registration the current session's server has, by bearer. private var accepted: (bearer: String, body: PushRegistrationBody)? /// A registration the server refused as invalid: not sent again as is. private var refused: (bearer: String, body: PushRegistrationBody)? /// Each running Live Activity's token, by task, with the origin of the /// instance that started it; and which of them the current session's /// server has. A token goes only to the account at its own origin. private var activities: [String: (origin: String, token: String)] = [:] private var acceptedActivities: [String: String] = [:] /// Tasks the server says are over or not this person's: their tokens are not sent again. private var closedActivities: [String: String] = [:] private var running = false private var again = false /// Moves on with every change of session: a pass that was waiting on the /// network when the session changed sends nothing more and records nothing. public private(set) var generation = 0 /// Called when the session changes, so activity observers deliver /// their tokens again for the new session. public var onSessionChanged: (() -> Void)? /// Called with a task whose activity the server will never take (it /// ended, or is not this person's): the app ends it on this device. public var onActivityClosed: ((String) -> Void)? public init(environment: APNsEnvironment? = PushEnvironment.current, platform: PushPlatform = .current) { self.environment = environment; self.platform = platform } /// The paired session's client, or nil once there is none. A new one /// is a new credential: everything is registered with it again. public func attach(_ client: EquipoClient?, lifetime: SignInLifetime? = nil, bindingID: String? = nil) async { guard lifetime?.isActive != false else { return } if client?.token != self.client?.token || lifetime !== self.lifetime || bindingID != self.bindingID { actionsEnabled = false; capabilityRead = false generation += 1 // Another session (another team, a new credential, or none): it // keeps only the activities its own instance started. At launch // that is every activity seen before the session was restored. if let account = client?.origin { activities = activities.filter { Self.same($0.value.origin, account) } } else { activities = [:] } acceptedActivities = [:]; closedActivities = [:] self.client = client onSessionChanged?() } self.client = client self.lifetime = lifetime self.bindingID = bindingID await sync() } public func deviceTokenChanged(_ token: Data) async { deviceToken = PushToken.hex(token) await sync() } /// iPhone only: the token the server starts a Live Activity with. public func startTokenChanged(_ token: Data) async { guard platform == .ios else { return } startToken = PushToken.hex(token) await sync() } /// A running Live Activity's own token, for the server's updates, from /// the instance at `origin` (the activity's attributes). An activity /// that names no origin is never sent anywhere. public func activityTokenChanged(_ token: Data, task: String, origin: String?) async { guard let origin else { return } activities[task] = (origin, PushToken.hex(token)) await sync() } /// Whether an activity's origin is this account's: scheme, host and port. static func same(_ origin: String, _ account: URL) -> Bool { guard let o = URL(string: origin), let scheme = o.scheme?.lowercased(), let host = o.host?.lowercased() else { return false } return scheme == account.scheme?.lowercased() && host == account.host?.lowercased() && o.port == account.port } /// The activity ended on this device: nothing more to send for it. public func activityEnded(task: String) { activities[task] = nil; acceptedActivities[task] = nil; closedActivities[task] = nil } /// The registration this device needs: none before the APNs token, or /// when this build cannot receive pushes at all. public var body: PushRegistrationBody? { guard let deviceToken, let environment else { return nil } var result = PushRegistrationBody(token: deviceToken, environment: environment, platform: platform, startToken: startToken) if actionsEnabled, let bindingID { result.actionsVersion = 1; result.bindingId = bindingID } return result } /// Sends whatever the server does not have yet. One pass at a time; a /// change during a pass is sent by one more pass after it. public func sync() async { if running { again = true; return } running = true defer { running = false } repeat { again = false await pass() } while again } private func pass() async { let lifetime = self.lifetime guard lifetime?.isActive != false, let client, let bearer = client.token else { return } let generation = self.generation if !capabilityRead, let bindingID, NotificationBinding.uuid(bindingID) { let enabled = (try? await client.notificationActionsEnabled()) == true guard lifetime?.isActive != false, generation == self.generation else { return } actionsEnabled = enabled; capabilityRead = true } if let body, !(accepted?.bearer == bearer && accepted?.body == body), !(refused?.bearer == bearer && refused?.body == body) { do { let write = try PendingWrite.json(body) _ = try await client.registerPush(write) guard lifetime?.isActive != false, generation == self.generation else { return } accepted = (bearer, body) } catch let error as EquipoAPIError { guard lifetime?.isActive != false, generation == self.generation else { return } if error.status == 403, body.actionsVersion == 1 { let enabled = try? await client.notificationActionsEnabled() guard lifetime?.isActive != false, generation == self.generation else { return } if enabled == false { actionsEnabled = false; capabilityRead = true; again = true } return } // A refusal is final for this body; anything else waits for the next sync. if let status = error.status, status == 400 || status == 422 { refused = (bearer, body) } return } catch { return } } // Activity tokens need the device's registration first. guard accepted?.bearer == bearer else { return } for (task, token) in activities.sorted(by: { $0.key < $1.key }) .filter({ Self.same($0.value.origin, client.origin) }).map({ ($0.key, $0.value.token) }) where acceptedActivities[task] != token && closedActivities[task] != token { guard lifetime?.isActive != false, generation == self.generation else { return } do { try await client.registerActivity(try PendingWrite.json(ActivityTokenBody(taskId: task, token: token))) guard lifetime?.isActive != false, generation == self.generation else { return } acceptedActivities[task] = token } catch let error as EquipoAPIError { guard lifetime?.isActive != false, generation == self.generation else { return } // Ended, or not this person's task: the server will never take it, // and the activity ends here too. if error.status == 404 || error.status == 409 || error.status == 400 { closedActivities[task] = token onActivityClosed?(task) } else { return } } catch { return } } } }