Cotton code
144 lines · 6.5 KB · SwiftRaw
// The chat's reading rules, as pure functions — the four screens' shared half,// and the one attachment row all four build from the answer's JSON.//// They live here rather than inside a model because three of the four screens// read them: a rule that lived in one model would be copied into the next, and// two copies of "which day is this" is exactly the drift this file exists to// prevent. ``MessageMedia`` is here for the same reason — the bubble's grid,// the gallery, the info strip and the media tab all read one attachment, and a// row declared beside one of them would be copied into the other three.//// **The clock is injected everywhere.** Not one function below reads `Date()`.import CottonKitimport Foundation// MARK: - One attachment/// One attachment, built from the answer's own JSON.////// **A KEPT typed row.** The conversation's prints, the voice strip, the/// gallery, the info strip and the media tab all read one attachment, and two/// ladders (``isImage`` here, `ThreadMediaSections.isVisual`)/// read the stated kind against the content type; pulling the fields out of/// the JSON once, here, is what stops a note from re-reading them per redraw. Not `Decodable` — the boundary's shapes are JSON, and a second/// decoder over the same answer would be a second reading of it.////// Two legal shapes, told apart by which of `key` / `url` is present — the/// crate hands the stored array on as it is stored, and both forms reach the/// app.////// **Every drawing field is optional in the stored entry.** `read.threadMedia`/// and `read.threadInfo`'s strip hand the stored column on UNTOUCHED;/// `read.thread` runs it through `media_out`, which carries `kind`, `width`,/// `height`, `sizeBytes` and `preview` through only when the writer set them,/// because a grid that has to resolve two hundred keys before it knows how/// tall a bubble is draws the conversation twice. An entry the sender never/// measured or stated — an imported archive, a hand-filed attachment — carries/// none of them, so a reader falls back to the content type whenever `kind` is/// absent, which is the same ladder every other media reader walks.struct MessageMedia: Equatable, Sendable {    /// The content-addressed object key. `read.mediaPath` is what turns one    /// into a path on THIS device; nothing in Swift fetches bytes.    var key: String?    var url: String?    var contentType: String = ""    var name: String?    /// The sender's own STATED kind (`image`, `video`, `voice`, `audio`,    /// `file`, `contact`), which outranks the content type — the importer    /// guessed the type from a file extension, the sending app stated the kind.    var kind: String?    /// The picture's own size in pixels, when the sender measured it. BOTH or    /// neither: an entry carrying one of the pair is a shape nothing writes,    /// and a grid that trusted a lone width would divide by zero.    var width: Int?    var height: Int?    /// How many bytes the object is. Absent on an imported archive that never    /// measured them.    var sizeBytes: Int?    /// A 32px JPEG in base64 — bounded by construction, which is why it is the    /// ONE picture this app holds in memory. `PhotosBlur` decodes it, and it is    /// what a tile shows while the real bytes resolve.    var preview: String?    /// A recording's length, when the sender measured it.    var durationMs: Int?    var playbackKey: String?    var playbackContentType: String?    /// Ogg/Opus remains the original. Only its playable rendition goes to    /// AVFoundation; other sources may already store a playable original.    var audioPlaybackKey: String? {        guard isAudio else { return nil }        if let playbackKey, !playbackKey.isEmpty { return playbackKey }        let type = contentType.lowercased().split(separator: ";").first.map(String.init) ?? ""        return ["audio/wav", "audio/x-wav", "audio/mp4", "audio/mpeg", "audio/aac", "audio/flac", "audio/caf", "audio/x-caf"].contains(type) ? key : nil    }    /// A voice note's drawn waveform, 0…1 per sample — the owner's app only    /// (`media_out`). Empty for a recording nobody sampled, which draws no    /// waveform rather than a flat line.    var waveform: [Double] = []    init(        key: String? = nil,        url: String? = nil,        contentType: String = "",        name: String? = nil,        kind: String? = nil,        width: Int? = nil,        height: Int? = nil,        sizeBytes: Int? = nil,        preview: String? = nil,        durationMs: Int? = nil,        playbackKey: String? = nil,        playbackContentType: String? = nil,        waveform: [Double] = []    ) {        self.key = key        self.url = url        self.contentType = contentType        self.name = name        self.kind = kind        self.width = width        self.height = height        self.sizeBytes = sizeBytes        self.preview = preview        self.durationMs = durationMs        self.playbackKey = playbackKey        self.playbackContentType = playbackContentType        self.waveform = waveform    }    /// One entry of a message's `media` array. The base64 `preview` is read    /// UNTRIMMED because it is bytes rather than a label.    init(_ json: JSONValue) {        key = json.text("key")        url = json.text("url")        contentType = json.text("contentType") ?? ""        name = json.text("name")        kind = json.text("kind")        width = json.number("width")        height = json.number("height")        sizeBytes = json.number("sizeBytes")        preview = json.untrimmed("preview")        durationMs = json.number("durationMs")        playbackKey = json.text("playbackKey")        playbackContentType = json.text("playbackContentType")        waveform = (json["waveform"]?.array ?? []).compactMap(\.double)    }    /// Is this entry a PICTURE — the one kind the grid draws?    ///    /// The stated kind outranks the content type: the importer guessed the    /// type from a file extension, the sending app stated the kind. A film is    /// not a picture here: the viewer plays it (`ViewerPlayer.swift`).    var isVideo: Bool { kind == "video" || (kind == nil && contentType.hasPrefix("video/")) }    var isAudio: Bool { ["voice", "audio"].contains(kind ?? "") || (kind == nil && contentType.hasPrefix("audio/")) }    var isImage: Bool {        switch kind {        case "image": return true        case "video", "voice", "audio", "file", "contact": return false        default: break        }        return contentType.hasPrefix("image/")    }}