// Cotton Chat's notifications on this phone, made to match the core's// `chat.notices` (assets/design/chat/CONTRACT.md, "Notifications").//// A message's notification is the push's, rewritten by the extension// (`App/ChatNotifications`) and filed under its conversation. What this keeps// is the rest://// - the CATEGORIES, registered at launch (iOS looks a category up in what the// app registered, so one registered late draws a plain banner): Reply and// Mark as read on a conversation's, Call back on a missed call's, in the// words `chat.notices` answers, the kit's until it has;// - the RESPONSES: a tap opens that chat in Chat's own thread screen// (`ChatOpening`); Reply is `chat.act send`, then `chat.act read`, then// `chat.flush`; Mark as read is `chat.act read`, then `chat.flush`; each// then asks `chat.notices` again;// - the RECONCILE: after anything lands or is read (`.cottonChatLanded`,// `.cottonChatRead`), a background push and the app coming to the front,// `chat.notices` is asked and every delivered chat notification whose// conversation it no longer lists is taken away (read here, on another of// the person's phones, or by its own Mark as read), as is every missed// call's it no longer lists; a missed call it lists and this phone does// not show is posted, under its `call`;// - the KEEP: `chat.keep { unmetered }` when the app comes to the front and// after a push lands, so no file is lost to the chat store's 30-day sweep// (videos and files wait for a network that is not metered).//// Every rule is the core's: this asks and draws its answers.#if os(iOS)importCottonKitimportCottonMailboximportCottonUIimportFoundationimportNetworkimportUserNotifications@MainActorfinalclassChatNotifier {privatelet center: ChatCenterprivatelet network = ChatNetwork()privatelet log: @Sendable (String) -> Voidprivatevar soonTask: Task<Void, Never>?privatevar observers: [any NSObjectProtocol] = []init(center: ChatCenter, log: @escaping @Sendable (String) -> Void) {self.center = centerself.log = log register(words: nil, back: nil)ChatNotificationHooks.respond = { [weakself] response inawaitself?.respond(response) }ChatNotificationHooks.woke = { [weakself] inawaitself?.woke() ?? false }for name in [Notification.Name.cottonChatLanded, .cottonChatRead] { observers.append(NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { [weakself] _ inMainActor.assumeIsolated { self?.soon() } }) } }// MARK: The app's life/// The app came to the front: the shade made to match, and what no phone kept is kept.func foregrounded() async {await reconcile()await keep() }/// A background push with chat news (the read nudge): land, match, keep.func woke() async -> Bool {await center.landWaiting()await reconcile()await keep()returntrue }/// Several landings in a row ask once.privatefunc soon() { soonTask?.cancel() soonTask = Task { @MainActor [weakself] intry? awaitTask.sleep(for: .milliseconds(400))guard !Task.isCancelled else { return }awaitself?.reconcile() } }// MARK: The categories/// Reply and Mark as read, Call back, in the core's words when it has/// answered them (`chat.notices`' `words`, a missed call's `back`), the/// kit's lines until then.privatefunc register(words: JSONValue?, back: String?) {let replyWord = words?["reply"]?.string ?? ShellLines.line("chat", "app.notice.reply")let reply = UNTextInputNotificationAction(// AUDIT E (a stolen phone): a reply from the lock screen asks Face ID or the passcode first. identifier: ChatNoticeNames.reply, title: replyWord, options: [.authenticationRequired], textInputButtonTitle: replyWord, textInputPlaceholder: words?["replyHint"]?.string ?? ShellLines.line("chat", "app.notice.reply_hint"))let markRead = UNNotificationAction( identifier: ChatNoticeNames.markRead, title: words?["markRead"]?.string ?? ShellLines.line("chat", "app.notice.mark_read"), options: [.authenticationRequired])let message = UNNotificationCategory(identifier: ChatNoticeNames.category, actions: [reply, markRead], intentIdentifiers: [], options: [])// Calling back opens the app: the call screen is the app's.let callBack = UNNotificationAction( identifier: ChatNoticeNames.callBack, title: back ?? ShellLines.line("chat", "app.call.back"), options: [.foreground])let missed = UNNotificationCategory(identifier: ChatNoticeNames.missedCategory, actions: [callBack], intentIdentifiers: [], options: []) UNUserNotificationCenter.current().setNotificationCategories([message, missed]) }// MARK: The responsesfunc respond(_ response: ChatNotificationResponse) async {let info = response.userInfoguard response.action != UNNotificationDismissActionIdentifier else { return }iflet call = info["call"]?.string {if response.action == ChatNoticeNames.callBack {ChatNotificationHooks.callBack?(call) } elseiflet thread = info["thread"]?.string {ChatOpening.shared.open(thread: thread) }return }switch response.action {caseChatNoticeNames.reply, ChatNoticeNames.markRead:// What the push said is landed first, so the read covers it.await center.landWaiting()guardlet thread = await thread(of: info) else { return }if response.action == ChatNoticeNames.reply {let text = response.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""if !text.isEmpty {do { _ = tryawait center.call("chat.act", ["act": "send", "thread": .string(thread), "text": .string(text)]) } catch { log("chat: a reply from a notification was refused: \((error as? CottonCallError)?.code ?? "refused")") } } }await read(thread, flushing: response.action == ChatNoticeNames.reply)default:// A tap: that chat, in Chat's own thread screen.guardlet thread = await thread(of: info) else { return }ChatOpening.shared.open(thread: thread) } }/// The chat read, the person's other phones told when the core says/// (`flush`), and the shade made to match.privatefunc read(_ thread: String, flushing: Bool) async {let answer = try? await center.call("chat.act", ["act": "read", "thread": .string(thread)])if flushing || answer?["flush"]?.bool == true { await center.flushNow() }NotificationCenter.default.post(name: .cottonChatRead, object: nil, userInfo: ["thread": thread])await reconcile() }/// The thread a notification is for: as the extension filed it, as the/// app last landed its number, or the number's own chat (`chat.start`)./// A group's with no thread said is none: its sender's chat is not it.privatefunc thread(of info: JSONValue) async -> String? {iflet thread = info["thread"]?.string { return thread }guardlet peer = info["peer"]?.string, !peer.isEmpty, info["group"] == nilelse { returnnil }iflet thread = ChatThreads.read()[peer] { return thread }returntry? await center.start(number: peer, person: nil) }// MARK: The reconcile/// `chat.notices`, and the shade made to match it.func reconcile() async {let answer: JSONValuedo { answer = tryawait center.call("chat.notices") } catch { log("chat: notices refused \((error as? CottonCallError)?.code ?? "")")return }let notices = answer["notices"]?.array ?? []let missed = answer["missed"]?.array ?? [] register(words: answer["words"], back: missed.first?["back"]?.string)let listed = Set(notices.compactMap { $0["thread"]?.string })let calls = Set(missed.compactMap { $0["call"]?.string })let threads = ChatThreads.read()var gone: [String] = []var shown: Set<String> = []for (identifier, info) inawaitSelf.delivered() whereChatNotificationHooks.isChat(info) {iflet call = info["call"]?.string {if calls.contains(call) { shown.insert(call) } else { gone.append(identifier) }continue }let thread = info["thread"]?.string ?? info["peer"]?.string.flatMap { threads[$0] }iflet thread {if !listed.contains(thread) { gone.append(identifier) } } elseif listed.isEmpty {// A push the app cannot place: nothing is unread anywhere, so it is not either. gone.append(identifier) } }if !gone.isEmpty { UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: gone) }for one in missed {guardlet call = one["call"]?.string, !shown.contains(call) else { continue } post(missed: one, call: call) } }/// Every notification of this app's in Notification Centre, as its/// identifier and `userInfo`. Nonisolated: the system answers on a queue/// of its own, never the main actor's. nonisolated privatestaticfunc delivered() async -> [(String, JSONValue)] {await withCheckedContinuation { continuation in UNUserNotificationCenter.current().getDeliveredNotifications { notes in continuation.resume(returning: notes.map { ($0.request.identifier, NotificationTaps.value(of: $0.request.content.userInfo)) }) } } }/// One missed call, as the core says it: its title, who, and Call back.privatefunc post(missed: JSONValue, call: String) {let content = UNMutableNotificationContent() content.title = missed["title"]?.string ?? "" content.body = missed["text"]?.string ?? "" content.sound = .default content.categoryIdentifier = ChatNoticeNames.missedCategoryvar info: [String: Any] = ["chat": 1, "call": call]iflet thread = missed["thread"]?.string { info["thread"] = thread content.threadIdentifier = thread } content.userInfo = infoSelf.add(UNNotificationRequest(identifier: ChatNoticeNames.missedPrefix + call, content: content, trigger: nil), log: log) }/// Posted; the system answers on a queue of its own, never the main actor's. nonisolated privatestaticfunc add(_ request: UNNotificationRequest, log: @escaping @Sendable (String) -> Void) { UNUserNotificationCenter.current().add(request) { error iniflet error { log("chat: a missed call was not posted: \(error)") } } }// MARK: The keep/// What no phone of the person's kept from the last 30 days, kept now.privatefunc keep() async {do { _ = tryawait center.call("chat.keep", ["unmetered": .bool(network.unmetered)]) } catch { log("chat: keep refused \((error as? CottonCallError)?.code ?? "")") }// Then the pictures a chat opened next will show (CONTRACT "Pictures at once"): never in Low Data Mode.do { _ = tryawait center.call("chat.warm", ["constrained": .bool(network.constrained)]) } catch { log("chat: warm refused \((error as? CottonCallError)?.code ?? "")") } }}/// Whether this phone's network is one a video may come down on: not/// metered (`isExpensive`, a hotspot or cellular) and not Low Data Mode.finalclassChatNetwork: @unchecked Sendable {privatelet monitor = NWPathMonitor()privatelet lock = NSLock()privatevar cheap = falseprivatevar low = falseinit() { monitor.pathUpdateHandler = { [weakself] path inlet unmetered = path.status == .satisfied && !path.isExpensive && !path.isConstrainedguardletselfelse { return }self.lock.withLock {self.cheap = unmeteredself.low = path.isConstrained } } monitor.start(queue: DispatchQueue(label: "com.cottondb.chat.network", qos: .utility)) }var unmetered: Bool { lock.withLock { cheap } }/// Low Data Mode: nothing is fetched in the background.var constrained: Bool { lock.withLock { low } }}#endif