Cotton code
279 lines · 12.7 KB · SwiftRaw
// The contract for the share extension — sub-step 4i's half of `Boundary.swift`.//// A SEPARATE FILE for the reason `Boundary+4d.swift` and `Boundary+4j.swift`// both give in their headers: several lanes are landing at once, and a lane that// appends to the middle of somebody else's file makes a merge conflict out of// what is really two independent additions. The rule stated in `Boundary.swift`// still binds every shape below — **where this file and// `crates/cotton-ffi/src/phone/{page,media}.rs` disagree, the// crate wins** — and `ShareMailboxTests` reads the method table by path so the// two cannot drift quietly.//// The names 4i asks for — a write the tool surface refuses in so many words,// 4p's `capture.media`, which the share drain is the second caller of, and the// read that says where a media key's bytes are://// | Method | Answers | Called by |// |---|---|---|// | `page.save` | `{id}` for one URL, `{ids:[…]}` for prose carrying several | the drain's fifth branch |// | `capture.media` | `{key, recordId}` | the drain's second branch, for a picture or a clip |// | `read.mediaPath` | `{path}` when the bytes are on this phone | every face drawing a media key |//// **Neither write is a `write {tool:…}` call and neither could be.** The tool surface// refuses `create_page` in as many words — "pages are saved from the share sheet// — a URL from the owner's phone, not an assistant write" — and `capture.media`// takes a PATH because bytes never cross this boundary: a base64 `bytes`// argument would put a 500 MB clip through a JSON string twice, which is the// jetsam kill build 106 already paid for. Both refusals are written down in the// crate rather than left as gaps, and both are quoted where this app would// otherwise have been tempted.//// Decoding is generous exactly as the three files before it are: every field is// optional or defaulted, and nothing throws on a shape it does not recognise.import Foundationextension CottonMethod {    /// `read.mediaPath` — the path if the bytes are already on this phone, and    /// NEVER a fetch (`phone/media.rs`).    ///    /// Declared HERE rather than beside a face that asks it: a read named    /// only beside its screen is invisible to `BoundaryContractTests`, so a    /// crate-side rename reaches the app as an `unknown_method` at runtime    /// instead of as a red test.    public static let readMediaPath = "read.mediaPath"    /// `page.save` — a URL from the share sheet becomes a row in the reading    /// pile (`phone/page.rs`).    ///    /// **It takes `url` OR shared `text`, never both**, and it refuses the pair    /// by name. Prose is handed over WHOLE and the crate extracts every URL    /// from it itself (`validate_pages`, `phone/page.rs:83-105`), writing one    /// row per URL — which is why this app carries no second URL regex and must    /// not grow one. `excerpt` is refused by name too: a saved page is a    /// pointer, and accepting the argument would tell the share sheet a summary    /// had been kept.    ///    /// **A second save of the same URL writes a SECOND row, deliberately.**    /// That is the TypeScript's behaviour (`createPage` mints a fresh id every    /// time), and inventing a uniqueness rule in a port would be exactly the    /// new behaviour this lane may not add.    public static let pageSave = "page.save"    /// `capture.media` — the bytes, then the row, then the upload ledger    /// (`phone/media.rs`).    ///    /// It TAKES A PATH and refuses a `bytes` argument by name. The order below    /// the boundary is the whole of it: every refusal happens before a byte    /// moves, then the file is copied into the content-addressed store, then the    /// record row is written carrying the object key, then the `_media` ledger    /// row queues the upload for the sync loop to drain. **No screen waits on    /// that upload** — which is why this branch of the drain can navigate the    /// moment the method answers.    ///    /// It captures `photo`, `video` and `document` and refuses the other six    /// kinds with a written reason: each of those belongs to a row something    /// else writes first, and this method mints its own.    ///    /// **A photo or a film brings its TIERS with it**, made by `MediaTiers` on    /// this side before the call — `thumbPath`, `displayPath`, `posterPath` and    /// the one string, `preview`. Paths, because the boundary's rule does not    /// bend for a thumbnail; the blur is a string because it is a column. The    /// crate writes `preview` and a film's `poster_key` onto the row and    /// enqueues one `_media` row per object, so the drain uploads every tier    /// exactly the way it uploads the original. **The capture never waits on    /// any of it** — the tiers are made from a local file and nothing here    /// touches the radio.    public static let captureMedia = "capture.media"    /// A Camera tool shot: `capture.media`'s request, written the moment it    /// is taken, held to a photo or a video.    public static let cameraShot = "camera.shot"}// MARK: - `page.save`/// What the drain sends for a URL, or for the prose that may carry several.////// A synthesised `Encodable` omits a nil optional, so an unset field is an/// ABSENT field — which matters here more than usual: sending both is a written/// refusal, not a preference, so the two initialisers below are the only two/// ways to spell this request.public struct PageSaveRequest: Encodable, Sendable, Equatable {    public var url: String?    public var text: String?    /// What the sharing app called the link — Safari says the page's title —    /// kept as the page's title until the page itself says better.    public var title: String?    /// One link, already a URL, with the title the sharing app gave it.    public static func url(_ url: String, title: String? = nil) -> PageSaveRequest {        PageSaveRequest(url: url, text: nil, title: title)    }    /// Prose. The crate extracts every URL in it and writes one row for each.    public static func text(_ text: String) -> PageSaveRequest {        PageSaveRequest(url: nil, text: text, title: nil)    }    private init(url: String?, text: String?, title: String?) {        self.url = url        self.text = text        self.title = title    }}/// `page.save`'s answer, in both of its shapes.////// One URL answers `{id}`; prose carrying several answers `{ids:[…]}`/// (`write_pages`, `phone/page.rs:108-117`). Read as ONE list either way, so no/// caller has to know which shape it asked for.public struct PagesSaved: Decodable, Equatable, Sendable {    public var ids: [String]    public init(ids: [String] = []) {        self.ids = ids    }    public init(from decoder: Decoder) throws {        let values = try decoder.container(keyedBy: CodingKeys.self)        if let one = try? values.decode(String.self, forKey: .id) {            ids = [one]        } else {            ids = (try? values.decode([String].self, forKey: .ids)) ?? []        }    }    private enum CodingKeys: String, CodingKey { case id, ids }}// MARK: - `capture.media`/// The three kinds `capture.media` captures.////// A closed enum rather than a string, so a kind the method refuses cannot be/// spelt from up here. The rest of `MediaKind` is absent BY DECISION and not by/// omission: `statement` is filed as a document now, and `meeting`, `message`,/// `avatar` and `session` each belong to a row something else writes first.public enum CaptureMediaKind: String, Sendable, CaseIterable {    case photo    case video    case document}/// What the share sheet just handed over.////// `filename` and `takenAt` are the crate's own spellings/// (`validate_capture`, `phone/media.rs:131-240`) and are kept verbatim: a/// camelCased `fileName` here would arrive as an absent argument and the row/// would carry no original name, silently.public struct CaptureMediaRequest: Encodable, Sendable, Equatable {    /// Where the bytes are NOW — the share extension's copy inside the app    /// group. Copied into the store, never referenced in place.    public var path: String    /// What kind of file this is. Checked against the kind's own list before a    /// byte moves, so a type the server would refuse is refused here first.    public var mime: String    public var kind: String    /// What the sharing app called it, when it said.    public var filename: String?    /// When the picture was taken, when the sharing app knew. Absent means    /// "now", which is what an unlabelled share is.    public var takenAt: String?    /// The 256 px grid thumbnail, as a PATH — `MediaTiers` encoded it a moment    /// ago into the caller's own temp directory.    ///    /// **Absent means "this could not be made", and that is the only way to say    /// it.** The crate refuses a path that is not there by name, deliberately:    /// a caller that sent one believes it did something, and quietly dropping    /// it would be a silent fallback. A capture whose tiers all failed sends    /// none of these four and lands anyway.    public var thumbPath: String?    /// The 1600 px rendition. Absent for a picture at or under two megapixels,    /// which IS its own display tier.    public var displayPath: String?    /// A film's still frame. Only a video ever carries one; the crate refuses    /// it on anything else by name.    public var posterPath: String?    /// The 24 px blur, base64, at most    /// `MediaTiers.previewMaxBase64Bytes`. It is a STRING and not a path    /// because it is a replicated COLUMN on the row — which is why a tile has    /// something to draw on a device that has never held these bytes.    public var preview: String?    /// `"thought"` for a picture a new thought will carry: it is stored in    /// Personal, where `capture.create` writes the thought, so the thought's    /// file holds the photo its attachments name. Absent, the picture is    /// stored in the database the call names — the Photos list's, the    /// record's — because that is the file whatever names it is in.    public var into: String?    /// How its bytes go up (MEDIA DRAIN 1, KEEP 1e): `wifi` holds them off Wi-Fi; absent is any network, as every    /// capture has always gone.    public var network: String?    /// The app or act that queued it (`albums.keep`).    public var askedBy: String?    /// `photos`: a copy of an original the phone's Photos library keeps, released from this phone once the object    /// holds it. Absent is a capture this phone keeps for good.    public var source: String?    public init(        path: String,        mime: String,        kind: CaptureMediaKind,        filename: String? = nil,        takenAt: String? = nil,        tiers: MediaTiers = .none,        forThought: Bool = false,        upload: CaptureUpload = CaptureUpload()    ) {        self.network = upload.network        self.askedBy = upload.askedBy        self.source = upload.source        self.path = path        self.mime = mime        self.kind = kind.rawValue        self.filename = filename        self.takenAt = takenAt        self.into = forThought ? "thought" : nil        self.thumbPath = tiers.thumbPath        self.displayPath = tiers.displayPath        self.posterPath = tiers.posterPath        self.preview = tiers.preview    }}/// How a capture's bytes go up and where else they live (`capture.media`'s `network`, `askedBy`, `source`).public struct CaptureUpload: Sendable, Equatable {    public var network: String?    public var askedBy: String?    public var source: String?    public init(network: String? = nil, askedBy: String? = nil, source: String? = nil) {        self.network = network        self.askedBy = askedBy        self.source = source    }}/// `capture.media`'s answer — the object key, the row that points at it, and/// for a film sent with its still, the still's key (`posterKey`; nil for a/// photo, a document, or a film the phone could cut no frame from).public struct MediaCaptured: Decodable, Equatable, Sendable {    public var key: String    public var recordId: String    public var posterKey: String?    public init(key: String = "", recordId: String = "", posterKey: String? = nil) {        self.key = key        self.recordId = recordId        self.posterKey = posterKey    }    public init(from decoder: Decoder) throws {        let values = try decoder.container(keyedBy: CodingKeys.self)        key = (try? values.decode(String.self, forKey: .key)) ?? ""        recordId = (try? values.decode(String.self, forKey: .recordId)) ?? ""        posterKey = try? values.decodeIfPresent(String.self, forKey: .posterKey)    }    private enum CodingKeys: String, CodingKey { case key, recordId, posterKey }}