Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/System/PushRegistrar.swift3// Description: Push registration and its lifecycle: asks for the notification permission once a session exists (never at first launch before4// sign-in), registers with APNs, sends the token to the server with the environment read from the signature, re-registers when the token,5// the session or the app version changes, removes the device on sign-out, and keeps the server's push state (preferences, status, devices)6// for the Settings pane. A server without APNs credentials is not an error: the app then announces new mail by itself.7import SPMailCore8import SPMailSystem9import SwiftUI10import UserNotifications11#if os(macOS)12import AppKit13#else14import UIKit15#endif1617@MainActor @Observable18final class PushRegistrar {19 enum Registration: Equatable {20 /// Nothing asked yet (no session, or notifications turned off in the app).21 case idle22 /// The person refused notifications in the system settings.23 case denied24 /// This build cannot receive pushes (no push entitlement), or APNs refused: the reason, for Settings.25 case unavailable(String)26 case registering27 case registered28 case failed(String)29 }3031 @ObservationIgnored unowned let app: AppModel32 @ObservationIgnored let next: NextAPI33 @ObservationIgnored private let defaults = UserDefaults.standard34 private(set) var registration: Registration = .idle35 private(set) var authorization: UNAuthorizationStatus = .notDetermined36 /// The server's row for this device (nil = not registered).37 private(set) var deviceId: String?38 private(set) var prefs: PushPrefs?39 private(set) var serverStatus: PushStatus?40 private(set) var devices: [PushDevice] = []41 private(set) var lastError: String?42 @ObservationIgnored private var token: Data?43 /// The environment of this build's tokens, from its signature; nil = no push entitlement.44 @ObservationIgnored let environment = PushEnvironmentDetector.current()45 #if DEBUG46 /// Self-test: a simulated token is registered as a sandbox token whatever the signature says.47 @ObservationIgnored var environmentOverride: PushEnvironment?48 #endif4950 init(app: AppModel, next: NextAPI) {51 self.app = app; self.next = next52 deviceId = defaults.string(forKey: Keys.deviceId)53 }5455 private enum Keys { static let deviceId = "push.deviceId", fingerprint = "push.fingerprint", registeredAt = "push.registeredAt", asked = "push.askedOnce" }5657 var isAuthorized: Bool { authorization == .authorized || authorization == .provisional }58 var thisDevice: PushDevice? { devices.first { $0.current } ?? devices.first { $0.id == deviceId } }59 /// The server announces new mail to this device: it has APNs credentials, the device is registered and enabled, the account has60 /// notifications on and the system lets them through. The app then posts no local notification of its own (no duplicates).61 var pipelineActive: Bool {62 guard deviceId != nil, isAuthorized, serverStatus?.configured == true, prefs?.enabled != false else { return false }63 return thisDevice?.enabled != false64 }6566 // MARK: session6768 /// Called once the session is up. Asks for the permission the first time (unless `prompt` is false), then registers.69 func sessionStarted(prompt: Bool) async {70 await refreshAuthorization()71 Task { await refreshServerState() }72 #if DEBUG73 // `-spmFakePushToken YES` (simulator captures): a simulated sandbox token is registered, so the dev backend treats this device as74 // reachable by push and the Settings pane shows a registered device. Real pushes are then delivered with `xcrun simctl push`.75 if UserDefaults.standard.bool(forKey: "spmFakePushToken") {76 environmentOverride = .sandbox77 let stored = UserDefaults.standard.data(forKey: "spmFakePushTokenValue") ?? Data((0..<32).map { _ in UInt8.random(in: 0...255) })78 UserDefaults.standard.set(stored, forKey: "spmFakePushTokenValue")79 await didRegister(token: stored)80 }81 #endif82 guard app.settings.notificationsEnabled else { registration = .idle; return }83 if authorization == .notDetermined {84 guard prompt else { return }85 defaults.set(true, forKey: Keys.asked)86 _ = try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound])87 await refreshAuthorization()88 }89 guard isAuthorized else { registration = authorization == .denied ? .denied : .idle; return }90 registerWithSystem()91 }9293 /// The switch in Settings: turning notifications on asks for the permission if it was never asked.94 func userEnabledNotifications() async { await sessionStarted(prompt: true) }9596 func refreshAuthorization() async {97 let status = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus98 if status != authorization { authorization = status }99 if status == .denied, registration != .denied { registration = .denied }100 }101102 private func registerWithSystem() {103 guard environment != nil || debugOverride != nil else {104 registration = .unavailable(L("Cette version de l’app n’a pas le droit de recevoir des notifications poussées."))105 return106 }107 if registration != .registered { registration = .registering }108 #if os(macOS)109 NSApp?.registerForRemoteNotifications()110 #else111 UIApplication.shared.registerForRemoteNotifications()112 #endif113 }114 private var debugOverride: PushEnvironment? {115 #if DEBUG116 return environmentOverride117 #else118 return nil119 #endif120 }121122 // MARK: token123124 /// What identifies a registration: a change in any of these means the server must hear from this device again.125 static func fingerprint(token: Data, environment: PushEnvironment, bundleId: String, appVersion: String, sessionId: String, locale: String) -> String {126 [token.map { String(format: "%02x", $0) }.joined(), environment.rawValue, bundleId, appVersion, sessionId, locale].joined(separator: "|")127 }128 static var appVersion: String {129 let info = Bundle.main.infoDictionary130 return "\(info?["CFBundleShortVersionString"] as? String ?? "0") (\(info?["CFBundleVersion"] as? String ?? "0"))"131 }132 /// The language the app runs in (the server writes its generic notification texts in it).133 static var locale: String { Bundle.main.preferredLocalizations.first ?? Locale.current.identifier }134135 func didRegister(token: Data) async {136 self.token = token137 guard app.api.token != nil, let session = app.me?.session.id else { return } // signed out meanwhile: registered at the next session138 guard let env = debugOverride ?? environment else { registration = .unavailable(L("Cette version de l’app n’a pas le droit de recevoir des notifications poussées.")); return }139 let stamp = Self.fingerprint(token: token, environment: env, bundleId: AppConfig.bundleId, appVersion: Self.appVersion, sessionId: session, locale: Self.locale)140 let recent = Date().timeIntervalSince1970 - defaults.double(forKey: Keys.registeredAt) < 7 * 86400141 if deviceId != nil, recent, defaults.string(forKey: Keys.fingerprint) == stamp { registration = .registered; return }142 do {143 let id = try await next.registerPush(PushRegistration(apnsToken: token, sandbox: env == .sandbox, bundleId: AppConfig.bundleId, deviceName: AppConfig.clientInfo.deviceName,144 locale: Self.locale, appVersion: Self.appVersion))145 deviceId = id146 defaults.set(id, forKey: Keys.deviceId); defaults.set(stamp, forKey: Keys.fingerprint); defaults.set(Date().timeIntervalSince1970, forKey: Keys.registeredAt)147 registration = .registered; lastError = nil148 await refreshServerState()149 } catch let e as APIError where e.isUnauthorized {150 registration = .idle151 } catch {152 // offline or refused: the next launch (or the next token callback) tries again153 registration = .failed(app.describe(error) ?? "")154 }155 }156157 func didFail(_ error: Error) {158 // a device already registered (a simulated token in development) stays registered; the system's reason is technical, ours is readable159 guard registration != .registered else { return }160 lastError = error.localizedDescription161 registration = .unavailable(L("Cette version de l’app n’a pas le droit de recevoir des notifications poussées."))162 }163164 // MARK: sign-out165166 /// Removes this device on the server (the session is still valid at this point). Best effort: the server also drops the token when167 /// the session ends.168 func unregister() async {169 guard let id = deviceId else { return }170 try? await next.deletePushDevice(id: id)171 forgetDevice()172 }173 func sessionEnded() {174 forgetDevice()175 prefs = nil; serverStatus = nil; devices = []; lastError = nil176 registration = .idle177 #if os(iOS)178 UIApplication.shared.unregisterForRemoteNotifications()179 #else180 NSApp?.unregisterForRemoteNotifications()181 #endif182 }183 private func forgetDevice() {184 deviceId = nil185 for k in [Keys.deviceId, Keys.fingerprint, Keys.registeredAt] { defaults.removeObject(forKey: k) }186 }187188 // MARK: server state (Settings › Notifications)189190 func refreshServerState() async {191 guard app.api.token != nil else { return }192 do {193 async let p = next.pushPrefs(), s = next.pushStatus(), d = next.pushDevices()194 let (prefs, status, devices) = try await (p, s, d)195 self.prefs = prefs; serverStatus = status; self.devices = devices196 // the server dropped this device (dead token, session change): register again at the next token callback197 if let id = deviceId, !devices.contains(where: { $0.id == id }) { forgetDevice(); if isAuthorized, app.settings.notificationsEnabled { registerWithSystem() } }198 lastError = nil199 app.system.notifications.recomputeBadge()200 app.system.shared.writeState()201 app.system.shared.scheduleSnapshot()202 } catch let e as APIError where e.isOffline {203 lastError = L("Le serveur est injoignable. Vérifiez la connexion.")204 } catch {205 lastError = app.describe(error)206 }207 }208209 /// Saves the account-wide preferences; the server's answer replaces the local copy.210 func save(_ new: PushPrefs) async {211 let before = prefs212 prefs = new213 do { prefs = try await next.setPushPrefs(new); lastError = nil } catch { prefs = before; lastError = app.describe(error) }214 app.system.notifications.recomputeBadge()215 app.system.shared.writeState()216 app.system.shared.scheduleSnapshot()217 }218 func setDevice(_ device: PushDevice, enabled: Bool) async {219 do { try await next.updatePushDevice(id: device.id, PushDevicePatch(enabled: enabled)); lastError = nil } catch { lastError = app.describe(error) }220 await refreshServerState()221 }222 func remove(_ device: PushDevice) async {223 do { try await next.deletePushDevice(id: device.id); lastError = nil } catch { lastError = app.describe(error) }224 if device.id == deviceId { forgetDevice(); registration = .idle }225 await refreshServerState()226 }227 /// Asks the server for a test notification on this device (or all of the user's). Returns how many were queued (0 when the server228 /// has no APNs credentials: nothing is ever simulated).229 func sendTest(to device: PushDevice? = nil) async -> Int? {230 do { let n = try await next.testPush(deviceId: device?.id); lastError = nil; Task { try? await Task.sleep(for: .seconds(3)); await refreshServerState() }; return n } catch { lastError = app.describe(error); return nil }231 }232}233