Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/System/SystemServices.swift3// Description: The system-integration layer of the app in one place: push registration, notification handling, the state shared with the4// extensions (widgets, share extension, notification service), Spotlight, deep links and background work. AppModel calls the few lifecycle5// hooks below; nothing here is a screen.6import SPMailCore7import SPMailSystem8import SwiftUI9#if os(macOS)10import AppKit11#else12import UIKit13#endif1415/// The one AppModel of the process. Push and background launches run without any window: delegates and intents must reach the model16/// without waiting for a view to appear.17@MainActor18enum AppRuntime {19 static let model = AppModel()20}2122@MainActor23final class SystemServices {24 unowned let app: AppModel25 let next: NextAPI26 let push: PushRegistrar27 let notifications: NotificationCoordinator28 let shared: SharedStateWriter29 let router: DeepLinkRouter30 private var observers: [NSObjectProtocol] = []31 private var installed = false3233 init(app: AppModel) {34 self.app = app35 next = NextAPI(app.api)36 push = PushRegistrar(app: app, next: next)37 notifications = NotificationCoordinator(app: app, next: next)38 shared = SharedStateWriter(app: app, next: next)39 router = DeepLinkRouter(app: app)40 }4142 /// Once per process, as early as possible (application delegate): the notification delegate must be set before the launch finishes,43 /// or a tap that started the app is lost.44 func install() {45 guard !installed else { return }46 installed = true47 notifications.install()48 let center = NotificationCenter.default49 func on(_ name: Notification.Name, _ body: @escaping @MainActor (SystemServices) -> Void) {50 observers.append(center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { if let self { body(self) } } })51 }52 // registered after LockController's own observers, so the lock state read here is the new one53 #if os(macOS)54 on(NSApplication.didResignActiveNotification) { $0.appDidLeave() }55 on(NSApplication.didHideNotification) { $0.appDidLeave() }56 on(NSApplication.didBecomeActiveNotification) { $0.appDidReturn() }57 #else58 on(UIApplication.didEnterBackgroundNotification) { $0.appDidLeave() }59 on(UIApplication.didBecomeActiveNotification) { $0.appDidReturn() }60 #endif61 on(.NSProcessInfoPowerStateDidChange) { $0.powerStateChanged() }62 BackgroundWork.install(app)63 }6465 // MARK: lifecycle hooks (called by AppModel)6667 /// A session is running (launch with a stored token, or sign-in). `prompt: false` never shows the system permission sheet.68 func sessionStarted(prompt: Bool = true) async {69 shared.sessionStarted()70 notifications.registerCategories()71 await push.sessionStarted(prompt: prompt)72 shared.scheduleSnapshot()73 await router.flush()74 await shared.importSharedDrafts()75 }76 /// Sign-out, before the session is revoked: the server forgets this device's token.77 func sessionEnding() async { await push.unregister() }78 /// Sign-out or revoked session: nothing of the account stays visible outside the app.79 func sessionEnded() {80 push.sessionEnded()81 shared.sessionEnded()82 notifications.sessionEnded()83 Spotlight.removeAll()84 router.reset()85 }86 func mailboxesReloaded() {87 notifications.recomputeBadge()88 shared.scheduleSnapshot()89 }90 func emailsChanged(account: String) {91 shared.scheduleSnapshot()92 Spotlight.reconcile(account: account, app: app)93 }94 func newMail(_ list: [EmailSummary], account: String) async {95 Spotlight.index(list, account: account, app: app)96 await notifications.announceLocally(list, account: account)97 }98 func accountDetached(_ id: String) {99 Spotlight.remove(account: id)100 notifications.removeDelivered(account: id)101 shared.scheduleSnapshot()102 }103104 // MARK: app activity105106 private func appDidLeave() {107 shared.writeState()108 BackgroundWork.schedule(app)109 }110 private func appDidReturn() {111 shared.writeState()112 Task {113 await shared.importSharedDrafts()114 await push.refreshAuthorization()115 await router.flush()116 }117 }118 private func powerStateChanged() { BackgroundWork.schedule(app) }119}120