SPB Git

Repository Public

NotificationCoordinator.swift 20.9 KB 362 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/System/NotificationCoordinator.swift3// Description: Notification handling: the categories of the server contract (`MAIL_NEW`, `MAIL_REMINDER`, `MAIL_ALERT`), foreground4// presentation that does not repeat what is on screen, tap routing to the exact conversation, the actions run in the background through5// the sync engine and the normal send path, silent pushes (sync within the time budget, badge), one notification per message whether it6// was announced by the server or by the app, and the badge kept right after local reads.7import SPMailCore8import SPMailSystem9import SwiftUI10import UserNotifications11#if os(macOS)12import AppKit13#else14import UIKit15#endif1617/// Carries a system completion handler into a main-actor task (the handlers are not `Sendable`; they are called exactly once, on the main actor).18private struct Completion<T>: @unchecked Sendable { let call: (T) -> Void }1920@MainActor21final class NotificationCoordinator: NSObject {22    unowned let app: AppModel23    let next: NextAPI24    private var ledger: NotificationLedger25    /// A command that waits for the app lock (macOS: notification actions carry no authentication of their own).26    private var afterUnlock: NotificationCommand?27    #if DEBUG28    /// Self-test: the last command resolved from a notification response, and whether it ran.29    private(set) var lastCommand: NotificationCommand?30    #endif3132    private static let ledgerKey = "notifications.ledger"3334    init(app: AppModel, next: NextAPI) {35        self.app = app; self.next = next36        ledger = UserDefaults.standard.data(forKey: Self.ledgerKey).flatMap { try? JSONDecoder().decode(NotificationLedger.self, from: $0) } ?? NotificationLedger()37        ledger.prune()38    }39    private func saveLedger() { if let d = try? JSONEncoder().encode(ledger) { UserDefaults.standard.set(d, forKey: Self.ledgerKey) } }4041    func install() {42        UNUserNotificationCenter.current().delegate = self43        registerCategories()44    }4546    // MARK: categories4748    private static func title(_ id: NotificationActionID) -> String {49        switch id {50        case .archive: L("Archiver"); case .markRead: L("Marquer comme lu"); case .reply: L("Répondre"); case .delete: L("Supprimer")51        case .open: L("Ouvrir"); case .snoozeHour: L("Rappeler dans 1 heure"); case .done: L("Terminé")52        }53    }54    private static func placeholder(_ category: String) -> String {55        switch category { case NotificationPayload.categoryNew: L("Nouveau message"); case NotificationPayload.categoryReminder: L("Rappel"); default: "SP Mail" }56    }57    /// Registered at launch and again whenever the app lock is turned on or off (the lock makes every mail action wait for the device to be unlocked).58    func registerCategories() {59        #if os(macOS)60        let platform = NotificationPlatform.macOS61        #else62        let platform = NotificationPlatform.iOS63        #endif64        let categories = NotificationCategories.all(platform: platform, lockEnabled: app.settings.lockEnabled).map { spec -> UNNotificationCategory in65            let actions = spec.actions.map { a -> UNNotificationAction in66                var options: UNNotificationActionOptions = []67                if a.destructive { options.insert(.destructive) }68                if a.authenticationRequired { options.insert(.authenticationRequired) }69                if a.foreground { options.insert(.foreground) }70                let icon = UNNotificationActionIcon(systemImageName: a.systemImage)71                if a.textInput != nil {72                    return UNTextInputNotificationAction(identifier: a.id.rawValue, title: Self.title(a.id), options: options, icon: icon, textInputButtonTitle: L("Envoyer"), textInputPlaceholder: L("Votre réponse"))73                }74                return UNNotificationAction(identifier: a.id.rawValue, title: Self.title(a.id), options: options, icon: icon)75            }76            return UNNotificationCategory(identifier: spec.id, actions: actions, intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: Self.placeholder(spec.id), options: [])77        }78        UNUserNotificationCenter.current().setNotificationCategories(Set(categories))79    }8081    // MARK: what is on screen8283    /// `<mailbox>:<thread>` of the conversations open in a window.84    private var visibleConversations: Set<String> {85        var keys: Set<String> = []86        for scene in app.scenes { if let account = scene.activeAccount { for e in scene.reader.conversation { keys.insert("\(account):\(e.threadId)") } } }87        return keys88    }89    private var visibleInboxes: Set<String> {90        var ids: Set<String> = []91        for scene in app.scenes where !scene.isDetached {92            if let account = scene.currentAccount, let inbox = scene.mailbox(.inbox), scene.selection == .mailbox(inbox.id), !scene.search.isActive { ids.insert(account) }93        }94        return ids95    }9697    // MARK: presentation (app running)9899    /// What crossed from the system callback: only values, no framework object.100    struct Incoming: Sendable {101        var route: NotificationRoute102        var payload: NotificationPayload?103        var threadKey: String?104        var identifier: String105        var isRemote: Bool106    }107108    func present(_ n: Incoming) -> UNNotificationPresentationOptions {109        if n.isRemote, let (mb, email) = n.route.target {110            // the server announced it: the app will not announce it again, and a local copy posted a moment ago goes111            ledger.record(NotificationIdentity.key(mailboxId: mb, emailId: email)); saveLedger()112            let legacy = NotificationIdentity.key(mailboxId: mb, emailId: email)113            if n.identifier != legacy { UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [legacy]) }114        }115        if n.isRemote, n.payload?.needsSync == true, let mb = n.payload?.mailboxId, let engine = app.engines[mb] { Task { try? await engine.syncNow() } }116        let active = AppActivity.isActive && app.phase == .ready117        let p = ForegroundPresentation.decide(appActive: active, route: n.route, threadKey: n.threadKey, visibleConversations: visibleConversations, visibleInboxes: visibleInboxes, paused: app.settings.notificationsPaused)118        var options: UNNotificationPresentationOptions = []119        if p.banner { options.insert(.banner) }120        if p.list { options.insert(.list) }121        if p.sound { options.insert(.sound) }122        if p.badge, app.system.push.prefs?.badge != PushBadge.none { options.insert(.badge) }123        return options124    }125126    // MARK: responses127128    func respond(_ command: NotificationCommand, identifier: String) async {129        #if DEBUG130        lastCommand = command131        #endif132        switch command {133        case .none: return134        case .open(let route):135            UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [identifier])136            if let link = route.deepLink { app.system.router.deliver(link) }137        default:138            guard await sessionReady() else { return }139            #if os(macOS)140            // no authentication step on macOS notifications: what sends content waits for the app lock, in the app141            if app.phase == .locked, command.needsUnlockedApp { afterUnlock = command; NSApp?.activate(ignoringOtherApps: true); return }142            #endif143            _ = await perform(command)144            UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [identifier])145        }146    }147148    /// The app lock was just opened: a quick reply typed while locked (macOS) now leaves.149    func unlocked() async {150        guard let command = afterUnlock, app.phase == .ready else { return }151        afterUnlock = nil152        _ = await perform(command)153    }154155    /// Launches the session if the app was started in the background by the notification, and waits for the engines.156    func sessionReady() async -> Bool {157        await app.launch()158        for _ in 0..<100 {159            if app.phase == .signedOut { return false }160            if (app.phase == .ready || app.phase == .locked), !app.engines.isEmpty { return true }161            try? await Task.sleep(for: .milliseconds(200))162        }163        return false164    }165166    /// Runs a notification action through the engine of the message's mailbox (optimistic local change + server operation, queued when167    /// offline) or the Next API, then pushes pending operations within the background time the system gives.168    @discardableResult169    func perform(_ command: NotificationCommand) async -> Bool {170        var ok = true171        var account: String?172        switch command {173        case .none, .open: return false174        case .archive(let mb, let email):175            account = mb176            guard let engine = app.engines[mb] else { return false }177            do { try await engine.archive(ids: [email], folderName: L("Archives")) } catch { ok = false }178        case .markRead(let mb, let email):179            account = mb180            guard let engine = app.engines[mb] else { return false }181            await engine.markSeen(true, ids: [email])182        case .delete(let mb, let email):183            account = mb184            guard let engine = app.engines[mb] else { return false }185            do { try await engine.delete(ids: [email]) } catch { ok = false }186        case .reply(let mb, let email, let text):187            account = mb188            ok = await quickReply(mailbox: mb, emailId: email, text: text)189        case .snooze(let mb, let email, let until):190            account = mb191            do { _ = try await next.snooze(mailboxId: mb, emailIds: [email], until: until) } catch { ok = false }192        case .done(let mb, let email, let kind):193            account = mb194            if kind == .reminder {195                do {196                    // « Terminé » settles every open reminder of that message (the one that fired, and one still waiting)197                    for r in try await next.reminders() where r.isOpen && r.mailboxId == mb && r.emailId == email { _ = try await next.updateReminder(id: r.id, done: true) }198                } catch { ok = false }199            }200            await app.engines[mb]?.markSeen(true, ids: [email])201        }202        if let account, let engine = app.engines[account] { _ = await AppModel.withBudget(20) { (try? await engine.syncNowAndWait()) != nil } }203        await app.reloadMailboxes()204        return ok205    }206207    /// A quick reply goes through the normal send path: the reply builder (recipients, threading headers, quoted original, signature),208    /// the identity the message was addressed to (the mailbox's default one otherwise) and the engine's outbox (idempotent submission,209    /// queued when offline). Exactly one message leaves.210    private func quickReply(mailbox mb: String, emailId: String, text: String) async -> Bool {211        guard let engine = app.engines[mb], let store = app.store else { return false }212        try? await engine.ensureCached(ids: [emailId])213        guard let original = (try? await store.email(mb, id: emailId)) ?? nil else { return false }214        if app.senders.isEmpty { await app.loadSenders() }215        let mine = app.senders.filter { $0.account == mb }216        guard let primary = mine.first(where: { !$0.isAlias }) ?? mine.first else { return false }217        let from = SenderIdentity.forReply(to: original, among: mine, deliveredTo: [], fallback: primary) ?? primary218        let me = Set(mine.map { $0.email.lowercased() } + [engine.address.lowercased()])219        let french = Locale.current.language.languageCode?.identifier != "en"220        var message = ReplyBuilder.build(kind: .reply, original: original, body: try? await engine.body(for: emailId), identity: from.identity, me: me, labels: french ? .french : .english, locale: .current)221        guard !message.to.isEmpty else { return false }222        message.text = text + message.text223        let sent = await engine.send(OutboxItem(account: mb, message: message))224        await engine.markSeen(true, ids: [emailId])225        await app.reloadOutbox()226        return sent.state == .accepted || sent.state == .queuedOffline || sent.state == .sending227    }228229    // MARK: remote notifications delivered to the app (silent pushes, and alerts while it runs)230231    /// A push reached the app: sync within the time budget the system gives a background launch, then put the badge right.232    /// Returns true when the mailboxes were really synchronised.233    func handleRemote(_ payload: NotificationPayload) async -> Bool {234        guard await sessionReady() else { return false }235        if let (mb, email) = payload.target, payload.kind == .new { ledger.record(NotificationIdentity.key(mailboxId: mb, emailId: email)); saveLedger() }236        let synced = await app.syncAll(budget: 22)237        await app.reloadMailboxes()238        let local = BadgeMath.badge(inboxUnread: app.inboxUnread, prefs: app.system.push.prefs)239        if app.system.push.prefs?.badge != PushBadge.none { Notifier.setBadge(BadgeMath.reconcile(server: payload.badge, local: local, localIsFresher: synced)) }240        if payload.kind == .badge { await removeReadNotifications() }241        return synced242    }243244    /// Mail was read elsewhere: the notifications of messages that are no longer unread in an Inbox leave Notification Centre.245    private func removeReadNotifications() async {246        guard let store = app.store else { return }247        var stale: [String] = []248        for (identifier, route) in await Self.delivered() {249            guard let (mb, email) = route.target else { continue }250            let inbox = app.mailboxes(for: mb).first { $0.role == "inbox" }?.id251            guard let e = (try? await store.email(mb, id: email)) ?? nil else { if app.engines[mb] != nil { stale.append(identifier) }; continue }252            if e.isSeen || (inbox != nil && !e.mailboxIds.contains(inbox!)) { stale.append(identifier) }253        }254        if !stale.isEmpty { UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: stale) }255    }256    /// Identifier and route of what is in Notification Centre (values only: `UNNotification` does not cross actors).257    private nonisolated static func delivered() async -> [(String, NotificationRoute)] {258        await UNUserNotificationCenter.current().deliveredNotifications().map { ($0.request.identifier, NotificationRoute(userInfo: $0.request.content.userInfo)) }259    }260261    // MARK: local notifications (no push pipeline)262263    /// New mail the app noticed by itself (live event stream, background refresh). Silent when the server announces mail by push, and for264    /// any message already announced: the person never gets two notifications for one message.265    func announceLocally(_ mails: [EmailSummary], account: String) async {266        guard !mails.isEmpty, app.settings.notificationsEnabled else { return }267        let center = UNUserNotificationCenter.current()268        guard await center.notificationSettings().authorizationStatus == .authorized else { return }269        let push = app.system.push270        // pushes delivered while the app was suspended were never seen by the delegate: read them from Notification Centre271        for (_, route) in await Self.delivered() { if let (mb, email) = route.target { ledger.record(NotificationIdentity.key(mailboxId: mb, emailId: email)) } }272        let prefs = push.prefs273        let level: PushPreview = app.settings.hideNotificationContent || app.lock.concealsContent ? .none : (prefs?.preview == .full ? .full : prefs?.preview == PushPreview.none ? .none : .sender)274        let french = Locale.current.language.languageCode?.identifier != "en"275        var posted = 0276        for m in mails.prefix(5) {277            let key = NotificationIdentity.key(mailboxId: account, emailId: m.id)278            let sender = m.from.first?.email.lowercased() ?? ""279            let priority = (prefs?.prioritySenders ?? []).contains { $0 == sender || ($0.hasPrefix("@") && sender.hasSuffix($0)) }280            let quiet = !priority && ((prefs?.quietHours?.contains(Date()) ?? false) || (prefs?.priorityOnly ?? false))281            guard LocalNotificationPolicy.shouldPostLocal(enabled: prefs?.enabled ?? true, paused: app.settings.notificationsPaused, appActive: AppActivity.isActive, pushPipelineActive: push.pipelineActive,282                                                          alreadyAnnounced: ledger.contains(key), mailboxMuted: prefs?.isMuted(mailbox: account) ?? false, inQuietHours: quiet) else { continue }283            let content = UNMutableNotificationContent()284            let generic = NotificationRedactor.generic(kind: .new, french: french)285            switch level {286            case .full:287                content.title = m.sender?.displayName ?? "SP Mail"288                content.subtitle = m.subject.isEmpty ? L("(sans objet)") : m.subject289                content.body = m.preview.isEmpty ? generic : String(m.preview.prefix(180))290            case .sender: content.title = m.sender?.displayName ?? "SP Mail"; content.body = generic291            default: content.title = "SP Mail"; content.body = generic292            }293            content.sound = .default294            content.categoryIdentifier = NotificationPayload.categoryNew295            content.threadIdentifier = "\(account):\(m.threadId)"296            content.interruptionLevel = priority ? .timeSensitive : .active297            content.userInfo = ["mb": account, "email": m.id, "thread": m.threadId, "kind": "new"]298            // the same request identifier as the server's push for this message: a late push replaces this notification instead of adding one299            let identifier = NotificationIdentity.localIdentifier(deviceId: push.deviceId, mailboxId: account, emailId: m.id)300            if (try? await center.add(UNNotificationRequest(identifier: identifier, content: content, trigger: nil))) != nil { ledger.record(key); posted += 1 }301        }302        if posted > 0, mails.count > 5 {303            let content = UNMutableNotificationContent()304            content.title = String(localized: "\(mails.count - 5) autres nouveaux messages")305            content.threadIdentifier = account306            content.userInfo = ["mb": account, "kind": "new"]307            try? await center.add(UNNotificationRequest(identifier: "\(account)/more", content: content, trigger: nil))308        }309        saveLedger()310    }311312    // MARK: badge and clean-up313314    /// The badge from the app's own counters (same rule as the server): called after every reload of the folders, so a message read here315    /// lowers the badge at once, before any push.316    func recomputeBadge() {317        guard app.phase == .ready || app.phase == .locked else { return }318        Notifier.setBadge(BadgeMath.badge(inboxUnread: app.inboxUnread, prefs: app.system.push.prefs))319    }320    func removeDelivered(account: String) {321        Task {322            let ids = await Self.delivered().filter { if case .conversation(let mb, _, _) = $0.1 { mb == account } else if case .inbox(let mb) = $0.1 { mb == account } else { false } }.map(\.0)323            UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ids)324        }325    }326    func sessionEnded() {327        ledger = NotificationLedger(); saveLedger()328        afterUnlock = nil329        let center = UNUserNotificationCenter.current()330        center.removeAllDeliveredNotifications(); center.removeAllPendingNotificationRequests()331        Notifier.setBadge(0)332    }333    #if DEBUG334    func ledgerContains(mailboxId: String, emailId: String) -> Bool { ledger.contains(NotificationIdentity.key(mailboxId: mailboxId, emailId: emailId)) }335    #endif336}337338// MARK: - UNUserNotificationCenterDelegate339340extension NotificationCoordinator: UNUserNotificationCenterDelegate {341    private nonisolated static func incoming(_ n: UNNotification) -> Incoming {342        let content = n.request.content343        return Incoming(route: NotificationRoute(userInfo: content.userInfo), payload: NotificationPayload(userInfo: content.userInfo), threadKey: content.threadIdentifier.isEmpty ? nil : content.threadIdentifier,344                        identifier: n.request.identifier, isRemote: n.request.trigger is UNPushNotificationTrigger)345    }346347    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {348        let incoming = Self.incoming(notification), done = Completion(call: completionHandler)349        Task { @MainActor in done.call(self.present(incoming)) }350    }351352    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {353        let content = response.notification.request.content354        let command = NotificationCommand.resolve(actionIdentifier: response.actionIdentifier, userInfo: content.userInfo, replyText: (response as? UNTextInputNotificationResponse)?.userText)355        let identifier = response.notification.request.identifier, done = Completion<Void>(call: { completionHandler() })356        Task { @MainActor in357            await self.respond(command, identifier: identifier)358            done.call(())359        }360    }361}362
Files main
Menu

Theme