import Foundation import UserNotifications #if os(iOS) import UIKit #else import AppKit #endif /// What the app model needs from the system's notifications. The apps use /// `SystemNotifications`; tests use a fake. @MainActor public protocol NotificationSystem: AnyObject { /// Asks to show alerts, badges and sounds (the system asks only once), /// then registers with APNs for this device's token. func askAndRegister() /// The app icon's badge: the person's Needs you count. func setBadge(_ count: Int) /// Signed out: stop receiving pushes at all, and clear what was shown, /// whether or not the server heard of the sign-out. func unregister() } /// Asking for permission, then registering with APNs, so that a sign-out /// while the permission prompt is still open is never undone by it: each /// request is stamped, and `stop` makes every earlier one stale. @MainActor public final class RemoteRegistration { private let authorize: @MainActor () async -> Void private let register: @MainActor () -> Void private let unregister: @MainActor () -> Void private var stamp = 0 public init(authorize: @escaping @MainActor () async -> Void, register: @escaping @MainActor () -> Void, unregister: @escaping @MainActor () -> Void) { self.authorize = authorize; self.register = register; self.unregister = unregister } /// Stamped now, before any waiting: a sign-out straight after this /// call already makes it stale, even if its work has not started. @discardableResult public func request() -> Task { stamp += 1 let mine = stamp return Task { @MainActor in guard mine == self.stamp else { return } await self.authorize() guard mine == self.stamp else { return } self.register() } } public func stop() { stamp += 1 unregister() } } /// UserNotifications registration and foreground, unlock-required responses. /// Old and unknown payloads retain open-only navigation. @MainActor public final class SystemNotifications: NSObject, NotificationSystem, UNUserNotificationCenterDelegate { public static let needsYouCategory = "needs_you" /// Called with where a tapped notification goes. public var onResponse: ((NotificationResponse) -> Void)? public var onRoute: ((PushRoute) -> Void)? private let remote = RemoteRegistration( authorize: { _ = try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) }, register: { #if os(iOS) UIApplication.shared.registerForRemoteNotifications() #else NSApplication.shared.registerForRemoteNotifications() #endif }, unregister: { let center = UNUserNotificationCenter.current() center.removeAllDeliveredNotifications() center.removeAllPendingNotificationRequests() #if os(iOS) UIApplication.shared.unregisterForRemoteNotifications() #else NSApplication.shared.unregisterForRemoteNotifications() #endif }) public override init() { super.init() let center = UNUserNotificationCenter.current() center.delegate = self center.setNotificationCategories(NotificationCategories.all) } public func askAndRegister() { remote.request() } public func setBadge(_ count: Int) { UNUserNotificationCenter.current().setBadgeCount(max(0, count)) } public func unregister() { remote.stop() } /// In front, a card or a finished task still shows; a reply goes to the /// list only, since the conversation is right there. public nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { let route = PushRoute(userInfo: notification.request.content.userInfo) return route == .conversation ? [.list, .badge] : [.banner, .list, .sound, .badge] } public nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async { guard response.actionIdentifier != UNNotificationDismissActionIdentifier else { return } let content = response.notification.request.content if let action = NotificationResponse(userInfo: content.userInfo, category: content.categoryIdentifier, action: response.actionIdentifier, text: (response as? UNTextInputNotificationResponse)?.userText) { await MainActor.run { self.onResponse?(action) } } else if let route = PushRoute(userInfo: content.userInfo) { await MainActor.run { self.onRoute?(route) } } } }