Cotton code
543 lines · 25.8 KB · SwiftRaw
// ACCOUNTS AND HOW MAIL ARRIVES (mail CONTRACT rows 11 and 12; DECISIONS "How mail arrives"): his mail accounts, each// with how its mail reaches him in words; adding one shows the three ways' honest words before he picks (This phone// first); an account's page says where its password is kept, what Cotton's fetcher logged, and offers Remove password,// name, signature, tag and Remove. With This phone fetches the password stays in this phone's own key store, never// in the core, and a round of `mail.fetch` runs each time Post comes to the front.// `mail.accounts`, `mail.account.plan`, `mail.account.add`, `mail.account`, `mail.account.way`, `mail.account.set`,// `mail.account.forget`, `mail.account.remove`, `mail.fetch`.#if os(iOS)import CottonKitimport Securityimport SwiftUI// ── the shapes ─────────────────────────────────────────────────────────struct PostAccountStatus: Decodable, Equatable, Sendable { var line: String; var state: String? }struct PostAccounts: Decodable, Equatable, Sendable {    struct Row: Decodable, Equatable, Sendable, Identifiable { var id: String; var address: String; var tag: String?; var kind: String?; var way: String?; var status: PostAccountStatus? }    struct Kind: Decodable, Equatable, Sendable, Identifiable { var kind: String; var label: String; var id: String { kind } }    var title: String    var rows: [Row]    var add: String    var kinds: [Kind]    var empty: String?}/// A way mail arrives, in the words he reads before he chooses it.struct PostWay: Decodable, Equatable, Sendable, Identifiable {    var id: String    var title: String    var line: String    var more: String?    var could: String?    var kept: String?    var logged: String?    var chosen: Bool = false}/// `mail.account.plan { kind }`: what adding this kind of account asks.struct PostAccountPlan: Decodable, Equatable, Sendable {    struct Field: Decodable, Equatable, Sendable, Identifiable { var id: String; var label: String; var hint: String?; var secret: Bool?; }    var kind: String    var provider: String    var title: String    var line: String?    var fields: [Field]    var how: String?    var steps: [String]    var note: String?    var ways: [PostWay]    var chosen: String}/// `mail.account { id }`: How mail arrives for one account.struct PostAccount: Decodable, Equatable, Sendable {    struct Password: Decodable, Equatable, Sendable { var kept: String?; var logged: String?; var forget: String? }    struct LogRow: Decodable, Equatable, Sendable, Identifiable { var at: String?; var when: String?; var line: String; var failed: Bool?; var why: String?; var id: String { "\(at ?? "")\(line)" } }    struct Log: Decodable, Equatable, Sendable { var title: String; var rows: [LogRow] }    struct Setting: Decodable, Equatable, Sendable { var label: String; var value: String? }    struct Remove: Decodable, Equatable, Sendable { var label: String; var line: String?; var count: Int? }    var id: String    var address: String    var kind: String?    var provider: String?    var title: String    var way: String    var ways: [PostWay]    var status: PostAccountStatus?    var password: Password?    var log: Log?    var name: Setting?    var signature: Setting?    var tag: Setting?    var remove: Remove?}/// `mail.account.forget`: the password is gone; where to revoke it at the provider; and the choice again.struct PostForgot: Decodable, Equatable, Sendable {    struct Page: Decodable, Equatable, Sendable { var label: String; var url: String? }    struct Next: Decodable, Equatable, Sendable { var title: String; var account: PostAccount }    var line: String    var provider_page: Page?    var next: Next}/// `mail.account.remove`: the question with its count, or done.struct PostRemoved: Decodable, Equatable, Sendable {    struct Ask: Decodable, Equatable, Sendable { var title: String; var line: String; var go: String; var cancel: String; var count: Int? }    var ask: Ask?    var line: String?}/// `mail.fetch`: one round of This phone fetches.struct PostFetched: Decodable, Equatable, Sendable {    var account: String; var fetched: Int?; var state: String?; var line: String?    /// The new mail this round rings for (Notifications: people, everyone or none).    var notify: [PostRing]?}// ── This phone's key store ─────────────────────────────────────────────/// The app passwords This phone fetches reads with, one per account, kept in this phone's key store only (never/// synced, readable after the first unlock so a background round can read it).enum PostMailKey {    private static let service = "cotton.post.fetch"    static func keep(_ password: String, for account: String) {        forget(account)        let item: [String: Any] = [            kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account,            kSecValueData as String: Data(password.utf8), kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,        ]        SecItemAdd(item as CFDictionary, nil)    }    static func read(_ account: String) -> String? {        let query: [String: Any] = [            kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account,            kSecReturnData as String: true, kSecMatchLimit as String: kSecMatchLimitOne,        ]        var found: CFTypeRef?        guard SecItemCopyMatching(query as CFDictionary, &found) == errSecSuccess, let data = found as? Data else { return nil }        return String(data: data, encoding: .utf8)    }    static func forget(_ account: String) {        let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account]        SecItemDelete(query as CFDictionary)    }}/// THIS PHONE FETCHES, one round for each account this phone holds a password for: on open, on coming to the front,/// and in the time iOS gives the app in the background (`BackgroundCatchUp.also`). Answers whether any mail came.enum PostFetch {    @MainActor static func round(_ core: any CottonCalling) async -> Bool {        guard let accounts = try? await core.call("mail.accounts", JSONValue.object([:]), as: PostAccounts.self) else { return false }        var any = false        for row in accounts.rows where row.way == "phone" {            guard let password = PostMailKey.read(row.id) else { continue }            let request = JSONValue.object(["account": .string(row.id), "password": .string(password)])            do {                let round = try await core.call("mail.fetch", request, as: PostFetched.self)                if (round.fetched ?? 0) > 0 { any = true }                await PostRings.ring(round.notify ?? [])            } catch {                Log.write("post: a fetch round for an account did not run — \(error)")            }        }        return any    }}/// Post's round joins the background catch-up, in Post only.public enum PostBackground {    @MainActor public static func attach() {        guard PostRoot.applies else { return }        BackgroundCatchUp.shared.also { core in _ = await PostFetch.round(core) }    }}extension PostModel {    /// One round, while Post is open. A round already running is left to finish.    func fetchHere() async {        guard !fetching else { return }        fetching = true        defer { fetching = false }        if await PostFetch.round(core) { changed() }    }}// ── the screens ────────────────────────────────────────────────────────/// ACCOUNTS: each account with how its mail arrives in words; Add an account asks which kind.struct PostAccountsScreen: View {    let model: PostModel    @State private var read: PostRead<PostAccounts>?    @State private var choosing = false    var body: some View {        VStack(spacing: 0) {            PostBar(back: PostWords.line("you.title"), onBack: { model.pop() }).padding(.horizontal, PostInk.side)            ScrollView {                VStack(alignment: .leading, spacing: 0) {                    PostTitle(text: read?.answer?.title ?? PostWords.line("account.title"))                    switch read {                    case .read(let answer)?:                        if let empty = answer.empty { PostNote(text: empty) }                        ForEach(Array(answer.rows.enumerated()), id: \.element.id) { index, row in                            PostLinkRow(title: row.address, line: [row.tag, row.status?.line].compactMap { $0 }.joined(separator: " · "),                                        last: index == answer.rows.count - 1, id: "post-account-\(row.id)") { model.push(.account(row.id)) }                        }                        PostButton(label: answer.add, weight: .go, id: "post-account-add") { choosing = true }.padding(.top, 18)                    case .refused(let line)?: PostRefused(line: line)                    case nil: EmptyView()                    }                }                .padding(.horizontal, PostInk.side)                .padding(.bottom, 24)            }        }        .background(PostInk.ground)        .task(id: model.generation) { read = await model.read("mail.accounts", as: PostAccounts.self) }        .confirmationDialog(read?.answer?.add ?? "", isPresented: $choosing, titleVisibility: .visible) {            ForEach(read?.answer?.kinds ?? []) { kind in                Button(kind.label.prefix(1).uppercased() + kind.label.dropFirst()) { model.push(.accountAdd(kind.kind)) }            }        }        .accessibilityIdentifier("post-accounts")    }}/// The ways, each a card with its honest words; the chosen one is marked.struct PostWayCards: View {    let ways: [PostWay]    let chosen: String    let choose: (String) -> Void    var body: some View {        VStack(spacing: 10) {            ForEach(ways) { way in                Button { choose(way.id) } label: {                    VStack(alignment: .leading, spacing: 5) {                        HStack {                            Text(way.title).font(PostType.sans(16.5, .bold)).foregroundStyle(PostInk.ink)                            Spacer()                            Image(systemName: way.id == chosen ? "checkmark.circle.fill" : "circle")                                .font(.system(size: 20, weight: .light))                                .foregroundStyle(way.id == chosen ? PostInk.accent : PostInk.faint)                        }                        Text(way.line).font(PostType.small).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true)                        ForEach([way.more, way.could, way.kept, way.logged].compactMap { $0 }, id: \.self) { line in                            Text(line).font(PostType.small).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true)                        }                    }                    .multilineTextAlignment(.leading)                    .padding(14)                    .frame(maxWidth: .infinity, alignment: .leading)                    .background(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(way.id == chosen ? PostInk.accent : PostInk.rule, lineWidth: way.id == chosen ? 1.5 : 1))                    .contentShape(Rectangle())                }                .buttonStyle(PostPressStyle())                .accessibilityAddTraits(way.id == chosen ? .isSelected : [])                .accessibilityIdentifier("post-way-\(way.id)")            }        }    }}/// ADD AN ACCOUNT: the fields the kind needs, how to make an app password, and the three ways before he picks.struct PostAccountAddScreen: View {    let model: PostModel    let kind: String    @State private var plan: PostRead<PostAccountPlan>?    @State private var values: [String: String] = [:]    @State private var way = "phone"    @State private var said: String?    @State private var adding = false    var body: some View {        VStack(spacing: 0) {            PostBar(back: PostWords.line("account.title"), onBack: { model.pop() }).padding(.horizontal, PostInk.side)            ScrollView {                VStack(alignment: .leading, spacing: 0) {                    switch plan {                    case .read(let p)?: content(p)                    case .refused(let line)?: PostRefused(line: line)                    case nil: EmptyView()                    }                }                .padding(.horizontal, PostInk.side)                .padding(.bottom, 24)            }            .scrollDismissesKeyboard(.interactively)        }        .background(PostInk.ground)        .task {            let read = await model.read("mail.account.plan", ["kind": .string(kind), "platform": .string("ios")], as: PostAccountPlan.self)            plan = read            if let chosen = read.answer?.chosen { way = chosen }        }        .accessibilityIdentifier("post-account-add")    }    @ViewBuilder private func content(_ p: PostAccountPlan) -> some View {        PostTitle(text: p.title)        if let line = p.line { PostLead(text: line) }        ForEach(p.fields) { field in            VStack(alignment: .leading, spacing: 4) {                Group {                    if field.secret == true {                        SecureField(field.label, text: binding(field.id))                    } else {                        TextField(field.label, text: binding(field.id))                            .keyboardType(field.id == "address" ? .emailAddress : .URL)                    }                }                .font(PostType.sans(16))                .foregroundStyle(PostInk.ink)                .textInputAutocapitalization(.never)                .autocorrectionDisabled()                .textContentType(field.secret == true ? .password : field.id == "address" ? .emailAddress : nil)                .frame(minHeight: 46)                .accessibilityIdentifier("post-account-field-\(field.id)")                PostRule()                if let hint = field.hint { Text(hint).font(PostType.small).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true) }            }            .padding(.top, 10)        }        if let how = p.how, !p.steps.isEmpty {            PostSection(title: how)            ForEach(Array(p.steps.enumerated()), id: \.offset) { index, step in                HStack(alignment: .firstTextBaseline, spacing: 10) {                    Text("\(index + 1)").font(PostType.sans(14, .bold)).foregroundStyle(PostInk.quiet)                    Text(step).font(PostType.sans(15)).foregroundStyle(PostInk.ink).fixedSize(horizontal: false, vertical: true)                }                .padding(.vertical, 4)            }        }        if let note = p.note { PostNote(text: note) }        PostWayCards(ways: p.ways, chosen: way) { way = $0 }.padding(.top, 18)        if let said { PostNote(text: said) }        PostButton(label: PostWords.line("account.add"), weight: .go, id: "post-account-add-go") { Task { await add(p) } }            .disabled(adding)            .padding(.top, 18)    }    private func binding(_ id: String) -> Binding<String> {        Binding(get: { values[id] ?? "" }, set: { values[id] = $0 })    }    /// Added: with This phone fetches the password goes into this phone's key store and the first round runs; with    /// Cotton fetches the core hands it to the object; with This Mac fetches the Mac asks for it.    private func add(_ p: PostAccountPlan) async {        said = nil        adding = true        defer { adding = false }        var request: [String: JSONValue] = ["kind": .string(kind), "way": .string(way)]        for (key, value) in values where !value.trimmingCharacters(in: .whitespaces).isEmpty {            if key == "password" && way != "cotton" { continue }            request[key] = .string(value)        }        switch await model.read("mail.account.add", request, as: PostAccount.self) {        case .read(let account):            if way == "phone", let password = values["password"], !password.isEmpty { PostMailKey.keep(password, for: account.id) }            values["password"] = nil            model.changed()            model.pop()            model.push(.account(account.id))            Task {                // New mail by this phone starts now: the one moment Post asks whether it may notify.                if way == "phone" { await PostRings.askOnce() }                await model.fetchHere()            }        case .refused(let line): said = line        }    }}/// HOW MAIL ARRIVES, for one account: its state in words, the ways, where the password is kept, Cotton's log, the/// settings, and Remove.struct PostAccountScreen: View {    let model: PostModel    let id: String    @State private var read: PostRead<PostAccount>?    @State private var said: String?    @State private var forgot: PostForgot?    @State private var askingPassword: String?    @State private var password = ""    @State private var editing: String?    @State private var value = ""    @State private var removing: PostRemoved.Ask?    @State private var forgetting = false    var body: some View {        VStack(spacing: 0) {            PostBar(back: PostWords.line("account.title"), onBack: { model.pop() }).padding(.horizontal, PostInk.side)            ScrollView {                VStack(alignment: .leading, spacing: 0) {                    switch read {                    case .read(let account)?: content(account)                    case .refused(let line)?: PostRefused(line: line)                    case nil: EmptyView()                    }                }                .padding(.horizontal, PostInk.side)                .padding(.bottom, 24)            }        }        .background(PostInk.ground)        .task(id: model.generation) { read = await model.read("mail.account", ["id": .string(id), "platform": .string("ios")], as: PostAccount.self) }        .alert(read?.answer?.provider.map { PostWords.line("account.password") + " · " + $0 } ?? PostWords.line("account.password"),               isPresented: Binding(get: { askingPassword != nil }, set: { if !$0 { askingPassword = nil } })) {            SecureField(PostWords.line("account.password"), text: $password)            Button(PostWords.line("write.cancel"), role: .cancel) { password = "" }            Button(PostWords.line("edit.save")) {                if let way = askingPassword { Task { await choose(way, password: password) } }            }        }        .alert(editingLabel, isPresented: Binding(get: { editing != nil }, set: { if !$0 { editing = nil } })) {            TextField(editingLabel, text: $value)            Button(PostWords.line("write.cancel"), role: .cancel) {}            Button(PostWords.line("edit.save")) { if let key = editing { Task { await set(key, value) } } }        }        .alert(removing?.title ?? "", isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } }), presenting: removing) { ask in            Button(ask.cancel, role: .cancel) {}            Button(ask.go, role: .destructive) { Task { await removeAccount(count: ask.count) } }        } message: { ask in Text(ask.line) }        .alert(PostWords.line("way.forget.title"), isPresented: $forgetting) {            Button(PostWords.line("way.forget.keep"), role: .cancel) {}            Button(PostWords.line("way.forget.go"), role: .destructive) { Task { await forgetPassword() } }        } message: { Text(PostWords.line("way.forget.line", ["provider": read?.answer?.provider ?? ""])) }        .accessibilityIdentifier("post-account")    }    private var editingLabel: String {        guard let a = read?.answer else { return "" }        switch editing {        case "name": return a.name?.label ?? ""        case "signature": return a.signature?.label ?? ""        case "tag": return a.tag?.label ?? ""        default: return ""        }    }    @ViewBuilder private func content(_ a: PostAccount) -> some View {        PostTitle(text: a.title)        Text(a.address).font(PostType.sans(16, .semibold)).foregroundStyle(PostInk.ink).padding(.top, 2)        if let status = a.status {            Text(status.line).font(PostType.small).foregroundStyle(status.state == "live" ? PostInk.quiet : PostInk.ink)                .fixedSize(horizontal: false, vertical: true).padding(.top, 4)                .accessibilityIdentifier("post-account-status")        }        if let forgot {            PostNote(text: forgot.line)            if let page = forgot.provider_page {                if let url = page.url.flatMap(URL.init(string:)) {                    PostLinkRow(title: page.label, last: true, id: "post-account-provider") { model.sheet = .reader(url, back: PostWords.line("account.title")) }                } else {                    PostNote(text: page.label)                }            }            PostSection(title: forgot.next.title)        }        PostWayCards(ways: a.ways, chosen: a.way) { way in            guard way != a.way else { return }            if way == "cotton" || way == "phone" { password = ""; askingPassword = way } else { Task { await choose(way, password: nil) } }        }        .padding(.top, 14)        if let said { PostNote(text: said) }        if let kept = a.password, forgot == nil {            VStack(alignment: .leading, spacing: 4) {                // The chosen way's card already says these; only what it doesn't is said again.                let said = Set(a.ways.filter { $0.id == a.way }.flatMap { [$0.line, $0.more, $0.could, $0.kept, $0.logged].compactMap { $0 } })                ForEach([kept.kept, kept.logged].compactMap { $0 }.filter { !said.contains($0) }, id: \.self) { line in                    Text(line).font(PostType.small).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true)                }            }            .padding(.top, 14)            if let forget = kept.forget {                PostButton(label: forget, weight: .outline, id: "post-account-forget") { forgetting = true }.padding(.top, 10)            }        }        if let log = a.log, !log.rows.isEmpty {            PostSection(title: log.title)            ForEach(Array(log.rows.enumerated()), id: \.element.id) { index, row in                VStack(alignment: .leading, spacing: 2) {                    Text(row.line).font(PostType.sans(15)).foregroundStyle(row.failed == true ? PostInk.ink : PostInk.quiet).fixedSize(horizontal: false, vertical: true)                    if let why = row.why { Text(why).font(PostType.small).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true) }                    if let when = row.when { Text(when).font(PostType.small).foregroundStyle(PostInk.faint) }                }                .padding(.vertical, 8)                .frame(maxWidth: .infinity, alignment: .leading)                .overlay(alignment: .bottom) { if index < log.rows.count - 1 { PostRule() } }                .accessibilityElement(children: .combine)            }        }        VStack(alignment: .leading, spacing: 0) {            ForEach([("name", a.name), ("tag", a.tag), ("signature", a.signature)], id: \.0) { key, setting in                if let setting {                    PostLinkRow(title: setting.label, line: setting.value?.isEmpty == false ? setting.value : nil, chevron: false, id: "post-account-\(key)") {                        value = setting.value ?? ""                        editing = key                    }                }            }        }        .padding(.top, 18)        if let remove = a.remove {            PostButton(label: remove.label, line: remove.line, weight: .quiet, id: "post-account-remove") { Task { await removeAccount(count: nil) } }                .padding(.top, 22)        }    }    private func choose(_ way: String, password typed: String?) async {        said = nil        var request: [String: JSONValue] = ["id": .string(id), "way": .string(way)]        if way == "cotton", let typed, !typed.isEmpty { request["password"] = .string(typed) }        switch await model.read("mail.account.way", request, as: PostAccount.self) {        case .read(let account):            if way == "phone", let typed, !typed.isEmpty { PostMailKey.keep(typed, for: id) } else { PostMailKey.forget(id) }            read = .read(account)            forgot = nil            model.changed()            if way == "phone" { Task { await model.fetchHere() } }        case .refused(let line): said = line        }        password = ""        askingPassword = nil    }    private func set(_ key: String, _ value: String) async {        switch await model.read("mail.account.set", ["id": .string(id), key: .string(value)], as: PostAccount.self) {        case .read(let account): read = .read(account); model.changed()        case .refused(let line): said = line        }    }    private func forgetPassword() async {        switch await model.read("mail.account.forget", ["id": .string(id)], as: PostForgot.self) {        case .read(let done): forgot = done; read = .read(done.next.account)        case .refused(let line): said = line        }    }    /// Remove asks once with the mails here counted; agreed, it runs with that count.    private func removeAccount(count: Int?) async {        var request: [String: JSONValue] = ["id": .string(id)]        if let count { request["count"] = .number(Double(count)) }        switch await model.read("mail.account.remove", request, as: PostRemoved.self) {        case .read(let done):            if let ask = done.ask {                removing = ask            } else {                PostMailKey.forget(id)                model.changed()                model.pop()            }        case .refused(let line): said = line        }    }}#endif