Cotton code
244 lines · 13.3 KB · SwiftRaw
// A boundary adapter, not an email engine: Rust answers envelopes, aggregates// and mailbox state, and every write below calls its existing archive verbs.import CottonKitimport CottonValuesimport Foundationactor EmailRecords: Records, ActingRecords {    let core: any CottonCalling    let definitions: [TableDefinition]    init(core: any CottonCalling, definitions: [TableDefinition]) {        self.core = core        self.definitions = definitions    }    func tableDefinitions() async throws -> [TableDefinition] { definitions }    func count(table: String) async throws -> Int {        var count = 0        var offset = 0        while true {            let page = try await readPage(table: table, project: nil, query: nil, offset: offset, filter: [:])            count += page.records.count            guard let next = page.next else { return count }            offset = next        }    }    private struct EngineRecord: Decodable, Sendable {        let id: String        let data: [String: RecordValue]        var record: TableRecord { TableRecord(id: id, values: data) }    }    private struct EnginePage: Decodable, Sendable {        let records: [EngineRecord]        let next_page: Int?        let total: Int?    }    private struct ListArguments: Encodable, Sendable {        let table: String        let project: String?        let query: String?        let page: Int        let limit: Int        let `where`: [String: RecordValue]        /// One section of the reader's plan (`PlanView`): a view of the        /// Email tool that reads its own section (Today).        var section: String? = nil        var timezone: String? = nil        var day: String? = nil        var today: String? = nil    }    private struct GetArguments: Encodable, Sendable { let table: String; let id: String }    private func readPage(table: String, project: String?, query: String?, offset: Int, filter: [String: RecordValue], plan: PlanView? = nil) async throws -> RecordPage {        var arguments = ListArguments(table: table, project: project, query: query, page: offset, limit: 50, where: filter)        if let plan {            arguments.section = plan.section            arguments.timezone = plan.timezone            arguments.day = plan.day            arguments.today = plan.today ?? CottonDate.formatter("yyyy-MM-dd", Calendar.current).string(from: Date())        }        let answer = try await core.call(CottonMethod.recordsList, arguments, as: EnginePage.self)        return RecordPage(records: answer.records.map(\.record), next: answer.next_page, total: answer.total)    }    func list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) async throws -> RecordPage {        if table == "email_thread", filter.isEmpty,            let words = query?.trimmingCharacters(in: .whitespacesAndNewlines), !words.isEmpty {            return try await searched(words, offset: page)        }        return try await readPage(table: table, project: project, query: query, offset: page, filter: filter)    }    /// A view's section (Email's Today), read by the core's plan: never the    /// whole mailbox answered as if it were the section.    func list(        table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue], limit: Int?,        plan: PlanView    ) async throws -> RecordPage {        try await readPage(table: table, project: project, query: query, offset: page, filter: filter, plan: plan)    }    /// **The Mail screen's search box asks Find, scoped to mail** (mailsearch):    /// `read.find` with `scope: "mail"` answers one conversation per hit —    /// subject before body, the sender's name and address too, Junk found and    /// labelled — where the list's own `query` matched subjects alone. The    /// conversations are then read whole, a page at a time, in Find's order.    /// The first page asks Find again (a sync can bring new mail); a later page    /// reads on from the answer the first one kept. A sender's list (a `where`)    /// is still narrowed by the list's own read, which Find cannot narrow.    private var found: (query: String, threads: [String])?    private struct IdsArguments: Encodable, Sendable { let table: String; let ids: [String] }    private func searched(_ words: String, offset: Int) async throws -> RecordPage {        let threads: [String]        if offset > 0, let found, found.query == words {            threads = found.threads        } else {            let read = try await core.callJSON(CottonMethod.readFind, SearchRequest(query: words, scope: "mail", channel: "mail"))            threads = Self.threads(FindSection.all(read).flatMap(\.hits))            found = (words, threads)        }        let slice = Array(threads.dropFirst(offset).prefix(50))        guard !slice.isEmpty else { return RecordPage(records: [], next: nil, total: threads.count) }        let answer = try await core.call(            CottonMethod.recordsList, IdsArguments(table: "email_thread", ids: slice), as: EnginePage.self)        let next = offset + slice.count        return RecordPage(records: answer.records.map(\.record), next: next < threads.count ? next : nil, total: threads.count)    }    /// The conversations Find's mail hits stand for (the core's `record`),    /// once each, in Find's order.    static func threads(_ hits: [FindHit]) -> [String] {        var seen = Set<String>()        return hits.compactMap { hit -> String? in            guard let card = hit.card, card.table == "email_thread", seen.insert(card.id).inserted else { return nil }            return card.id        }    }    func get(table: String, id: String) async throws -> TableRecord? {        try await core.call(CottonMethod.recordsGet, GetArguments(table: table, id: id), as: EngineRecord.self).record    }    func create(table: String, data: [String: RecordValue]) async throws -> ChangeRecord { throw ActionRefused("Email is imported; Cotton cannot send mail.") }    func update(table: String, id: String, patch: [String: RecordValue]) async throws -> ChangeRecord {        let before = try await get(table: table, id: id)        if table == "email_thread", patch.keys.allSatisfy({ $0 == "summary" }), let value = patch["summary"] {            let words = value.text?.trimmingCharacters(in: .whitespacesAndNewlines)            try await write("update_summary", ["kind": .string(table), "id": .string(id), "summary": words?.isEmpty == false ? .string(words!) : .null])        } else { throw ActionRefused("Use the email conversation’s mailbox actions to change its state.") }        return ChangeRecord(id: UUID().uuidString, byline: "You", before: before, after: try await get(table: table, id: id))    }    func delete(table: String, id: String) async throws -> ChangeRecord { throw ActionRefused("Use Bin on the conversation; empty the bin to erase it.") }    func reorder(table: String, ids: [String]) async throws -> ChangeRecord { throw ActionRefused("Email is ordered by time.") }    func link(table: String, id: String, column: String, target: String) async throws -> ChangeRecord { throw ActionRefused("The email envelope is kept by the archive.") }    /// A mailbox act this session took: the conversation, the state it set    /// and what the state was, so the receipt's Undo sets it back.    private struct Taken { let thread: String; let key: String; let was: Bool }    private var taken: [String: Taken] = [:]    func undo(change: String) async throws -> ChangeRecord {        // A group's change (made, renamed, deleted) is the core's to take back.        guard let act = taken.removeValue(forKey: change) else { return try await core.undoGroupChange(change) }        let before = try await get(table: "email_thread", id: act.thread)        try await write("update_email", ["threadId": .string(act.thread), act.key: .bool(act.was)])        return ChangeRecord(id: UUID().uuidString, byline: "You", before: before, after: try await get(table: "email_thread", id: act.thread), undoable: false)    }    /// What a mailbox act says once done, naming the conversation (R4).    static func said(bin value: Bool, subject: String?) -> String {        let trimmed = subject?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""        let name = trimmed.isEmpty ? "this conversation" : trimmed        return value ? "Moved \(name) to the bin" : "Restored \(name)"    }    func listActions(table: String) async -> [RecordAction] { [] }    /// The Junk view (the ring's Junk slip) offers Empty Junk now while Junk    /// holds anything.    func listActions(table: String, where filter: [String: RecordValue]) async -> [RecordAction] {        guard table == "email_thread", filter == Self.junk,              let held = try? await readPage(table: table, project: nil, query: nil, offset: 0, filter: filter).records, !held.isEmpty        else { return [] }        return [RecordAction(id: "empty_junk", label: ShellLines.line("email", "junk.empty_now"), confirmation: Self.emptyJunkQuestion)]    }    /// Junk's read, as email_thread.json's Junk view names it.    static let junk: [String: RecordValue] = ["sender_kind": .text("junk")]    static var emptyJunkQuestion: WriteConfirmation { WriteConfirmation(        title: ShellLines.line("email", "junk.question"),        message: ShellLines.line("email", "junk.question_body"),        confirmLabel: ShellLines.line("email", "junk.confirm")) }    func pageActions(table: String, record: TableRecord) async -> [RecordAction] {        // A sender's Junk, Keep and Add to People are the definition's        // commands, drawn by the page and the row's long press.        guard table == "email_thread" else { return [] }        // An imported thread is not binned from its page, and its sender is        // blocked from the sender's own page (architect, r7): its acts are the        // definition's — Star, Archive, Junk, Record, Add to calendar. One        // already in the bin (an earlier Empty Junk) is brought back here.        guard record["binned"].bool == true else { return [] }        return [RecordAction(id: "bin", label: ShellLines.line("email", "restore"))]    }    func perform(_ action: RecordAction, table: String, record: TableRecord?) async throws -> ActionOutcome {        if action.id == "empty_junk" {            try await write("empty_junk", [:])            return .said("Junk emptied into the bin")        }        guard let record else { throw ActionRefused("Open a conversation or sender first.") }        guard table == "email_thread" else { throw ActionRefused("That action is not available here.") }        let value: Bool        switch action.id {        case "bin": value = record["binned"].bool != true        default: throw ActionRefused("That action is not available here.")        }        let key = action.id        let was = record["binned"].bool == true        try await write("update_email", ["threadId": .string(record.id), key: .bool(value)])        // A receipt that names the conversation, with the Undo that sets        // the state back (R4) — never the act's own label again.        let change = ChangeRecord(            id: UUID().uuidString, byline: "You", before: record, after: try await get(table: table, id: record.id),            said: ChangeSaid(kind: "command", said: Self.said(bin: value, subject: record["subject"].text)))        taken[change.id] = Taken(thread: record.id, key: key, was: was)        return .change(change)    }    private func write(_ tool: String, _ args: [String: JSONValue]) async throws {        _ = try await core.call(CottonMethod.write, WriteRequest(tool: tool, args: .object(args)), as: WriteAnswer.self)    }    static func record(_ value: JSONValue) throws -> TableRecord {        try JSONDecoder().decode(EngineRecord.self, from: JSONEncoder().encode(value)).record    }}/// Email keeps groups like any core table: each a view on the ring after/// Email's fixed views.extension EmailRecords: GroupingRecords {    func groups(of table: String, holding record: String?) async throws -> [GroupStack] {        try await core.listGroups(of: table, holding: record)    }    func createGroup(named name: String, of table: String, records: [String]) async throws -> (change: ChangeRecord, group: RecordGroup?) {        try await core.makeGroup(named: name, of: table, records: records)    }    func updateGroup(_ id: String, _ change: GroupChange) async throws -> ChangeRecord {        try await core.changeGroup(id, change)    }    func deleteGroup(_ id: String) async throws -> ChangeRecord {        try await core.binGroup(id)    }}extension EmailRecords: RecordCommands {    /// A definition's command on a conversation — Star, Archive, Mark read and    /// their opposites — run by the core, which answers its receipt and Undo.    func command(table: String, id: String, command: RecordCommand, picked: String?) async throws -> ChangeRecord {        let outcome: CommandOutcome        do {            outcome = try await core.call(                "records.command", ["table": RecordValue.text(table), "id": .text(id), "command": .text(command.id),                                     "picked": picked.map(RecordValue.text) ?? .null],                as: CommandOutcome.self)        } catch let refusal as CottonCallError {            throw ActionRefused(refusal.message)        }        return try outcome.change(table: table, record: id)    }}