Repository Public
1import AppKit2import MCCCore3import UserNotifications45/// What a notification says for an alert event. Pure, so that it can be tested without the notification centre.6struct AlertNotificationContent: Equatable {7 var identifier: String8 var title: String9 var body: String10 var critical: Bool1112 /// Firing and resolved alerts are announced; pending, acknowledged and suppressed (silence / maintenance) are not.13 static func make(for e: API.AlertChangedEvent, nodeAlias: String?) -> AlertNotificationContent? {14 guard e.suppressed != true else { return nil }15 let where_ = nodeAlias.map { " · \($0)" } ?? ""16 switch e.state {17 case .firing:18 return .init(identifier: "alert-\(e.alertId)", title: tr("notify.alert.firing", e.severity.label) + where_, body: e.summary,19 critical: e.severity == .critical)20 case .resolved:21 return .init(identifier: "alert-\(e.alertId)", title: tr("notify.alert.resolved") + where_, body: e.summary, critical: false)22 case .pending, .acknowledged:23 return nil24 }25 }26}2728/// Local notifications for alerts received over the event stream while the app runs, and registration for remote29/// notifications. A notification only ever OPENS the alert: any action still goes through the normal confirmed,30/// authenticated flow.31@MainActor32final class AlertNotifier: NSObject, UNUserNotificationCenterDelegate {33 private let enabled: Bool34 private weak var app: AppModel?35 private var handlerID: UUID?36 private var asked = false37 nonisolated static let alertIDKey = "alert_id"3839 init(enabled: Bool) {40 self.enabled = enabled41 super.init()42 }4344 func attach(to app: AppModel) {45 guard enabled else { return }46 self.app = app47 UNUserNotificationCenter.current().delegate = self48 handlerID = app.session.addEventHandler { [weak self] envelope in49 if case .alertChanged(let e) = envelope.event { self?.notify(e) }50 }51 }5253 func requestAuthorizationIfNeeded() {54 guard enabled, !asked else { return }55 asked = true56 Task {57 let granted = (try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])) ?? false58 // Remote notifications need the aps-environment entitlement (provisioned Release build only).59 if granted, Entitlements.apsEnvironment != nil { NSApp.registerForRemoteNotifications() }60 }61 }6263 private func notify(_ e: API.AlertChangedEvent) {64 guard let app, let c = AlertNotificationContent.make(for: e, nodeAlias: e.nodeId.flatMap { app.session.nodes.alias($0) }) else { return }65 let content = UNMutableNotificationContent()66 content.title = c.title67 content.body = c.body68 content.sound = c.critical ? .defaultCritical : .default69 content.userInfo = [Self.alertIDKey: e.alertId]70 content.threadIdentifier = "alerts"71 // Same identifier for firing and resolved: the resolution replaces the alert in Notification Centre.72 UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: c.identifier, content: content, trigger: nil))73 }7475 /// The APNs device token goes to the server (`PUT /me/devices/current/push-token`).76 func didRegister(deviceToken: Data) {77 guard let app, app.session.phase == .signedIn else { return }78 let production = Entitlements.apsEnvironment == "production"79 Task { _ = try? await app.session.account.registerPushToken(deviceToken, production: production) }80 }8182 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {83 [.banner, .list, .sound]84 }8586 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {87 let id = response.notification.request.content.userInfo[Self.alertIDKey] as? String88 await MainActor.run {89 guard let id, let app = self.app else { return }90 // Opening only. Acknowledging, resolving or acting is done in the app, by the signed-in user.91 app.show(.alerts, focus: .alert(id))92 }93 }94}9596final class AppDelegate: NSObject, NSApplicationDelegate {97 @MainActor static var notifier: AlertNotifier?9899 func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {100 MainActor.assumeIsolated { Self.notifier?.didRegister(deviceToken: deviceToken) }101 }102103 func application(_ application: NSApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {104 // No APNs entitlement or no network: local notifications keep working; nothing to surface.105 }106107 /// The menu bar extra keeps the app useful with every window closed.108 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }109}110