SPB Git

Repository Public

Push.swift 7.3 KB 161 lines swift

1import Foundation2import MCCCore3import Observation4import UIKit5import UserNotifications67/// What a notification says about an alert. Pure, unit-tested.8struct AlertNotificationContent: Equatable, Sendable {9    var identifier: String10    var title: String11    var body: String12    var critical: Bool1314    /// Only a firing, non-suppressed alert is announced locally.15    static func make(for e: API.AlertChangedEvent, nodeAlias: String?) -> AlertNotificationContent? {16        guard e.state == .firing, e.suppressed != true else { return nil }17        let title = [e.severity.label, nodeAlias].compactMap { $0 }.joined(separator: " · ")18        return AlertNotificationContent(identifier: "alert-" + e.alertId, title: title, body: e.summary, critical: e.severity == .critical)19    }20}2122/// Where a notification leads. A notification can only OPEN a screen: acknowledging, resolving or running anything23/// is done in the app, by the signed-in user, through the confirmed flows.24enum NotificationRouting {25    static let alertIDKey = "alert_id"26    static let actionIDKey = "action_id"27    static let categoryAlert = "MCC_ALERT"28    static let openActionID = "MCC_OPEN"2930    static func route(for userInfo: [AnyHashable: Any]) -> Route? {31        if let id = userInfo[alertIDKey] as? String, UUID(uuidString: id) != nil { return .alert(id) }32        if let id = userInfo[actionIDKey] as? String, UUID(uuidString: id) != nil { return .action(id) }33        return nil34    }35}3637/// Remote-notification registration, the device token upload, local notifications for alerts received over the38/// event stream while the app is active, and the handling of taps.39@MainActor40@Observable41final class PushCoordinator: NSObject, UNUserNotificationCenterDelegate {42    static let localAlertsKey = "mcc.notifications.local_alerts"4344    @ObservationIgnored weak var app: AppModel?45    private(set) var authorization: UNAuthorizationStatus = .notDetermined46    /// Result of the last token upload (`PUT /me/devices/current/push-token`), for the diagnostics pane.47    private(set) var tokenUploadedAt: Date?48    private(set) var registrationError: String?49    var localAlerts: Bool {50        didSet { UserDefaults.standard.set(localAlerts, forKey: Self.localAlertsKey) }51    }52    @ObservationIgnored private var handler: UUID?53    @ObservationIgnored private var deviceToken: Data?5455    override init() {56        localAlerts = UserDefaults.standard.object(forKey: Self.localAlertsKey) as? Bool ?? true57        super.init()58    }5960    private var disabled: Bool { app?.environment.uiTesting ?? true }6162    func start() {63        guard let app, !disabled else { return }64        let center = UNUserNotificationCenter.current()65        center.delegate = self66        // One category, one action, and it only brings the app to the foreground. Nothing destructive, nothing that67        // changes server state from a notification.68        let open = UNNotificationAction(identifier: NotificationRouting.openActionID, title: tr("notifications.action.open"), options: [.foreground])69        center.setNotificationCategories([UNNotificationCategory(identifier: NotificationRouting.categoryAlert, actions: [open], intentIdentifiers: [])])70        handler = app.session.addEventHandler { [weak self] envelope in71            if case .alertChanged(let e) = envelope.event { self?.notifyLocally(e) }72        }73        Task { await refreshAuthorization() }74    }7576    func refreshAuthorization() async {77        authorization = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus78    }7980    /// Called once a session exists: registers with APNs if the user already accepted notifications.81    func sessionOpened() {82        guard !disabled else { return }83        Task {84            await refreshAuthorization()85            if authorization == .authorized || authorization == .provisional { UIApplication.shared.registerForRemoteNotifications() }86            if let deviceToken { upload(deviceToken) }87        }88    }8990    /// Asks for the permission (from Settings → Notifications, never at launch).91    func requestAuthorization() async {92        guard !disabled else { return }93        _ = try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])94        await refreshAuthorization()95        if authorization == .authorized || authorization == .provisional { UIApplication.shared.registerForRemoteNotifications() }96    }9798    func didRegister(deviceToken: Data) {99        self.deviceToken = deviceToken100        registrationError = nil101        upload(deviceToken)102    }103104    func didFailToRegister(_ error: any Error) { registrationError = error.localizedDescription }105106    private func upload(_ token: Data) {107        guard let app, app.session.phase == .signedIn else { return }108        Task {109            do {110                _ = try await app.session.account.registerPushToken(token, production: AppEnvironment.pushIsProduction)111                tokenUploadedAt = Date()112            } catch {113                registrationError = APIError.from(error).message114            }115        }116    }117118    private func notifyLocally(_ e: API.AlertChangedEvent) {119        guard localAlerts, authorization == .authorized || authorization == .provisional, let app,120              let c = AlertNotificationContent.make(for: e, nodeAlias: e.nodeId.flatMap({ app.session.nodes.alias($0) })) else { return }121        let content = UNMutableNotificationContent()122        content.title = c.title123        content.body = c.body124        content.sound = .default125        content.userInfo = [NotificationRouting.alertIDKey: e.alertId]126        content.threadIdentifier = "mcc-alerts"127        content.categoryIdentifier = NotificationRouting.categoryAlert128        UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: c.identifier, content: content, trigger: nil))129    }130131    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {132        [.banner, .list, .sound]133    }134135    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {136        let info = response.notification.request.content.userInfo137        let alert = info[NotificationRouting.alertIDKey] as? String138        let action = info[NotificationRouting.actionIDKey] as? String139        await MainActor.run {140            var userInfo: [AnyHashable: Any] = [:]141            if let alert { userInfo[NotificationRouting.alertIDKey] = alert }142            if let action { userInfo[NotificationRouting.actionIDKey] = action }143            // Opening only: the route is consumed by a signed-in, unlocked scene.144            if let route = NotificationRouting.route(for: userInfo) { self.app?.pendingRoute = route }145        }146    }147}148149final class AppDelegate: NSObject, UIApplicationDelegate {150    @MainActor static weak var push: PushCoordinator?151152    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {153        MainActor.assumeIsolated { Self.push?.didRegister(deviceToken: deviceToken) }154    }155156    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: any Error) {157        // Simulator, no APNs entitlement or no network: local notifications keep working.158        MainActor.assumeIsolated { Self.push?.didFailToRegister(error) }159    }160}161
Files main
Menu

Theme