oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2
3/// Keeps the server's push registration for this device current: the APNs
4/// token, its gateway, and on iPhone the Live Activity push-to-start token,
5/// sent with the paired device's bearer; then each running Live Activity's
6/// own token. Something is sent again when it changes, when another team's
7/// session takes over, or after it could not be sent (on the next `sync`,
8/// when the app comes to the front). Tokens are never logged.
9@MainActor
10public final class PushRegistrar {
11 public let environment: APNsEnvironment?
12 public let platform: PushPlatform
13 public private(set) var deviceToken: String?
14 public private(set) var startToken: String?
15
16 private var bindingID: String?
17 private var actionsEnabled = false
18 private var capabilityRead = false
19 private var client: EquipoClient?
20 private var lifetime: SignInLifetime?
21 /// The registration the current session's server has, by bearer.
22 private var accepted: (bearer: String, body: PushRegistrationBody)?
23 /// A registration the server refused as invalid: not sent again as is.
24 private var refused: (bearer: String, body: PushRegistrationBody)?
25 /// Each running Live Activity's token, by task, with the origin of the
26 /// instance that started it; and which of them the current session's
27 /// server has. A token goes only to the account at its own origin.
28 private var activities: [String: (origin: String, token: String)] = [:]
29 private var acceptedActivities: [String: String] = [:]
30 /// Tasks the server says are over or not this person's: their tokens are not sent again.
31 private var closedActivities: [String: String] = [:]
32 private var running = false
33 private var again = false
34 /// Moves on with every change of session: a pass that was waiting on the
35 /// network when the session changed sends nothing more and records nothing.
36 public private(set) var generation = 0
37 /// Called when the session changes, so activity observers deliver
38 /// their tokens again for the new session.
39 public var onSessionChanged: (() -> Void)?
40 /// Called with a task whose activity the server will never take (it
41 /// ended, or is not this person's): the app ends it on this device.
42 public var onActivityClosed: ((String) -> Void)?
43
44 public init(environment: APNsEnvironment? = PushEnvironment.current, platform: PushPlatform = .current) {
45 self.environment = environment; self.platform = platform
46 }
47
48 /// The paired session's client, or nil once there is none. A new one
49 /// is a new credential: everything is registered with it again.
50 public func attach(_ client: EquipoClient?, lifetime: SignInLifetime? = nil, bindingID: String? = nil) async {
51 guard lifetime?.isActive != false else { return }
52 if client?.token != self.client?.token || lifetime !== self.lifetime || bindingID != self.bindingID {
53 actionsEnabled = false; capabilityRead = false
54 generation += 1
55 // Another session (another team, a new credential, or none): it
56 // keeps only the activities its own instance started. At launch
57 // that is every activity seen before the session was restored.
58 if let account = client?.origin {
59 activities = activities.filter { Self.same($0.value.origin, account) }
60 } else {
61 activities = [:]
62 }
63 acceptedActivities = [:]; closedActivities = [:]
64 self.client = client
65 onSessionChanged?()
66 }
67 self.client = client
68 self.lifetime = lifetime
69 self.bindingID = bindingID
70 await sync()
71 }
72
73 public func deviceTokenChanged(_ token: Data) async {
74 deviceToken = PushToken.hex(token)
75 await sync()
76 }
77 /// iPhone only: the token the server starts a Live Activity with.
78 public func startTokenChanged(_ token: Data) async {
79 guard platform == .ios else { return }
80 startToken = PushToken.hex(token)
81 await sync()
82 }
83 /// A running Live Activity's own token, for the server's updates, from
84 /// the instance at `origin` (the activity's attributes). An activity
85 /// that names no origin is never sent anywhere.
86 public func activityTokenChanged(_ token: Data, task: String, origin: String?) async {
87 guard let origin else { return }
88 activities[task] = (origin, PushToken.hex(token))
89 await sync()
90 }
91
92 /// Whether an activity's origin is this account's: scheme, host and port.
93 static func same(_ origin: String, _ account: URL) -> Bool {
94 guard let o = URL(string: origin), let scheme = o.scheme?.lowercased(), let host = o.host?.lowercased() else { return false }
95 return scheme == account.scheme?.lowercased() && host == account.host?.lowercased() && o.port == account.port
96 }
97 /// The activity ended on this device: nothing more to send for it.
98 public func activityEnded(task: String) {
99 activities[task] = nil; acceptedActivities[task] = nil; closedActivities[task] = nil
100 }
101
102 /// The registration this device needs: none before the APNs token, or
103 /// when this build cannot receive pushes at all.
104 public var body: PushRegistrationBody? {
105 guard let deviceToken, let environment else { return nil }
106 var result = PushRegistrationBody(token: deviceToken, environment: environment, platform: platform, startToken: startToken)
107 if actionsEnabled, let bindingID { result.actionsVersion = 1; result.bindingId = bindingID }
108 return result
109 }
110
111 /// Sends whatever the server does not have yet. One pass at a time; a
112 /// change during a pass is sent by one more pass after it.
113 public func sync() async {
114 if running { again = true; return }
115 running = true
116 defer { running = false }
117 repeat {
118 again = false
119 await pass()
120 } while again
121 }
122
123 private func pass() async {
124 let lifetime = self.lifetime
125 guard lifetime?.isActive != false, let client, let bearer = client.token else { return }
126 let generation = self.generation
127 if !capabilityRead, let bindingID, NotificationBinding.uuid(bindingID) {
128 let enabled = (try? await client.notificationActionsEnabled()) == true
129 guard lifetime?.isActive != false, generation == self.generation else { return }
130 actionsEnabled = enabled; capabilityRead = true
131 }
132 if let body, !(accepted?.bearer == bearer && accepted?.body == body), !(refused?.bearer == bearer && refused?.body == body) {
133 do {
134 let write = try PendingWrite.json(body)
135 _ = try await client.registerPush(write)
136 guard lifetime?.isActive != false, generation == self.generation else { return }
137 accepted = (bearer, body)
138 } catch let error as EquipoAPIError {
139 guard lifetime?.isActive != false, generation == self.generation else { return }
140 if error.status == 403, body.actionsVersion == 1 {
141 let enabled = try? await client.notificationActionsEnabled()
142 guard lifetime?.isActive != false, generation == self.generation else { return }
143 if enabled == false {
144 actionsEnabled = false; capabilityRead = true; again = true
145 }
146 return
147 }
148 // A refusal is final for this body; anything else waits for the next sync.
149 if let status = error.status, status == 400 || status == 422 { refused = (bearer, body) }
150 return
151 } catch { return }
152 }
153 // Activity tokens need the device's registration first.
154 guard accepted?.bearer == bearer else { return }
155 for (task, token) in activities.sorted(by: { $0.key < $1.key })
156 .filter({ Self.same($0.value.origin, client.origin) }).map({ ($0.key, $0.value.token) })
157 where acceptedActivities[task] != token && closedActivities[task] != token {
158 guard lifetime?.isActive != false, generation == self.generation else { return }
159 do {
160 try await client.registerActivity(try PendingWrite.json(ActivityTokenBody(taskId: task, token: token)))
161 guard lifetime?.isActive != false, generation == self.generation else { return }
162 acceptedActivities[task] = token
163 } catch let error as EquipoAPIError {
164 guard lifetime?.isActive != false, generation == self.generation else { return }
165 // Ended, or not this person's task: the server will never take it,
166 // and the activity ends here too.
167 if error.status == 404 || error.status == 409 || error.status == 400 {
168 closedActivities[task] = token
169 onActivityClosed?(task)
170 }
171 else { return }
172 } catch { return }
173 }
174 }
175}
176