// 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) import CottonKit import CottonMailbox import CottonUI import Foundation import Network import UserNotifications @MainActor final class ChatNotifier { private let center: ChatCenter private let network = ChatNetwork() private let log: @Sendable (String) -> Void private var soonTask: Task? private var observers: [any NSObjectProtocol] = [] init(center: ChatCenter, log: @escaping @Sendable (String) -> Void) { self.center = center self.log = log register(words: nil, back: nil) ChatNotificationHooks.respond = { [weak self] response in await self?.respond(response) } ChatNotificationHooks.woke = { [weak self] in await self?.woke() ?? false } for name in [Notification.Name.cottonChatLanded, .cottonChatRead] { observers.append(NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in MainActor.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() return true } /// Several landings in a row ask once. private func soon() { soonTask?.cancel() soonTask = Task { @MainActor [weak self] in try? await Task.sleep(for: .milliseconds(400)) guard !Task.isCancelled else { return } await self?.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. private func 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 responses func respond(_ response: ChatNotificationResponse) async { let info = response.userInfo guard response.action != UNNotificationDismissActionIdentifier else { return } if let call = info["call"]?.string { if response.action == ChatNoticeNames.callBack { ChatNotificationHooks.callBack?(call) } else if let thread = info["thread"]?.string { ChatOpening.shared.open(thread: thread) } return } switch response.action { case ChatNoticeNames.reply, ChatNoticeNames.markRead: // What the push said is landed first, so the read covers it. await center.landWaiting() guard let thread = await thread(of: info) else { return } if response.action == ChatNoticeNames.reply { let text = response.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" if !text.isEmpty { do { _ = try await 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. guard let 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. private func 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. private func thread(of info: JSONValue) async -> String? { if let thread = info["thread"]?.string { return thread } guard let peer = info["peer"]?.string, !peer.isEmpty, info["group"] == nil else { return nil } if let thread = ChatThreads.read()[peer] { return thread } return try? await center.start(number: peer, person: nil) } // MARK: The reconcile /// `chat.notices`, and the shade made to match it. func reconcile() async { let answer: JSONValue do { answer = try await 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 = [] for (identifier, info) in await Self.delivered() where ChatNotificationHooks.isChat(info) { if let 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] } if let thread { if !listed.contains(thread) { gone.append(identifier) } } else if 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 { guard let 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 private static func 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. private func post(missed: JSONValue, call: String) { let content = UNMutableNotificationContent() content.title = missed["title"]?.string ?? "" content.body = missed["text"]?.string ?? "" content.sound = .default content.categoryIdentifier = ChatNoticeNames.missedCategory var info: [String: Any] = ["chat": 1, "call": call] if let thread = missed["thread"]?.string { info["thread"] = thread content.threadIdentifier = thread } content.userInfo = info Self.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 private static func add(_ request: UNNotificationRequest, log: @escaping @Sendable (String) -> Void) { UNUserNotificationCenter.current().add(request) { error in if let 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. private func keep() async { do { _ = try await 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 { _ = try await 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. final class ChatNetwork: @unchecked Sendable { private let monitor = NWPathMonitor() private let lock = NSLock() private var cheap = false private var low = false init() { monitor.pathUpdateHandler = { [weak self] path in let unmetered = path.status == .satisfied && !path.isExpensive && !path.isConstrained guard let self else { return } self.lock.withLock { self.cheap = unmetered self.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