Cotton code
123 lines · 5.4 KB · SwiftRaw
// What the notification extension says for a chat push, read from the push// itself without the core or the network: the sealed box the object put in// it, opened (`ChatBox`), titled with the name the app last wrote into the// app group (`ChatNames`), the number where it has none.//// It lands nothing: the app's `chat.incoming` takes, checks and lands every// item when it next opens. And it stays quiet rather than guess: a stranger's// request comes with no box (the object keeps their words off a lock screen// until the person accepts them), and a box that does not open, or opens to// something other than a message, keeps "New message".import Foundation/// A rewritten alert: the sender, and the words when the message has some.public struct ChatAlertWords: Equatable, Sendable {    public var title: String    public var body: String?    /// The sender's number (`+` and digits), as the box says it.    public var from: String    /// The group it was said in (its id), when it was.    public var group: String?    public init(title: String, body: String?, from: String = "", group: String? = nil) {        self.title = title        self.body = body        self.from = from        self.group = group    }    /// The conversation the alert is grouped under when the app has not yet    /// said its thread (`ChatThreads`): the group, else the number.    public var conversation: String { group ?? from }}public enum ChatAlert {    struct Payload: Decodable {        var kind: String        var from: String        var body: String?        var group: String?    }    /// The words for a pushed box, or nil to keep the push's own.    public static func words(box: String?, privateKey: String, names: [String: String]) -> ChatAlertWords? {        guard let box,            let opened = ChatBox.open(box, privateKey: privateKey),            let payload = try? JSONDecoder().decode(Payload.self, from: opened.payload),            payload.kind == "message", !payload.from.isEmpty        else { return nil }        let body = payload.body?.trimmingCharacters(in: .whitespacesAndNewlines)        return ChatAlertWords(title: names[payload.from] ?? payload.from, body: body?.isEmpty == false ? body : nil,                              from: payload.from, group: payload.group?.isEmpty == false ? payload.group : nil)    }}/// The thread the core lands each Cotton conversation in, by its number/// (`chat.incoming`'s `landed` and `chat.start` say both), kept in the app/// group's defaults so the extension files an alert under the thread the/// app's `chat.notices` names, and a tap or a reply finds it. Only ids and/// numbers: never words, never keys.public enum ChatThreads {    static let key = "cotton.chat.threads"    public static func read(from defaults: UserDefaults? = ChatNames.defaults()) -> [String: String] {        defaults?.dictionary(forKey: key) as? [String: String] ?? [:]    }    public static func remember(_ threads: [String: String], in defaults: UserDefaults? = ChatNames.defaults()) {        guard let defaults else { return }        var held = read(from: defaults)        let fresh = threads.filter { !$0.key.isEmpty && !$0.value.isEmpty }        guard fresh.contains(where: { held[$0.key] != $0.value }) else { return }        held.merge(fresh) { _, new in new }        defaults.set(held, forKey: key)    }    public static func forget(in defaults: UserDefaults? = ChatNames.defaults()) {        defaults?.removeObject(forKey: key)    }}/// The names the app knows its Cotton chats by, number to name, kept in the/// app group's defaults for the extension. Only names: never words, never keys.public enum ChatNames {    static let key = "cotton.chat.names"    public static func defaults(bundleIdentifier: String? = Bundle.main.bundleIdentifier) -> UserDefaults? {        UserDefaults(suiteName: CottonDefaults.appGroup(bundleIdentifier: bundleIdentifier))    }    public static func read(from defaults: UserDefaults? = defaults()) -> [String: String] {        defaults?.dictionary(forKey: key) as? [String: String] ?? [:]    }    /// Names merged into what is kept; a blank name is not one.    public static func remember(_ names: [String: String], in defaults: UserDefaults? = defaults()) {        guard let defaults else { return }        var held = read(from: defaults)        let fresh = names.filter { !$0.value.trimmingCharacters(in: .whitespaces).isEmpty }        guard fresh.contains(where: { held[$0.key] != $0.value }) else { return }        held.merge(fresh) { _, new in new }        defaults.set(held, forKey: key)    }    public static func forget(in defaults: UserDefaults? = defaults()) {        defaults?.removeObject(forKey: key)    }}/// The names Cotton Chat's notifications are filed and answered under, the/// same in the extension that rewrites a push and in the app that registers/// the categories and answers their actions.public enum ChatNoticeNames {    /// A conversation's notification: Reply and Mark as read.    public static let category = "chat.message"    public static let reply = "chat.reply"    public static let markRead = "chat.read"    /// A missed call's notification: Call back.    public static let missedCategory = "chat.missed"    public static let callBack = "chat.callBack"    /// A missed call's notification identifier: this, then the call.    public static let missedPrefix = "chat.missed."}