Open History to see the last commit
1@preconcurrency import UserNotifications
2import UIKit
3
4extension Notification.Name {
5 static let platformRouteReceived = Notification.Name("T3PlatformRouteReceived")
6 static let platformDeviceTokenChanged = Notification.Name("T3PlatformDeviceTokenChanged")
7}
8
9enum PlatformNotificationPayload {
10 private static let routeKeys = ["t3_route", "route", "url", "deep_link", "deeplink"]
11
12 static func route(from userInfo: [AnyHashable: Any]) -> PlatformRoute? {
13 for key in routeKeys {
14 if let value = value(named: key, in: userInfo),
15 let route = try? PlatformDeepLinkParser.parse(value) {
16 return route
17 }
18 }
19
20 let environmentID = value(named: "environment_id", in: userInfo)
21 ?? value(named: "environmentId", in: userInfo)
22 if let threadID = value(named: "thread_id", in: userInfo)
23 ?? value(named: "threadId", in: userInfo) {
24 return .thread(environmentID: environmentID, threadID: threadID)
25 }
26 if let projectID = value(named: "project_id", in: userInfo)
27 ?? value(named: "projectId", in: userInfo) {
28 return .project(environmentID: environmentID, projectID: projectID)
29 }
30 return nil
31 }
32
33 private static func value(named name: String, in userInfo: [AnyHashable: Any]) -> String? {
34 userInfo.first { key, _ in
35 String(describing: key).caseInsensitiveCompare(name) == .orderedSame
36 }.flatMap { _, value in
37 let string = value as? String
38 return string?.isEmpty == false ? string : nil
39 }
40 }
41}
42
43@MainActor
44protocol PlatformDeviceTokenSink: AnyObject {
45 func registered(token: String)
46 func registrationFailed(_ error: Error)
47 func invalidated()
48}
49
50/// Persists the APNs identity and publishes a seam for server registration.
51/// The environment client can subscribe without coupling UIApplicationDelegate to transport code.
52@MainActor
53final class PlatformPersistedDeviceTokenSink: PlatformDeviceTokenSink {
54 static let shared = PlatformPersistedDeviceTokenSink()
55
56 private let defaults: UserDefaults
57 private let key = "swift-ios.apns-device-token.v1"
58
59 init(defaults: UserDefaults = .standard) {
60 self.defaults = defaults
61 }
62
63 var currentToken: String? {
64 defaults.string(forKey: key)
65 }
66
67 func registered(token: String) {
68 defaults.set(token, forKey: key)
69 NotificationCenter.default.post(
70 name: .platformDeviceTokenChanged,
71 object: nil,
72 userInfo: ["token": token]
73 )
74 }
75
76 func registrationFailed(_ error: Error) {
77 NotificationCenter.default.post(
78 name: .platformDeviceTokenChanged,
79 object: nil,
80 userInfo: ["error": error.localizedDescription]
81 )
82 }
83
84 func invalidated() {
85 defaults.removeObject(forKey: key)
86 NotificationCenter.default.post(name: .platformDeviceTokenChanged, object: nil)
87 }
88}
89
90@MainActor
91final class PlatformNotificationService: NSObject, UNUserNotificationCenterDelegate {
92 static let shared = PlatformNotificationService()
93
94 private let center: UNUserNotificationCenter
95 private let tokenSink: any PlatformDeviceTokenSink
96 private let authorizationStatus: @MainActor () async -> UNAuthorizationStatus
97 private let authorizationRequest: @MainActor () async -> Bool
98 private let updateRemoteRegistration: @MainActor (Bool) -> Void
99 private var preferenceRevision: UInt64 = 0
100 private(set) var enabled = false
101
102 init(
103 center: UNUserNotificationCenter = .current(),
104 tokenSink: (any PlatformDeviceTokenSink)? = nil,
105 authorizationStatus: (@MainActor () async -> UNAuthorizationStatus)? = nil,
106 authorizationRequest: (@MainActor () async -> Bool)? = nil,
107 updateRemoteRegistration: (@MainActor (Bool) -> Void)? = nil
108 ) {
109 self.center = center
110 self.tokenSink = tokenSink ?? PlatformPersistedDeviceTokenSink.shared
111 self.authorizationStatus = authorizationStatus ?? {
112 await center.notificationSettings().authorizationStatus
113 }
114 self.authorizationRequest = authorizationRequest ?? {
115 (try? await center.requestAuthorization(options: [.alert, .badge, .sound])) == true
116 }
117 self.updateRemoteRegistration = updateRemoteRegistration ?? { enabled in
118 if enabled {
119 UIApplication.shared.registerForRemoteNotifications()
120 } else {
121 UIApplication.shared.unregisterForRemoteNotifications()
122 center.removeAllPendingNotificationRequests()
123 center.removeAllDeliveredNotifications()
124 }
125 }
126 super.init()
127 }
128
129 func installDelegate() {
130 center.delegate = self
131 }
132
133 /// Returns nil when a newer preference change supersedes this check.
134 @discardableResult
135 func synchronize(enabled: Bool) async -> Bool? {
136 installDelegate()
137 preferenceRevision &+= 1
138 let revision = preferenceRevision
139
140 guard enabled else {
141 self.enabled = false
142 updateRemoteRegistration(false)
143 tokenSink.invalidated()
144 return false
145 }
146
147 let status = await authorizationStatus()
148 guard preferenceRevision == revision else { return nil }
149 let authorized = isAuthorized(status)
150 self.enabled = authorized
151 if authorized {
152 updateRemoteRegistration(true)
153 }
154 return authorized
155 }
156
157 /// Call only in response to an explicit user action such as enabling the
158 /// Notifications toggle. Startup synchronization never presents a prompt.
159 @discardableResult
160 func requestAuthorization() async -> Bool? {
161 installDelegate()
162 preferenceRevision &+= 1
163 let revision = preferenceRevision
164 let status = await authorizationStatus()
165 guard preferenceRevision == revision else { return nil }
166 let authorized: Bool
167 switch status {
168 case .notDetermined:
169 authorized = await authorizationRequest()
170 case .authorized, .provisional, .ephemeral:
171 authorized = true
172 case .denied:
173 authorized = false
174 @unknown default:
175 authorized = false
176 }
177
178 guard preferenceRevision == revision else { return nil }
179 enabled = authorized
180 if authorized {
181 updateRemoteRegistration(true)
182 }
183 return authorized
184 }
185
186 func schedule(_ signal: PlatformThreadSignal) async {
187 guard enabled else { return }
188 let revision = preferenceRevision
189 let settings = await center.notificationSettings()
190 guard enabled, preferenceRevision == revision,
191 [.authorized, .provisional, .ephemeral].contains(settings.authorizationStatus) else {
192 return
193 }
194
195 let content = UNMutableNotificationContent()
196 content.title = notificationTitle(for: signal.kind)
197 content.body = signal.thread.title
198 content.sound = .default
199 content.threadIdentifier = signal.thread.id
200 if let url = PlatformRoute.thread(
201 environmentID: signal.thread.environmentID,
202 threadID: signal.thread.wireID ?? signal.thread.id
203 ).url {
204 content.userInfo = ["t3_route": url.absoluteString]
205 }
206
207 let request = UNNotificationRequest(
208 identifier: "thread:\(signal.thread.id):\(signal.thread.state.rawValue)",
209 content: content,
210 trigger: nil
211 )
212 try? await center.add(request)
213 }
214
215 func didRegisterForRemoteNotifications(deviceToken: Data) {
216 guard enabled else { return }
217 tokenSink.registered(token: deviceToken.map { String(format: "%02x", $0) }.joined())
218 }
219
220 func didFailToRegisterForRemoteNotifications(_ error: Error) {
221 guard enabled else { return }
222 tokenSink.registrationFailed(error)
223 }
224
225 nonisolated func userNotificationCenter(
226 _ center: UNUserNotificationCenter,
227 didReceive response: UNNotificationResponse,
228 withCompletionHandler completionHandler: @escaping @Sendable () -> Void
229 ) {
230 let route = PlatformNotificationPayload.route(
231 from: response.notification.request.content.userInfo
232 )
233 DispatchQueue.main.async {
234 defer { completionHandler() }
235 guard let route else { return }
236 PlatformRouteMailbox.shared.put(route)
237 NotificationCenter.default.post(
238 name: .platformRouteReceived,
239 object: nil,
240 userInfo: ["route": route]
241 )
242 }
243 }
244
245 nonisolated func userNotificationCenter(
246 _ center: UNUserNotificationCenter,
247 willPresent notification: UNNotification
248 ) async -> UNNotificationPresentationOptions {
249 await MainActor.run { enabled ? [.banner, .sound] : [] }
250 }
251
252 private func notificationTitle(for kind: PlatformFeedbackKind) -> String {
253 switch kind {
254 case .success:
255 "Task completed"
256 case .warning:
257 "T3 Code needs you"
258 case .error:
259 "Task failed"
260 }
261 }
262
263 private func isAuthorized(_ status: UNAuthorizationStatus) -> Bool {
264 switch status {
265 case .authorized, .provisional, .ephemeral:
266 true
267 case .notDetermined, .denied:
268 false
269 @unknown default:
270 false
271 }
272 }
273}
274
275@MainActor
276final class T3PlatformAppDelegate: NSObject, UIApplicationDelegate {
277 func application(
278 _ application: UIApplication,
279 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
280 ) -> Bool {
281 PlatformBackgroundRefreshCoordinator.shared.register()
282 PlatformNotificationService.shared.installDelegate()
283 return true
284 }
285
286 func application(
287 _ application: UIApplication,
288 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
289 ) {
290 PlatformNotificationService.shared.didRegisterForRemoteNotifications(deviceToken: deviceToken)
291 }
292
293 func application(
294 _ application: UIApplication,
295 didFailToRegisterForRemoteNotificationsWithError error: Error
296 ) {
297 PlatformNotificationService.shared.didFailToRegisterForRemoteNotifications(error)
298 }
299
300 func application(
301 _ application: UIApplication,
302 didReceiveRemoteNotification userInfo: [AnyHashable: Any],
303 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
304 ) {
305 completionHandler(
306 PlatformNotificationPayload.route(from: userInfo) == nil ? .noData : .newData
307 )
308 }
309}