SPB Git

Repository Public

NotificationService.swift 7.2 KB 142 lines swift

1// SP Wallet iOS2// File: Core/System/NotificationService.swift3// Description: Local notifications for NEW alert rows returned by the server (there is no APNs path on the server). Only the4//              kinds listed in `AlertNotificationPolicy` notify; the others stay in the app. The text is the catalogue's5//              lock-screen wording (no amount, no address, no reason text). Nothing is ever notified from a client-side guess:6//              the only input is `WalletAlert` rows.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPWalletCore12import UserNotifications1314/** Which server alert kinds raise a local notification, and with what content. Pure: no system call. */15enum AlertNotificationPolicy {16    enum Category: String, CaseIterable, Sendable {17        case transaction, order, liquidation, riskLimit, signingError, agentStopped, signerState18    }1920    /**21     The category of a kind, nil when the kind stays in-app. Simulated (paper) fills and liquidations stay in-app: a22     notification must not make a simulation look like an event on real funds. The catalogue has no "large portfolio move"23     kind: the server does not emit such an alert, so the app does not notify one.24     */25    static func category(_ kind: AlertKind) -> Category? {26        switch kind {27        case .transferConfirmed, .transferFailed, .swapConfirmed, .swapFailed, .bridgeConfirmed, .bridgeFailed: .transaction28        case .agentOrderFilled, .derivLiveFilled: .order29        case .derivLiveLiquidation: .liquidation30        case .derivLossLimit, .derivHalt, .derivMarginWarning: .riskLimit31        case .securitySignerRefused, .agentMmSignerRefusals: .signingError32        case .agentStopped, .agentStoppedLoss, .agentStoppedMandate, .agentMmHalted: .agentStopped33        case .securitySignerUnreachable, .securitySignerBack, .securitySignerHalted, .securitySignerUnhalted, .securityKillSwitchOn, .securityKillSwitchOff: .signerState34        default: nil35        }36    }3738    /** `.critical` would bypass Focus and the mute switch and needs an Apple entitlement: never used. */39    enum Level: Equatable, Sendable { case active, timeSensitive }40    static func level(_ severity: AlertSeverity) -> Level { severity == .critical ? .timeSensitive : .active }4142    struct Content: Equatable, Sendable {43        let identifier: String44        let title: String45        let body: String46        let level: Level47        let category: Category48        let alertId: Int6449    }5051    /** nil when the row does not notify: unknown kind, in-app kind, already read, or held back by the owner's server-side rules. */52    static func content(for a: WalletAlert, locale: AlertLocale) -> Content? {53        guard let cat = category(a.kind), !a.isRead else { return nil }54        // the owner's quiet hours and hourly cap are decided by the server; the app follows that decision instead of second-guessing it55        if a.delivery == .quiet || a.delivery == .capped || a.delivery == .stale { return nil }56        let t = a.text(locale: locale, detail: false)57        return Content(identifier: "alert-\(a.id)", title: t.title, body: t.body, level: level(a.severity), category: cat, alertId: a.id)58    }59}6061/** The system calls the app needs; replaced by a recorder in tests. */62@MainActor protocol NotificationPosting: AnyObject {63    func isAuthorized() async -> Bool64    func post(_ c: AlertNotificationPolicy.Content) async65    func setBadge(_ n: Int) async66}6768@MainActor final class SystemNotificationPoster: NotificationPosting {69    private var center: UNUserNotificationCenter { .current() }70    func isAuthorized() async -> Bool {71        let s = await center.notificationSettings().authorizationStatus72        return s == .authorized || s == .provisional73    }74    func post(_ c: AlertNotificationPolicy.Content) async {75        let n = UNMutableNotificationContent()76        n.title = c.title; n.body = c.body; n.sound = .default77        n.threadIdentifier = c.category.rawValue78        n.interruptionLevel = c.level == .timeSensitive ? .timeSensitive : .active79        n.userInfo = ["spwallet": "alert", "alertId": NSNumber(value: c.alertId)]80        // same identifier for the same server row: even a repeated call replaces, never duplicates81        try? await center.add(UNNotificationRequest(identifier: c.identifier, content: n, trigger: nil))82    }83    func setBadge(_ n: Int) async { try? await center.setBadgeCount(max(n, 0)) }84}8586@MainActor final class NotificationService: AlertNotifying {87    private let enabled: @MainActor () -> Bool88    private let poster: NotificationPosting89    private let locale: @MainActor () -> AlertLocale9091    init(enabled: @escaping @MainActor () -> Bool, poster: NotificationPosting, locale: @escaping @MainActor () -> AlertLocale = { AlertPresentation.locale }) {92        self.enabled = enabled; self.poster = poster; self.locale = locale93    }94    convenience init(preferences: Preferences) {95        self.init(enabled: { [weak preferences] in preferences?.notifications ?? false }, poster: SystemNotificationPoster())96    }9798    /** One notification per new row of a notifying kind — only when the owner turned notifications on AND iOS allows them. */99    func notify(_ rows: [WalletAlert]) async {100        guard enabled(), await poster.isAuthorized() else { return }101        let l = locale()102        for c in rows.compactMap({ AlertNotificationPolicy.content(for: $0, locale: l) }) { await poster.post(c) }103    }104105    /** The icon badge is the server's unread count; without the owner's switch and iOS's permission nothing is set. */106    func setBadge(_ unread: Int) async {107        guard enabled(), await poster.isAuthorized() else { return }108        await poster.setBadge(unread)109    }110}111112/**113 Tapping a notification opens the alert centre — navigation only, nothing else.114 `activate()` in the App's `init` (the delegate must exist before launch ends, or a tap that starts the app is lost), then115 `install { router.section = .alerts }` once the router exists; a tap received in between is delivered at that moment.116 */117final class NotificationTapHandler: NSObject, UNUserNotificationCenterDelegate, @unchecked Sendable {118    static let shared = NotificationTapHandler()119    @MainActor private var open: (@MainActor () -> Void)?120    @MainActor private var pending = false121122    func activate() { UNUserNotificationCenter.current().delegate = self }123124    @MainActor func install(open: @escaping @MainActor () -> Void) {125        self.open = open126        if pending { pending = false; open() }127    }128129    @MainActor func tapped() { if let open { open() } else { pending = true } }130131    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {132        let ours = response.notification.request.content.userInfo["spwallet"] as? String == "alert"133        guard ours, response.actionIdentifier == UNNotificationDefaultActionIdentifier else { return }134        await MainActor.run { self.tapped() }135    }136137    /** While the app is open the banner is still shown: the row is real and the owner asked to be told. */138    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {139        [.banner, .list, .sound]140    }141}142
Files main
Menu

Theme