oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import Observation
3import RastrilloApple
4
5/// The app's state above any one screen: the paired team, if any, its
6/// session, and pairing when there is none; and its pushes: permission is
7/// asked once there is a team, never before, and the registration follows
8/// the session.
9@MainActor @Observable
10public final class EquipoAppModel {
11 public let accounts: DeviceAccounts
12 public private(set) var session: EquipoSession?
13 public let pairing: PairingModel
14 public let oficina: EquipoOficinaID
15 public private(set) var showingPairing: Bool
16 private var started = false
17 private var isForeground = false
18 private var endingSession = false
19 private let makeTransport: @Sendable (URL) -> EquipoTransport
20 /// Set when the server ended the session, so pairing can say why.
21 public private(set) var endedTeam: String?
22 /// Where a tapped notification or Live Activity asked to go, until the
23 /// screens have gone there.
24 public var destination: Destination?
25 let notificationActions = NotificationDispatcher.live()
26
27 @ObservationIgnored public let push: PushRegistrar
28 @ObservationIgnored let notifications: NotificationSystem?
29 #if os(iOS)
30 @ObservationIgnored public let liveActivities: LiveActivities
31 #endif
32
33 public init(store: SecretStore = KeychainSecretStore(), notifications: NotificationSystem? = nil,
34 push: PushRegistrar = PushRegistrar(), oficinaModel: OficinaIDModel? = nil,
35 makeTransport: @escaping @Sendable (URL) -> EquipoTransport = { URLSessionTransport(origin: $0) },
36 now: @escaping @Sendable () -> Date = Date.init, deviceLabel: (() -> String)? = nil) {
37 self.makeTransport = makeTransport
38 accounts = DeviceAccounts(store: store)
39 pairing = PairingModel(accounts: accounts, makeTransport: makeTransport)
40 let old = accounts.all().first { $0.oficinaIdentity == nil && $0.isUsable() }
41 let route = accounts.signInRoute
42 showingPairing = route.map { $0 == "pairing" } ?? (old != nil)
43 oficina = EquipoOficinaID(model: oficinaModel ?? .live(configuration: EquipoOficinaID.configuration,
44 appGroup: EquipoOficinaID.appGroup),
45 accounts: accounts, makeTransport: makeTransport, now: now,
46 label: deviceLabel ?? { PairingView.deviceLabel })
47 self.notifications = notifications
48 self.push = push
49 #if os(iOS)
50 liveActivities = LiveActivities(registrar: push)
51 #endif
52 notificationActions.onRoute = { [weak self] route in self?.open(route) }
53 oficina.suspended = showingPairing
54 oficina.onAccount = { [weak self] account, transport, lifetime in self?.adopt(account, transport: transport, lifetime: lifetime) }
55 oficina.onLeave = { [weak self] in
56 guard let self, !self.showingPairing else { return }
57 self.sessionEnded(serverEnded: false)
58 }
59 if showingPairing, let account = old {
60 // Written again so a slice 1 credential becomes readable after
61 // first unlock, for Live Activity tokens sent in the background.
62 try? accounts.commit(.save(account), lifetime: accounts.lifetimes.current)
63 session = EquipoSession(account: account, accounts: accounts, transport: makeTransport(account.origin))
64 sessionStarted()
65 }
66 }
67
68 public var needsPairing: Bool { session == nil || session?.status == .signedOut }
69
70 public func start() async {
71 guard !started else { return }
72 started = true
73 await oficina.start()
74 }
75
76 /// The view's task cancels this clock when its scene goes away. A scene
77 /// that stays open still renews daily, without waiting for a foreground.
78 public func runRenewals(sleep: @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }) async {
79 await start()
80 while !Task.isCancelled {
81 do { try await sleep(.seconds(24 * 60 * 60)) } catch { return }
82 await oficina.renewIfNeeded()
83 }
84 }
85
86 public func otherWays() {
87 showingPairing = true
88 oficina.pause()
89 session?.invalidate(); session = nil
90 pairing.cancel()
91 let lifetime = accounts.lifetimes.begin()
92 try? accounts.commit(.route("pairing"), lifetime: lifetime)
93 forgetPushes()
94 }
95
96 public func useOficinaID() async {
97 showingPairing = false
98 pairing.cancel()
99 await oficina.resume()
100 }
101
102 /// After pairing approves this device.
103 public func paired() {
104 guard let account = pairing.account, let lifetime = pairing.handoff() else { return }
105 adopt(account, transport: makeTransport(account.origin), lifetime: lifetime)
106 foreground()
107 }
108
109 func adopt(_ account: DeviceAccount, transport: EquipoTransport? = nil, lifetime: SignInLifetime? = nil) {
110 let lifetime = lifetime ?? (session == nil ? accounts.lifetimes.current : accounts.lifetimes.begin())
111 guard lifetime.isActive else { return }
112 endedTeam = nil
113 if let session, session.lifetime === lifetime, !session.isInvalidated, account.oficinaIdentity != nil,
114 session.account.oficinaIdentity == account.oficinaIdentity,
115 session.account.oficinaTeam == account.oficinaTeam, session.origin == account.origin, let transport {
116 session.renew(account, transport: transport)
117 } else {
118 session?.invalidate()
119 session = EquipoSession(account: account, accounts: accounts, transport: transport, lifetime: lifetime)
120 }
121 sessionStarted()
122 }
123
124 /// There is a team: ask to notify (the system asks once), register with
125 /// APNs, and register this device with the team's server.
126 private func sessionStarted() {
127 if isForeground { session?.startLive() }
128 notifications?.askAndRegister()
129 guard let session else { return }
130 notificationActions.attach(session: session, selection: accounts.notificationSelection)
131 let client = session.client, lifetime = session.lifetime
132 let push = self.push
133 let bindingID = accounts.notificationSelection?.id
134 Task {
135 guard lifetime.isActive else { return }
136 await push.attach(client, lifetime: lifetime, bindingID: bindingID)
137 }
138 }
139
140 /// Leave the conversation. Only a server-ended session names the team
141 /// in the pairing notice; kit sign-out and replacement are local choices.
142 public func sessionEnded(serverEnded: Bool = true) {
143 guard !endingSession else { return }
144 endingSession = true
145 defer { endingSession = false }
146 let departing = session
147 endedTeam = serverEnded ? departing?.teamName : nil
148 session = nil
149 // Remove through the still-current lifetime before ending it. The
150 // coordinator's onLeave can call back here; session is already nil.
151 if let departing, departing.account.oficinaIdentity != nil { oficina.sessionEnded(lifetime: departing.lifetime) }
152 departing?.invalidate()
153 pairing.cancel()
154 forgetPushes()
155 }
156
157 public func signOut() async {
158 if session?.account.oficinaIdentity != nil || !showingPairing {
159 oficina.signOut()
160 return
161 }
162 let departing = session
163 session = nil
164 endedTeam = nil
165 pairing.cancel()
166 if departing == nil { accounts.lifetimes.current.end() }
167 forgetPushes()
168 await departing?.signOut()
169 }
170
171 /// No team: nothing more is registered, no badge, no task on the Lock Screen.
172 private func forgetPushes() {
173 notificationActions.clear()
174 let push = self.push
175 Task { [weak self] in
176 guard self?.session == nil else { return }
177 await push.attach(nil)
178 }
179 notifications?.setBadge(0)
180 // Even if the server never heard of the sign-out, this device stops
181 // receiving the team's notifications; pairing again registers anew.
182 notifications?.unregister()
183 #if os(iOS)
184 let live = liveActivities
185 Task { await live.endAll() }
186 #endif
187 }
188
189 public func notificationResponse(_ response: NotificationResponse) {
190 Task { await notificationActions.receive(response) }
191 }
192 public func notificationBindingChanged() {
193 guard let session else { return }
194 notificationActions.attach(session: session, selection: accounts.notificationSelection)
195 let binding = accounts.notificationSelection?.id
196 Task { await push.attach(session.client, lifetime: session.lifetime, bindingID: binding) }
197 }
198
199 /// Where a tapped notification or Live Activity goes.
200 public func open(_ route: PushRoute) { destination = route.destination }
201
202 /// The app badge is the Needs you count, once known: unknown is not zero.
203 public func needsYouChanged(_ count: Int?) {
204 guard let count, session != nil else { return }
205 notifications?.setBadge(count)
206 }
207
208 public func foreground() {
209 isForeground = true
210 if let session {
211 session.previews.checkExpiry()
212 Task { await session.previews.foreground(client: session.client) }
213 }
214 NativeConnectivity.shared.foregrounded()
215 let push = self.push
216 Task { await push.sync() }
217 let lifetime = accounts.lifetimes.current
218 Task {
219 await start()
220 guard lifetime.isActive else { return }
221 await oficina.renewIfNeeded()
222 guard lifetime.isActive else { return }
223 if isForeground { session?.startLive() }
224 }
225 }
226 public func background() { isForeground = false; session?.previews.background(); session?.stopLive() }
227}
228