Cotton code
226 lines · 10.9 KB · SwiftRaw
// The one thing SwiftUI cannot do: the APNs token, and the tap callback.//// `didRegisterForRemoteNotificationsWithDeviceToken` has no SwiftUI equivalent// and `UNUserNotificationCenterDelegate` has to be set on a live object before// any notification can be delivered to it, so the app takes a// `UIApplicationDelegateAdaptor` — and this class does four things and nothing// else:////   1. sets itself as the notification centre's delegate, at launch, before any//      push can arrive;//   2. registers the `cotton_message` REPLY category, also at launch — iOS looks//      a category identifier up in what the app registered, so one registered//      lazily renders as a plain banner with no action;//   3. turns the raw token into the lowercase hex APNs wants and leaves it on//      the bridge;//   4. turns a tap into a `NotificationTap` and leaves that on the bridge too,//      and a push presented or tapped into its `PushReceipt` beside it;//   5. re-attaches the first copy's background download at launch, and hands//      iOS's background-events call to it (`CottonAppDelegate+FirstCopy.swift`)//      — the transfer iOS carried while the app was suspended or gone is//      delivered to this process before anything asks;//   6. registers the two background catch-up tasks, at launch, because iOS//      takes a task's handler only before launch has finished//      (`Sync/BackgroundCatchUp.swift`);//   7. answers a push that woke the app in the background with one slice of//      the same catch-up;//   8. in Cotton Chat, hands the chat's own responses (a tap, Reply, Mark as//      read, Call back) and its read nudge to the chat engine//      (`ChatNotificationHooks`), which the engine fills at launch.//// Everything after that is `NotificationsModel`'s. This class holds no state,// reaches no core, and decides nothing.#if os(iOS)import CottonKit#if canImport(UIKit)import CottonVoiceimport UIKit#endifimport UserNotifications/// `@MainActor` because both protocols it adopts are: `UIApplicationDelegate`/// and `UNUserNotificationCenterDelegate` are main-actor-isolated in the SDK,/// and a class that were not would have every callback crossing into isolated/// code. It costs nothing here — the class holds no state and hands everything/// to `NotificationBridge`, which is main-actor too.@MainActorpublic final class CottonAppDelegate: NSObject, UIApplicationDelegate {    public func application(        _ application: UIApplication,        didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil    ) -> Bool {        UNUserNotificationCenter.current().delegate = self        // HERE AND ONLY HERE: a handler registered after launch has finished        // makes iOS raise, and a launch in the background — the app was not        // running when a task came due — reaches no view at all.        BackgroundCatchUp.registerTasks()        BackgroundCatchUp.shared.use(scheduler: SystemCatchUpScheduler())        // Albums' first pass, carried on in the phone's processing time (`Albums/AlbumsPass.swift`); only Albums'        // plist permits its identifiers, so every other app registers nothing.        AlbumsPass.registerTasks()        AlbumsKeeper.registerTask()        // A film's bundle or file iOS was carrying when the app went: its        // session made again, so what landed is handed to this process.        FilmKeeper.shared.wake()        for downloads in KeptDownloads.all { downloads.wake() }        return true    }    /// iOS finished a film's bundle or a book while the app was gone, and    /// woke it to say so (`FilmKeeper`, `KeptDownloads`).    public func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String,                            completionHandler: @escaping () -> Void) {        switch identifier {        case FilmKeeper.session: FilmKeeper.shared.wake(completionHandler)        default:            // A voice model's files, fetched in the background.            if VoiceModelStore.handleBackgroundEvents(identifier: identifier, completion: completionHandler) { return }            guard let downloads = KeptDownloads.all.first(where: { $0.identifier == identifier }) else { return completionHandler() }            downloads.wake(completionHandler)        }    }    /// APNs handed over a token.    ///    /// The hex string is what the rail wants: `apns.rs` posts to    /// `/3/device/{token}` with exactly this spelling.    ///    /// **`registerForRemoteNotifications()` is never called from here** — the    /// model calls it once the permission is `granted`, because asking APNs for    /// a token before the person has said yes is a token for a phone that will    /// never show a banner.    public func application(        _ application: UIApplication,        didRegisterForRemoteNotificationsWithDeviceToken token: Data    ) {        let hex = token.map { String(format: "%02x", $0) }.joined()        NotificationBridge.shared.token(hex)    }    /// APNs would not.    ///    /// **Reported and nothing else.** A device with no token is a quiet phone,    /// not an error screen: every local reminder still fires, and the next    /// launch asks again.    public func application(        _ application: UIApplication,        didFailToRegisterForRemoteNotificationsWithError error: Error    ) {        NotificationBridge.shared.tokenFailed(String(describing: error))    }    /// A push woke the app in the background — the Mac's silent wake for a    /// phone that is behind, or any push that carries `content-available`.    ///    /// A wake carries no record content, by rule (`push/rail.rs`,    /// `wake_device`): of data only the database whose receipt head moved    /// (`body.databaseId`), sent at most once a minute per device. What is new    /// is on the Mac, and the way to have it is to ask: every wake is answered    /// with one time-boxed receipts slice (`sync.now`, which exchanges every    /// database this phone holds in one pass, records before bytes), inside    /// the thirty seconds iOS gives — and iOS is told when it is over, which    /// is what keeps the next wake coming. The database id is only logged.    public func application(        _ application: UIApplication,        didReceiveRemoteNotification userInfo: [AnyHashable: Any],        fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void    ) {        // Cotton Chat's read nudge (`{ aps: { content-available }, chat: 1,        // read: 1 }`): what waits is landed and the chat's notifications made        // to match (`ChatNotificationHooks`), inside the time iOS gives.        if let woke = ChatNotificationHooks.woke, ChatNotificationHooks.isChat(NotificationTaps.value(of: userInfo)) {            Task { @MainActor in                let asked = await woke()                completionHandler(asked ? .newData : .failed)            }            return        }        if let database = Self.wokenDatabase(userInfo) { Log.write("catch-up: woken for database \(database)") }        Task { @MainActor in            let caughtUp = await BackgroundCatchUp.shared.runRefresh()            completionHandler(caughtUp ? .newData : .failed)        }    }}extension CottonAppDelegate {    /// The database a silent wake names (`{"aps": {"content-available": 1},    /// "body": {"databaseId": …}}`), or nil for any other push.    nonisolated static func wokenDatabase(_ userInfo: [AnyHashable: Any]) -> String? {        ((userInfo["body"] as? [String: Any])?["databaseId"] as? String).flatMap { $0.isEmpty ? nil : $0 }    }}/// `@preconcurrency` on the conformance, and it is the documented spelling/// rather than a silencer: `UNUserNotificationCenterDelegate` is an Objective-C/// protocol with no isolation of its own, while both callbacks below are/// main-actor work on a main-actor class. Without it the compiler reads a/// main-actor witness for a nonisolated requirement as a crossing it cannot/// check. UIKit calls these on the main thread; the attribute is what says so.extension CottonAppDelegate: @preconcurrency UNUserNotificationCenterDelegate {    /// A tap, or an action. ONE callback for both tap tables, because iOS gives    /// one.    public func userNotificationCenter(        _ center: UNUserNotificationCenter,        didReceive response: UNNotificationResponse,        withCompletionHandler completion: @escaping () -> Void    ) {        let request = response.notification.request        // Cotton Post's own: a tap opens that conversation (`Post/PostRings.swift`).        #if os(iOS)        if let thread = PostRings.thread(of: request.content.userInfo) {            PostRings.tapped(thread)            completion()            return        }        #endif        let userInfo = NotificationTaps.value(of: request.content.userInfo)        // Cotton Chat's own: a tap opens the chat, Reply and Mark as read are        // answered by the chat engine before iOS is told it is done.        if let respond = ChatNotificationHooks.respond, ChatNotificationHooks.isChat(userInfo) {            let chat = ChatNotificationResponse(                action: response.actionIdentifier, userInfo: userInfo,                text: (response as? UNTextInputNotificationResponse)?.userText, identifier: request.identifier)            Task { @MainActor in                await respond(chat)                completion()            }            return        }        if let receipt = PushReceipt.of(userInfo: userInfo, date: response.notification.date, how: .opened) {            NotificationBridge.shared.met(receipt)        }        let tap = NotificationTap(            userInfo: userInfo,            identifier: request.identifier,            actionIdentifier: response.actionIdentifier        )        NotificationBridge.shared.arrive(tap)        completion()    }    /// A reminder that fires while the app is open.    ///    /// Without this iOS delivers a foreground notification SILENTLY, so a    /// reminder that fires while you are reading the very list it is about    /// would simply not appear.    ///    /// **No `.badge`, deliberately.** The app-icon badge is computed by the    /// sync loop (4g's lane) from the unread total; letting a notification    /// increment it here would be a second writer of one number.    public func userNotificationCenter(        _ center: UNUserNotificationCenter,        willPresent notification: UNNotification,        withCompletionHandler completion: @escaping (UNNotificationPresentationOptions) -> Void    ) {        // A server push shown while the app is open is the phone's receipt        // of it (`PushReceipt`) — what Test push waits for.        let userInfo = NotificationTaps.value(of: notification.request.content.userInfo)        if let receipt = PushReceipt.of(userInfo: userInfo, date: notification.date, how: .shown) {            NotificationBridge.shared.met(receipt)        }        completion([.banner, .list, .sound])    }}#endif