Cotton code
104 lines · 6.9 KB · SwiftRaw
// COTTON DEV ONLY: Post's walk helpers, read from the launch's arguments or environment.// - `-post-invent-many N` (COTTON_POST_INVENT_MANY): N invented mails generated in one batch (thousands to sync).// - `-post-invent` (COTTON_POST_INVENT=1): invented mail written into this phone's copy by `developer.inventMail`, as//   the Mac's reader lands it: invented people writing about invented things, machines of each group, attachments.//   Every name, address and word is made up (`*.invented.test`); the real Cotton refuses the call by name.// - `-post-open <place>` (COTTON_POST_OPEN): a tab (`mail`, `senders`, `files`, `you`), `side`, `search`, `write`,//   `look`, or `list:<place>`.// - `-post-ring` (COTTON_POST_RING=1): once Post goes to the background, the newest Inbox conversation is rung as a//   fetch round's `notify` would be (Post/PostRings.swift), so the notification and its tap can be walked without a//   mail server.#if os(iOS) && COTTON_DEVimport CottonKitimport Foundationimport UIKitenum PostDevOpen {    @MainActor    static func run(_ model: PostModel) async {        let arguments = ProcessInfo.processInfo.arguments        let env = ProcessInfo.processInfo.environment        func value(_ flag: String, _ key: String) -> String? {            if let at = arguments.firstIndex(of: flag), at + 1 < arguments.count { return arguments[at + 1] }            return env[key]        }        if arguments.contains("-post-invent") || env["COTTON_POST_INVENT"] == "1" {            _ = await model.read("developer.inventMail", invented, as: JSONValue.self)            model.changed()        }        // `-post-invent-many N`: N invented mails more (`generate`), as one batch to send, so another app of the same        // account on this phone has thousands of rows to catch up on (the sync seen walk, 26 Nov 2026).        if let many = value("-post-invent-many", "COTTON_POST_INVENT_MANY").flatMap(Int.init), many > 0 {            var asked = invented            asked["mail"] = .array([])            asked["generate"] = .object(["emails": .number(Double(many)), "threads": .number(Double(max(1, many / 2)))])            _ = await model.read("developer.inventMail", asked, as: JSONValue.self)            model.changed()        }        if arguments.contains("-post-ring") || env["COTTON_POST_RING"] == "1" {            await PostRings.askOnce()            if case .read(let list) = await model.read("mail.list", ["place": .string("inbox")], as: PostList.self),               let row = list.rows.first(where: { $0.thread != nil }) {                let ring = PostRing(id: row.email ?? row.thread ?? "", thread: row.thread, title: row.from.name, body: row.subject)                Task { @MainActor in                    for await _ in NotificationCenter.default.notifications(named: UIApplication.didEnterBackgroundNotification) {                        // Within the moment iOS grants on leaving, as a real round runs within its background time.                        let held = UIApplication.shared.beginBackgroundTask()                        await PostRings.ring([ring])                        UIApplication.shared.endBackgroundTask(held)                        break                    }                }            }        }        guard let open = value("-post-open", "COTTON_POST_OPEN") else { return }        switch open {        case "mail", "senders", "files", "you": model.tab = PostTab(rawValue: open) ?? .mail        case "side": model.sideOpen = true        case "search": model.sheet = .search        case "write": model.sheet = .write(mode: "new", thread: nil, email: nil, draft: nil)        case "look": model.tab = .you; model.paths[.you] = [.look]        case "accounts": model.tab = .you; model.paths[.you] = [.accounts]        case "add-gmail": model.tab = .you; model.paths[.you] = [.accounts, .accountAdd("gmail")]        case "domains": model.tab = .you; model.paths[.you] = [.domains]        default:            if open.hasPrefix("list:") { model.paths[.mail] = [.list(String(open.dropFirst(5)))] }        }    }    /// An invented mailbox: four people, a few of their conversations (one with two attachments), and machine mail    /// spread over invented senders, enough for every band and group.    private static var invented: [String: JSONValue] {        let now = Date()        func at(_ minutesAgo: Double) -> JSONValue { .string(ISO8601DateFormatter().string(from: now.addingTimeInterval(-minutesAgo * 60))) }        func person(_ name: String, _ email: String) -> JSONValue { .object(["name": .string(name), "email": .string(email)]) }        func mail(_ id: String, _ thread: String, _ subject: String, _ fromName: String, _ fromAddress: String, _ ago: Double, _ body: String,                  unread: Bool = false, files: [(String, String)] = []) -> JSONValue {            .object([                "id": .string(id), "thread": .string(thread), "subject": .string(subject),                "from": .object(["name": .string(fromName), "address": .string(fromAddress)]),                "at": at(ago), "body": .string(body), "unread": .bool(unread),                "attachments": .array(files.map { .object(["name": .string($0.0), "text": .string($0.1)]) }),            ])        }        let priya = "priya@people.invented.test", arjun = "arjun@people.invented.test", sara = "sara@people.invented.test", rohan = "rohan@people.invented.test"        return [            "me": .object(["address": "me@post.invented.test"]),            "people": .array([person("Priya Nair", priya), person("Arjun Mehta", arjun), person("Sara Lindqvist", sara), person("Rohan Iyer", rohan)]),            "mail": .array([                mail("post-dev-1", "post-flat", "Flat papers", "Priya Nair", priya, 40,                     "Here's the lease draft. Clause 7 is the one about the deposit; they've put two months, not three.\n\nCan you read it tonight? I'll call them tomorrow morning.\n\nThe floor plan is at https://plans.invented.test/flat-4b if you want to look first.",                     unread: true, files: [("lease-draft.pdf", "An invented lease draft"), ("floor-plan.pdf", "An invented floor plan")]),                mail("post-dev-2", "post-build", "Build 1.0.3 is in review", "Arjun Mehta", arjun, 95,                     "Build 1.0.3 went in this morning. Screenshots are in the shared folder.", unread: true),                mail("post-dev-3", "post-kickoff", "Kickoff on 2 Dec", "Sara Lindqvist", sara, 60 * 26,                     "Works for us. Thursday at ten, and I'll bring the drawings."),                mail("post-dev-4", "post-goa", "Goa in January?", "Rohan Iyer", rohan, 60 * 24 * 4,                     "We're thinking the second week of January. Are you in? Tell me by Friday?"),            ]),            "generate": .object(["emails": .number(160), "threads": .number(60), "step": .number(47), "end": at(5), "senders": .number(9), "domains": .number(5)]),        ]    }}#endif