//! Bytes on the phone: `capture.media`, `media.ensure`, and the seam that //! brings bytes back DOWN. //! //! ## The rule these three exist to keep //! //! **Bytes are offline-first — the phone holds them, permanently** (AGENTS.md). //! A new file is copied into the content-addressed media store, the RECORD row //! is written locally carrying the object KEY, and a `_media` ledger row queues //! the upload for the media drain to carry with backoff. No screen waits on an //! upload, no row is deleted because one failed, and no renderer fetches what //! `ensureLocal(key)` can answer from disk. //! //! Every one of those three pieces already exists in this tree — //! `cotton_client::media::store::put_media_file`, the key builders in //! `cotton_core::media::keys`, and `cotton_store::media_ledger` — so nothing //! here is a second implementation of any of them. What is here is the ORDER: //! bytes first, then the row, then the ledger, all inside one write. //! //! ## Bytes never cross the FFI boundary //! //! Design M4/P-rule: a read answers a PATH and Swift reads the file itself. //! `media.ensure` answers a path, `read.mediaPath` answers a path or //! `present: false`, and `capture.media` TAKES a path — a //! base64 `bytes` argument would put a 500 MB recording through a JSON string //! twice, which is the jetsam kill this repo has already paid for once. //! //! ## Why the fetch is a SEAM and not an HTTP call written here //! //! The bytes come from wherever this device's database is served, and only //! the connection knows that: `personal.connect` installs the object's GET //! (`phone::personal_object::ObjectMedia`, `GET /v1/media/` under the //! object's bearer, a rendition asked at its width). A build or a launch with //! none is refused BY NAME rather than handed an invented path: see //! [`NO_MEDIA_FETCH`]. The way UP is the drain's, over the same door //! (`cotton_client::media::transport::ObjectMediaTransport`). //! //! ## One capture //! //! `capture.media` files a photo, video, document or book and refuses other //! kinds. Documents reuse the record their bytes already name, as MCP intake //! does, and so does a book: the same file shared twice is one book. //! //! A BOOK (`kind: "book"`, the books kit's `book` table) is an EPUB or a PDF //! under `/books/.`, and its row is made here with what the //! phone read from the file (`book: { format, title, author?, language?, //! isbn?, pages? }`), `source: file`, `status: want_to_read` and `added_on` //! the phone's own day (its time zone, as the app opened the core). Its cover //! (`coverPath`, the picture the phone took from the file: JPEG, PNG, GIF or WebP) is kept as a //! picture key in `cover`, uploaded like any picture, and NO Photos row is //! made: a book's cover is not a photo the person took. use std::path::{Path, PathBuf}; use serde_json::{json, Map, Value}; use cotton_client::layout::Layout; use cotton_client::media::store::{media_file_path, put_media_file, sha256_file}; use cotton_core::books::{stamped, FROM_OPF}; use cotton_core::media::keys::{ avatar_key, book_key, document_original_key, media_kind_for, media_limits, photo_display_key, photo_key, photo_thumb_key, video_display_key, video_key, video_poster_key, video_thumb_key, MediaKind, BOOK_EXTENSIONS, }; use cotton_store::media_holdings::{record_holding, Tier as HoldTier}; use cotton_store::media_ledger::{enqueue_media, mark_viewed, media_by_key, MediaEnqueueInput}; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::handlers::common::{insert_row, text, update_row}; use cotton_tools::mcp::handlers::documents::tools::{ document_with_bytes, new_document_id, out_of_the_bin_again, }; use crate::handle::CottonHandle; use crate::methods::MethodError; use crate::phone::io_trouble::io_refusal; /// How bytes come DOWN, when something has given this device a way. /// /// One method, because there is one question; see the module note for who /// answers it. pub trait MediaFetch: Send + Sync + std::fmt::Debug { /// Write the bytes behind one object key INTO `dest`, or say why they did /// not come. /// /// **A path, never a `Vec`, and this is the same rule twice.** A /// meeting recording is routinely hundreds of megabytes and a video can be /// half a gigabyte; a signature that handed those back as bytes would hold /// the whole file in memory on a phone, which is precisely the jetsam kill /// build 106 already paid for — no exception, no Bugsink event, read by the /// person as a white screen. It is also the shape the way UP already has: /// `cotton_client::media::drain::MediaDrainDeps::upload` streams from a /// path, and coming down is the same problem mirrored. /// /// `dest` is a scratch file the caller owns and will rename; an /// implementation writes it and returns, and a partial write is the /// caller's to clean up. /// /// `database` is the file the key belongs to, as the caller holds it — the /// request names it, because the server signs a key only inside the /// database a request is about. fn fetch_to(&self, database: &str, key: &str, dest: &Path) -> Result<(), NotFetched>; } /// Why bytes did not come down: the reason in the transport's own words, for /// the log and the error's details, and what the server answered — `Some(0)` /// when it never answered, `None` when the trouble was on this device. #[derive(Debug, Clone, PartialEq, Eq)] pub struct NotFetched { pub waiting: Option<(String, String)>, pub reason: String, pub status: Option, } impl NotFetched { /// Does what arrived stay, for the next fetch to resume? A cut or a /// dropped line (status 0) keeps it; an answer from the store does not. pub fn keeps_partial(&self) -> bool { self.waiting.is_none() && self.status == Some(0) } } impl From for NotFetched { fn from(reason: String) -> Self { NotFetched { reason, status: None, waiting: None } } } /// What `media.ensure` answers when the bytes did not come: a sentence a page /// can print as it is, with the key, the transport's reason and the status in /// `details` — a grid asks for many keys, and a log must still say which. /// /// `mac_away` is this device's own copy saying the serving Mac is not /// reachable (`sync_state::serving_away`). Only then does a fetch that /// reached no server say the Mac could not be reached: one failed fetch on a /// phone that is online and a Mac that answers is not the Mac away (walker /// pass 5: Documents said it was). pub(crate) fn not_fetched(key: &str, trouble: &NotFetched, mac_away: bool) -> MethodError { if let Some((code, holder)) = &trouble.waiting { let sentence = if code == "holder_asleep" { format!("{holder} is asleep.") } else { format!("Coming from {holder}.") }; return MethodError::new(code, sentence).with_details(json!({ "key": key, "reason": trouble.reason, "status": trouble.status, "holder": holder, })); } let (code, sentence) = match trouble.status { Some(404) => ( "bytes_not_uploaded", "This file is not on this device yet, and it has not reached Cotton either. It will \ open once the device that added it has sent it.", ), // The one sentence for a missing byte while the Mac is away (walker's // offline pass): the phone is online, the Mac is not, so it never // says "when this device is online"; the page's Fetch act retries. Some(0) if mac_away => ("mac_away", "Not on this phone yet \u{2014} the Mac that keeps it could not be reached"), Some(0) => ("unreachable_server", "Not on this phone yet \u{2014} it could not be fetched just now"), Some(_) => ( "unreachable_server", "This file is not on this device, and Cotton did not hand it over just now. Try again \ in a while.", ), None => ( "unreadable", "This file came down but could not be saved on this device. Try again.", ), }; MethodError::new(code, sentence).with_details(json!({ "key": key, "reason": trouble.reason, "status": trouble.status, })) } /// The trigger to run once the bytes land. /// /// A closed enum rather than a `&str`, so a typo is a compile error and a /// trigger the server does not know cannot be written into `_media.after`. /// /// `statement_parse` is NOT one of them: it left with schema v23 — the share /// sheet and the Documents screen file the paper as a DOCUMENT and the /// statements worker reads it — so there is no money-specific upload trigger /// any more. THIS enum is where the union is declared — it is what goes into /// the `after` column of `_media` /// (`crates/cotton-store/src/media_ledger.rs`). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MediaAfter { /// The documents pipeline: unlock, extract, summarise, land. DocumentProcess, } impl MediaAfter { pub const fn as_str(self) -> &'static str { match self { MediaAfter::DocumentProcess => "document_process", } } } /// The sentence `media.ensure` answers with when nothing has filled the seam. pub const NO_MEDIA_FETCH: &str = "This file is not on this device yet, and this device cannot fetch it just now. Nothing is \ lost: it comes down once this device can reach Cotton."; // ── capture.media ─────────────────────────────────────────────────────────── /// The ceiling on the blur, in bytes of base64 — `cotton-core`'s, re-exported. /// /// ONE number for both producers. This constant used to be declared here at /// 1,536 (with the measurement that 1,024 is unreachable for a baseline JPEG /// written beside it) while the Mac's tiers worker declared its own at 1,024 /// and REFUSED every blur over it, resting the row for thirty days: the /// library's thumbnails never got made and `_media_tiers_skips` filled with /// the refusals. The reasoning and the number live in /// `cotton_core::media::tiers`, and `media_tests.rs` holds this re-export to it. pub use cotton_core::media::tiers::PREVIEW_MAX_BASE64_BYTES; /// The renditions Swift made before it called, as PATHS. /// /// **Still no bytes across this boundary** — the module's first rule, unchanged. /// ImageIO and AVFoundation live on the phone and Rust has no decoder for HEIC /// at all (there is no `image`, `libheif` or `webp` crate in this workspace, on /// purpose), so the tiers are encoded in Swift, written to the caller's own /// temp directory, and named here. The one string is the blur, and it is a /// string because it is a COLUMN: see [`PREVIEW_MAX_BASE64_BYTES`]. /// /// Every field is optional and each `None` is a real state rather than a gap: /// a picture already at or under two megapixels gets no `display` (the original /// IS the display tier), only a film has a `poster`, and a file ImageIO cannot /// decode arrives with all four empty and is captured anyway. **A capture never /// fails because a thumbnail could not be made** — the original is the point, /// and the Mac's backlog worker makes the rest later. #[derive(Debug, Default)] pub struct CaptureTiers { /// The 256 px grid thumbnail, JPEG. pub thumb: Option, /// The 1600 px rendition a detail view opens, JPEG. Absent for a picture /// that is already small enough to be its own. pub display: Option, /// A film's still frame, JPEG. Absent for anything that is not a film. pub poster: Option, /// The 24 px blur, base64, capped at [`PREVIEW_MAX_BASE64_BYTES`]. pub preview: Option, } /// What the person just picked. #[derive(Debug)] pub struct CaptureMediaArgs { /// Where the bytes are NOW — the share extension's inbox, the picker's temp /// copy. Copied into the store, never referenced in place. pub path: PathBuf, pub mime: String, pub filename: Option, pub kind: MediaKind, /// When the picture was taken, when the picker knew. `None` means "now", /// which is what a camera capture is. pub taken_at: Option, /// The renditions the phone encoded a moment ago; see [`CaptureTiers`]. pub tiers: CaptureTiers, /// A book's facts, read from its file; `Some` exactly for `kind: "book"`. pub book: Option, /// How its bytes go up, and where else they live ([`CaptureUpload`]). pub upload: CaptureUpload, } /// How a capture's bytes go up (MEDIA DRAIN 1, KEEP 1e): written on its /// ledger rows in the capture's own transaction. All `None` is every app's /// capture as it always was: any network, nobody named, Cotton's own bytes. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct CaptureUpload { /// `wifi` holds the file while the phone is not on Wi-Fi; `None` or /// `any` goes on any network. pub network: Option, /// The app or act that queued it (`albums.keep`). pub asked_by: Option, /// `photos`: a copy of an original the phone's Photos library keeps. Not /// a capture this phone made for good: once the object holds it, its /// local original leaves (`cotton_client::media::release`). pub source: Option, } /// The upload words a capture may carry, refused before a byte moves. fn validate_upload(request: &Value) -> Result { let word = |field: &str| request.get(field).and_then(Value::as_str).map(str::trim).filter(|word| !word.is_empty()).map(str::to_string); let network = word("network"); if let Some(network) = network.as_deref() { if !matches!(network, "any" | "wifi") { return Err(MethodError::new("bad_request", format!("`{network}` is not a network rule: `any` or `wifi`"))); } } let source = word("source"); if let Some(source) = source.as_deref() { if source != cotton_client::media::release::PHOTOS_SOURCE { return Err(MethodError::new("bad_request", format!("`{source}` is not a place this phone copies from: `photos`"))); } } let asked_by = word("askedBy"); if asked_by.as_deref().is_some_and(|asked| asked.len() > 64) { return Err(MethodError::new("bad_request", "`askedBy` names an app or an act in at most 64 characters")); } Ok(CaptureUpload { network, asked_by, source }) } /// What the phone read from a book's own file (the EPUB's package document, /// the PDF's attributes), and its cover. #[derive(Debug, Default)] pub struct CaptureBook { /// `epub` or `pdf`: the key's extension and the row's `format`. pub format: String, pub title: String, /// The book row's other columns the file says, by key: `author`, /// `language`, `isbn` and, for an EPUB the core reads, the whole /// package's (`EpubFacts::columns`). pub columns: Map, /// Where `columns` came from, as the row's `filled_from` says each one /// it writes (`cotton_core::books::SOURCES`): `opf` for an EPUB's package /// or a Calibre `metadata.opf`; none for what a shell read off a PDF. pub columns_from: Option<&'static str>, /// A PDF's page count; an EPUB has no pages. pub pages: Option, /// The device's own IANA zone, which the row's `added_on` is the day in; /// set by [`capture`] from the zone the app opened the core with. pub zone: String, /// The cover the phone took from the file (a PDF's first page), or the /// one the core took from an EPUB: JPEG, PNG, GIF or WebP. pub cover: Option, /// The EPUB's own cover, written beside the book's file while it is /// captured, and gone when the capture is. pub cover_read: Option, /// The book this file is for (a book's Add file): its `file` and /// `format` set, and what the file says filling only its empty columns. /// Absent, the file is a book of its own. pub into: Option, } /// A book cover's content type by its extension, as the EPUB carries it: the /// picture types the object keeps (`media_limits(Photo)`). fn cover_type(ext: &str) -> Option<&'static str> { match ext { "jpg" | "jpeg" => Some("image/jpeg"), "png" => Some("image/png"), "gif" => Some("image/gif"), "webp" => Some("image/webp"), _ => None, } } /// The content type of a book's format: the one [`media_limits`] accepts for it. fn book_mime(format: &str) -> Option<&'static str> { match format { "epub" => Some("application/epub+zip"), "pdf" => Some("application/pdf"), _ => None, } } /// `book` and `coverPath`, refused by name on any kind but a book and /// required on a book; checked before a byte moves. fn validate_book(request: &Value, kind: MediaKind, mime: &str) -> Result, MethodError> { let bad = |message: String| MethodError::new("bad_request", message); if kind != MediaKind::Book { for field in ["book", "coverPath", "into"] { if request.get(field).is_some() { return Err(bad(format!("a {kind} has no `{field}`: only a book carries one"))); } } return Ok(None); } let facts = request .get("book") .and_then(Value::as_object) .ok_or_else(|| bad("a book names its format as `book: { format }`, and a PDF what its file says: `{ title?, pages? }`".to_string()))?; let words = |key: &str| facts.get(key).and_then(Value::as_str).map(str::trim).filter(|value| !value.is_empty()).map(str::to_string); let format = words("format").unwrap_or_default(); if !BOOK_EXTENSIONS.contains(&format.as_str()) { return Err(bad(format!("a book's format is epub or pdf, not `{format}`"))); } if book_mime(&format) != Some(mime) { return Err(bad(format!("a {format} book is {}, not `{mime}`", book_mime(&format).unwrap_or_default()))); } // THE CORE READS AN EPUB (6 Nov 2026): a shell // that sends an EPUB with no title hands its reading to the core — // title, author, language, ISBN and cover from the package document, // the file's name where it says no title. iOS's BookFile still sends // what it read; a PDF is the shell's to read (no PDF reader here), its // title its name when the shell has none. let file_name = request.get("filename").and_then(Value::as_str).and_then(cotton_core::media::book_file::title_from_file_name); if format == "epub" && words("title").is_none() { for said in ["author", "language", "isbn", "pages"] { if facts.get(said).is_some() { return Err(bad(format!("an EPUB the core reads says its own `{said}`: send none"))); } } if request.get("coverPath").is_some() { return Err(bad("an EPUB the core reads says its own cover: send no `coverPath`".to_string())); } return read_epub_book(request, file_name, into_of(request)?); } let title = words("title").or(file_name).ok_or_else(|| bad("a book has a title: the file's own, else its name (`filename`)".to_string()))?; let pages = match facts.get("pages") { None | Some(Value::Null) => None, Some(value) => Some(value.as_u64().filter(|pages| *pages > 0).ok_or_else(|| bad("a book's `pages` is a whole number above none".to_string()))?), }; let cover = tier_path(request, "coverPath")?; if let Some(cover) = cover.as_ref() { let ext = cover.extension().and_then(std::ffi::OsStr::to_str).map(str::to_lowercase).unwrap_or_default(); if cover_type(&ext).is_none() { return Err(bad(format!("a book's cover is a .jpg, .png, .gif or .webp, not `{}`", cover.display()))); } } let into = into_of(request)?; let columns: Map = ["author", "language", "isbn"].into_iter().filter_map(|column| words(column).map(|value| (column.to_string(), Value::from(value)))).collect(); Ok(Some(CaptureBook { format, title, columns, columns_from: None, pages, zone: String::new(), cover, cover_read: None, into })) } /// One book of a folder (Books' Add a folder), checked as `capture.media` /// checks a book before a byte moves: its staged file at `path`, its format, /// what its `metadata.opf` and file say (`columns`, its title apart), and its /// cover — a picture staged beside it, or the EPUB's own, written beside the /// file for the capture and gone with it. pub(crate) fn folder_book( path: &Path, filename: &str, format: &str, title: String, columns: Map, cover: Option, ) -> Result { let mime = book_mime(format).ok_or_else(|| MethodError::new("bad_request", format!("a book's format is epub or pdf, not `{format}`")))?; check_ceiling(MediaKind::Book, &path.to_string_lossy(), mime)?; let usable = |ext: &str| cover_type(if ext == "jpeg" { "jpg" } else { ext }).is_some(); let (cover, cover_read) = match cover { None => (None, None), Some(FolderCover::Staged(staged)) => { let ext = staged.extension().and_then(std::ffi::OsStr::to_str).map(str::to_lowercase).unwrap_or_default(); (usable(&ext).then_some(staged), None) } Some(FolderCover::Read(cover)) if usable(&cover.extension) => { let folder = path.parent().filter(|folder| !folder.as_os_str().is_empty()).unwrap_or(Path::new(".")); let written = tempfile::Builder::new() .prefix(".cover-") .suffix(&format!(".{}", cover.extension)) .tempfile_in(folder) .and_then(|mut file| std::io::Write::write_all(&mut file, &cover.bytes).map(|()| file.into_temp_path())) .map_err(|error| MethodError::new("unreadable", io_refusal(format!("{filename}'s cover could not be written beside it"), folder, &error)))?; (Some(written.to_path_buf()), Some(written)) } Some(FolderCover::Read(_)) => (None, None), }; Ok(CaptureMediaArgs { path: path.to_path_buf(), mime: mime.to_string(), filename: Some(filename.to_string()), kind: MediaKind::Book, taken_at: None, tiers: CaptureTiers::default(), book: Some(CaptureBook { format: format.to_string(), title, columns, columns_from: Some(FROM_OPF), pages: None, zone: String::new(), cover, cover_read, into: None }), upload: CaptureUpload::default(), }) } /// A folder book's cover: a picture staged from the folder, or the one its /// EPUB carries. pub(crate) enum FolderCover { Staged(PathBuf), Read(cotton_core::media::book_file::EpubCover), } /// `into`: the book a file is for, by its id. fn into_of(request: &Value) -> Result, MethodError> { match request.get("into") { None | Some(Value::Null) => Ok(None), Some(Value::String(id)) if !id.trim().is_empty() => Ok(Some(id.trim().to_string())), Some(_) => Err(MethodError::new("bad_request", "`into` names the book this file is for by its id")), } } /// An EPUB's facts as the core reads them off the file at `path` /// (`cotton_core::media::book_file`), its cover written beside the file for /// the capture to keep. A file that is no EPUB is refused before a byte moves. fn read_epub_book(request: &Value, file_name: Option, into: Option) -> Result, MethodError> { let path = request.get("path").and_then(Value::as_str).map(str::trim).filter(|path| !path.is_empty()).map(PathBuf::from) .ok_or_else(|| MethodError::new("bad_request", "`path` is where the bytes are now"))?; let shown = file_name.clone().unwrap_or_else(|| "this book".to_string()); let reader = crate::phone::whatsapp_import::FileRanges::open(&path, &shown)?; let facts = cotton_core::media::book_file::read_epub(&reader).map_err(|trouble| MethodError::new("unreadable", trouble.to_string()))?; let columns = facts.columns(); let title = facts.package.title.or(file_name).ok_or_else(|| MethodError::new("bad_request", "an EPUB that says no title is named by its `filename`"))?; let cover_read = match facts.cover.filter(|cover| cover_type(&cover.extension).is_some()) { None => None, Some(cover) => { let folder = path.parent().filter(|folder| !folder.as_os_str().is_empty()).unwrap_or(Path::new(".")); let written = tempfile::Builder::new() .prefix(".cover-") .suffix(&format!(".{}", cover.extension)) .tempfile_in(folder) .and_then(|mut file| std::io::Write::write_all(&mut file, &cover.bytes).map(|()| file.into_temp_path())) .map_err(|error| MethodError::new("unreadable", io_refusal(format!("{shown}'s cover could not be written beside it"), folder, &error)))?; Some(written) } }; let cover = cover_read.as_ref().map(|written| written.to_path_buf()); Ok(Some(CaptureBook { format: "epub".into(), title, columns, columns_from: Some(FROM_OPF), pages: None, zone: String::new(), cover, cover_read, into })) } /// The kind's ceiling and its content types, answered off the file's /// metadata before a byte moves. fn check_ceiling(kind: MediaKind, path: &str, mime: &str) -> Result<(), MethodError> { // THE CEILING AND THE TYPE, also before the copy. Both are read from the // kind's own declaration rather than from numbers written here, and both // would be refused by the server when the upload URL is minted — finding // that out three hours later on a train is worse than finding it out now, // and finding it out AFTER the bytes are in the store is worse than either. let limit = media_limits(kind); let size_bytes = std::fs::metadata(path) .map_err(|error| { MethodError::new( "bad_request", format!("there is no file at `{path}` to capture: {error}"), ) })? .len(); if size_bytes > limit.max_bytes { return Err(MethodError::new( "too_large", format!( "this {kind} is {size_bytes} bytes, over the {} the server will accept for one", limit.max_bytes ), )); } if !limit.content_types.contains(&mime) { return Err(MethodError::new( "bad_request", format!( "the server will not take a {kind} of type `{mime}` — it accepts {}", limit.content_types.join(", ") ), )); } Ok(()) } pub fn validate_capture(request: &Value) -> Result { if request.get("bytes").is_some() { // NOT SILENTLY IGNORED, and not accepted either. See the module note: // a body this size through JSON is the jetsam kill build 106 already // paid for, and the boundary rule is that bytes never cross it. return Err(MethodError::new( "bad_request", "bytes never cross this boundary — write the file to disk and pass its `path`", )); } let path = request .get("path") .and_then(Value::as_str) .map(str::trim) .filter(|path| !path.is_empty()) .ok_or_else(|| MethodError::new("bad_request", "`path` is where the bytes are now"))?; let mime = request .get("mime") .and_then(Value::as_str) .map(str::trim) .filter(|mime| !mime.is_empty()) .ok_or_else(|| MethodError::new("bad_request", "`mime` is what kind of file this is"))?; let kind = request .get("kind") .and_then(Value::as_str) .unwrap_or_default(); let kind = MediaKind::ALL .into_iter() .find(|candidate| candidate.as_str() == kind) .ok_or_else(|| { MethodError::new( "bad_request", format!("`{kind}` is not a kind of media this database stores"), ) })?; // WHICH KINDS THIS METHOD CAPTURES, decided HERE rather than after the // copy. `write_media` used to refuse `statement` on its way past the key // builder — by which point `put_media_file` had already written the bytes // into the store, so a refused capture left a file behind that nothing // would ever reference or sweep. // // The six refusals are written reasons, not gaps: `statement` is filed as // a DOCUMENT now (`statement_parse` left with schema v23), and `meeting`, // `message`, `avatar`, `walkthrough` and `session` are each a file that // belongs to a row something else writes first — a meeting's segments to a // recording in progress, a message's to a thread, an avatar's to a person, // and a `walkthrough` key's bytes to the `cotton_feedback` row // they are the picture of. // `capture.media` mints its own record, which is exactly what those must // not do. // // `meeting` STAYS REFUSED, and now there is a door beside the refusal: // `meetings.create` (`phone/meetings.rs`) is the one producer of a // `cotton_meetings` row, for both the recorder and the importer. A meeting // is a row with a STATUS the server's pipeline walks and an audio key its // manifest names; minting one as a side effect of a generic media capture // would put the two entrances on two different producers. if !matches!( kind, MediaKind::Photo | MediaKind::Video | MediaKind::Document | MediaKind::Book ) { return Err(MethodError::new( "bad_request", format!( "`{kind}` is not a kind of file this method captures: it belongs to a record \ something else writes first, and this method mints its own" ), )); } check_ceiling(kind, path, mime)?; // THE TIERS, and every refusal about them is ALSO before the copy — the // same order the ceiling and the content type already keep, for the same // reason. In particular the blur's cap is checked here, so an over-cap // preview costs the person a retry rather than a photograph. let tiers = validate_tiers(request, kind)?; let book = validate_book(request, kind, mime)?; let upload = validate_upload(request)?; if upload.source.is_some() && !matches!(kind, MediaKind::Photo | MediaKind::Video) { return Err(MethodError::new("bad_request", "only a photo or a video is copied from Photos")); } Ok(CaptureMediaArgs { path: PathBuf::from(path), mime: mime.to_string(), filename: request .get("filename") .and_then(Value::as_str) .map(str::trim) .filter(|name| !name.is_empty()) .map(str::to_string), kind, taken_at: request .get("takenAt") .and_then(Value::as_str) .map(str::to_string), tiers, book, upload, }) } /// One tier path, proved to be a file before anything is copied anywhere. /// /// **A named path that is not there is a refusal, not a shrug.** The caller /// wrote this file seconds ago in its own temp directory; if it has gone, the /// honest answer is to say which one and let the capture be retried, and the /// refusal is free because it happens before a single byte has moved. The /// alternative — quietly dropping a tier the caller said it had made — is the /// silent fallback this repo does not ship. /// /// The way a caller says "I could not make this one" is to send NOTHING. That /// is what `MediaTiers` in `CottonKit` does when ImageIO cannot read the file, /// and it is why a capture still lands when the tiers cannot be made. fn tier_path(request: &Value, field: &str) -> Result, MethodError> { let Some(raw) = request .get(field) .and_then(Value::as_str) .map(str::trim) .filter(|path| !path.is_empty()) else { return Ok(None); }; let size = std::fs::metadata(raw) .map_err(|error| { MethodError::new( "bad_request", format!( "`{field}` names `{raw}` and there is no file there: {error}. Send no \ `{field}` at all when the rendition could not be made — the capture lands \ without it." ), ) })? .len(); if size == 0 { return Err(MethodError::new( "bad_request", format!("`{field}` names `{raw}`, which is an empty file"), )); } Ok(Some(PathBuf::from(raw))) } /// The four tier arguments, each refused by name when it does not belong to /// this kind of file. /// /// A document has no tier ladder at all — it is a PDF, and the pages it draws /// come from the documents pipeline — and a poster is the first frame of a /// film, so neither belongs on a photograph. Refusing rather than ignoring is /// the point: a caller that sent one believes it did something. fn validate_tiers(request: &Value, kind: MediaKind) -> Result { let ladder = matches!(kind, MediaKind::Photo | MediaKind::Video); for field in ["thumbPath", "displayPath", "preview"] { if !ladder && request.get(field).is_some() { return Err(MethodError::new( "bad_request", format!("a {kind} has no `{field}`: only a photo and a video carry renditions"), )); } } if kind != MediaKind::Video && request.get("posterPath").is_some() { return Err(MethodError::new( "bad_request", format!("a {kind} has no `posterPath`: a poster is the still frame of a film"), )); } let preview = request .get("preview") .and_then(Value::as_str) .map(str::trim) .filter(|preview| !preview.is_empty()) .map(str::to_string); if let Some(preview) = preview.as_deref() { // BEFORE THE BYTES MOVE, and the sentence says the number: this string // goes into a replicated column on every device. if preview.len() > PREVIEW_MAX_BASE64_BYTES { return Err(MethodError::new( "too_large", format!( "`preview` is {} bytes of base64, over the {PREVIEW_MAX_BASE64_BYTES} a blur \ may be: it is a column every device carries, so it is a 24 px picture and \ nothing more", preview.len() ), )); } } Ok(CaptureTiers { thumb: tier_path(request, "thumbPath")?, display: tier_path(request, "displayPath")?, poster: tier_path(request, "posterPath")?, preview, }) } /// `capture.media` — the bytes, then the row, then the ledger. pub fn capture(handle: &CottonHandle, request: &Value) -> Result { let mut args = validate_capture(request)?; capture_args(&handle.client(), &mut args) } /// A capture already checked, through the one writer: the bytes, the row and /// the ledger, and a book kept on this phone. Books' Add a folder lands each /// book here, as Add files does. pub(crate) fn capture_args(client: &crate::shell::client::ClientController, args: &mut CaptureMediaArgs) -> Result { if let Some(book) = args.book.as_mut() { book.zone = client .time_zone() .map(str::to_string) .ok_or_else(|| MethodError::new("bad_request", "this phone named no time zone, so a book's day added cannot be said"))?; } let layout = client.layout().clone(); let device_key = client.self_device_id(); let answer = client .write_rows("capture.media", &mut |ctx| { write_media(ctx, &layout, args, device_key.as_deref()) }) .map_err(|reason| MethodError::new("capture_refused", reason))?; // A book this phone brought in is kept on it: its reader opens the bytes // here, signed in or not, and never asks the object for them. if args.kind == MediaKind::Book { let key = answer["answer"]["key"].as_str().ok_or_else(|| MethodError::new("capture_refused", "a book's capture answers its key"))?; super::books::keep_here(client, key)?; } Ok(crate::authoring::own_answer(answer)) } /// The whole act, so a test can drive it over a `Ctx` and a temp layout. /// /// ORDER MATTERS. Request refusals happen in `validate_capture`, /// BEFORE a byte moves — the kind, the ceiling and the content type are all /// answered off `std::fs::metadata` and the kind's own `media_limits`, so a /// capture that is going to be refused leaves nothing behind in the store. /// Then the bytes land, because a row pointing at a key whose bytes were never /// copied is a record the person can open and find empty. The ledger row goes /// last, because it is what makes the upload happen and there is nothing to /// upload until the other two are true. An existing document with an invalid /// key is refused after the local copy, without changing its row or ledger. pub fn write_media( ctx: &mut Ctx<'_>, layout: &Layout, args: &CaptureMediaArgs, device_key: Option<&str>, ) -> Result { let workspace_id = ctx.workspace_id.to_string(); let file_id = ctx.file.id(); // A book's extension is its format, whatever its file was called. let ext = match args.book.as_ref() { Some(book) => book.format.clone(), None => extension_of(args.filename.as_deref(), &args.path), }; // 1. THE BYTES. Content-addressed, so a file picked twice is copied once. let stored = put_media_file(layout, &workspace_id, &args.path, &ext).map_err(|error| { io_refusal( "the file could not be copied into this device's store", &args.path, &error, ) })?; let existing_book = if args.kind == MediaKind::Book { book_with_file(ctx, &book_key(file_id, &stored.sha256, &ext))? } else { None }; let existing_document = if args.kind == MediaKind::Document { document_with_bytes(ctx, &stored.sha256).map_err(|error| error.to_string())? } else { None }; let content_type = match existing_document.as_ref() { Some(row) => text(row, "mime").ok_or("the existing document has no content type")?, None => args.mime.clone(), }; // 2. THE KEY, from `cotton_core::media::keys` and nowhere else. let (key, record_id, table, after) = match args.kind { MediaKind::Photo => ( photo_key(file_id, &stored.sha256, &ext), format!("photo:{}", stored.sha256), "cotton_photos", None, ), MediaKind::Video => ( video_key(file_id, &stored.sha256, &ext), format!("video:{}", stored.sha256), "cotton_videos", None, ), MediaKind::Document => { let (id, key, after) = if let Some(row) = existing_document.as_ref() { let id = text(row, "id").ok_or("the existing document has no id")?; let key = text(row, "storage_path") .filter(|key| !key.is_empty()) .ok_or("the existing document has no original file key")?; let after = (text(row, "status").as_deref() == Some("processing")) .then_some(MediaAfter::DocumentProcess); (id, key, after) } else { let id = new_document_id(ctx, &stored.sha256).map_err(|error| error.to_string())?; let key = document_original_key(file_id, &id, &ext); (id, key, Some(MediaAfter::DocumentProcess)) }; (key, id, "cotton_documents", after) } // The row is made below, by the records' own producer path: its id is // the one that path mints, or the book already holding these bytes. MediaKind::Book => ( book_key(file_id, &stored.sha256, &ext), existing_book.clone().unwrap_or_default(), BOOK_TABLE, None, ), // UNREACHABLE, and it stays a refusal rather than a panic. // `validate_capture` is the ONE gate on which kinds this method // captures, and it refuses the other six BEFORE any bytes are copied — // which is the whole point of it living there. A caller that reached // `write_media` directly with one of them gets the same sentence and // still writes nothing. other => { return Err(format!( "`{other}` is not a kind of file this method captures: it belongs to a record \ something else writes first, and this method mints its own" )) } }; // THE DERIVED KEYS, from the same module and off the ORIGINAL's digest — // never the rendition's. Whoever wants a tile has to be able to NAME it // before anyone has encoded it, which is the same trick `video_poster_key` // has always played, and it is why none of these is a column. // // Computed for every kind and used only where a tier was sent: a document // reaches neither branch, because `validate_tiers` refused its arguments // before a byte moved. let (thumb_key, display_key, poster_key) = match args.kind { MediaKind::Video => ( video_thumb_key(file_id, &stored.sha256), video_display_key(file_id, &stored.sha256), video_poster_key(file_id, &stored.sha256), ), _ => ( photo_thumb_key(file_id, &stored.sha256), photo_display_key(file_id, &stored.sha256), String::new(), ), }; // The wall, asked of the key rather than assumed from the builder that made // it: one function decides what a key means, and this is the same one the // server checks against. let read_back = media_kind_for(&key, file_id).map_err(|error| error.to_string())?; if read_back != args.kind { return Err(format!( "the key this would write reads back as {read_back}, not {}", args.kind )); } // 4. THE RECORD ROW, carrying the key. This is the synced half. let now = cotton_tools::mcp::handlers::common::now_iso(ctx); let taken_at = args.taken_at.clone().unwrap_or_else(|| now.clone()); let patch = match args.kind { MediaKind::Photo | MediaKind::Video => { let mut patch = Map::new(); patch.insert("key".to_string(), Value::from(key.clone())); patch.insert("sha256".to_string(), Value::from(stored.sha256.clone())); patch.insert("content_type".to_string(), Value::from(args.mime.clone())); patch.insert( "size_bytes".to_string(), Value::from(size_i64(stored.size_bytes)), ); patch.insert("taken_at".to_string(), Value::from(taken_at)); patch.insert( "original_filename".to_string(), args.filename.clone().map_or(Value::Null, Value::from), ); // THE BLUR IS A COLUMN, so it travels in the ordinary fold with the // row it belongs to — which is the whole reason a tile has // something to draw on a phone that has never held these bytes. // Null when the phone could not make one, and null is a real state: // the Mac's backlog worker fills it later, or it stays null for // ever for a format ImageIO cannot decode, and the tile draws a // glyph. patch.insert( "preview".to_string(), args.tiers .preview .clone() .map_or(Value::Null, Value::from), ); if args.kind == MediaKind::Video { // A film with no poster is a grey glyph in every grid, and the // describe worker skips it. The key is DERIVED from the film's // own digest, so it is nameable before anyone has encoded it. patch.insert( "poster_key".to_string(), args.tiers .poster .as_ref() .map_or(Value::Null, |_| Value::from(poster_key.clone())), ); } patch } MediaKind::Document => { let mut patch = Map::new(); patch.insert( "original_name".to_string(), Value::from( args.filename .clone() .unwrap_or_else(|| stored.sha256.clone()), ), ); patch.insert("mime".to_string(), Value::from(args.mime.clone())); patch.insert( "byte_size".to_string(), Value::from(size_i64(stored.size_bytes)), ); patch.insert("sha256".to_string(), Value::from(stored.sha256.clone())); patch.insert("storage_path".to_string(), Value::from(key.clone())); // `processing`, because that is what it is: the bytes have not gone // up and the pipeline has not run. A row that claimed `ready` would // be a document the person could open and find nothing in. patch.insert("status".to_string(), Value::from("processing")); patch.insert("status_changed_at".to_string(), Value::from(now.clone())); // `app`, never `agent`: this IS the app. patch.insert("source".to_string(), Value::from("app")); patch } // A book's row is its facts and its file (`book_row`). // Unreachable: every other kind returned above. _ => Map::new(), }; let mut record_id = record_id; let mut cover_key = Value::Null; if args.kind == MediaKind::Book { let book = args.book.as_ref().ok_or("a book capture carries what its file says")?; match (existing_book.as_deref(), book.into.as_deref()) { (Some(held), Some(into)) if held != into => { return Err("this file is another book's already: the same file is one book".to_string()); } (Some(_), _) => {} (None, into) => { // A book given its file keeps the cover it has. let wants_cover = match into { Some(into) => cotton_tools::mcp::handlers::tables::get_record_by_table(ctx, json!({"table": BOOK_TABLE, "id": into}).as_object().expect("an object")) .map(|held| held["data"]["cover"].as_str().is_none_or(str::is_empty)) .unwrap_or(false), None => true, }; let cover = match book.cover.as_ref().filter(|_| wants_cover) { Some(path) => Some(keep_cover(ctx, layout, &workspace_id, path, &now)?), None => None, }; cover_key = cover.clone().map_or(Value::Null, Value::from); record_id = match into { Some(into) => attach_file(ctx, into, book, &key, cover)?, None => make_book(ctx, book, &key, cover)?, }; } } } else if cotton_store::erase::is_gone(ctx.db(), table, &record_id) .map_err(|error| error.to_string())? { return Err( "this picture was removed from Cotton for good, so it is not added again".to_string(), ); } if args.kind == MediaKind::Book { // Made above, or already held. } else if let Some(row) = existing_document.as_ref() { // Preserve the original metadata and key. Re-filing a binned document // restores it through the same route as MCP intake. out_of_the_bin_again(ctx, row).map_err(|error| error.to_string())?; } else { insert_row(ctx, table, &record_id, patch).map_err(|failure| failure.to_string())?; } // 5. THE LEDGER. Device-local, never synced, and the reason no screen waits // on an upload: the sync loop's drain claims this row, uploads with // backoff, and runs the trigger — which only ever SHORTENS the wait, since // the server's workers sweep anyway. // A COPY OF A PHOTOS ORIGINAL is not this phone's capture for good: Photos // keeps the original, and once the object holds it too the copy here // leaves (KEEP 1e). Its rule is written in this same transaction, so the // drain never sees the row without it. let from_photos = args.upload.source.is_some(); let fresh_original = media_by_key(ctx.db(), &key).map_err(|error| error.to_string())?.is_none(); enqueue_media( ctx.db(), &MediaEnqueueInput { key: key.clone(), workspace_id: workspace_id.clone(), sha256: stored.sha256.clone(), content_type, size_bytes: size_i64(stored.size_bytes), local_path: Some(stored.path.to_string_lossy().to_string()), state: None, after: after.map(|trigger| trigger.as_str().to_string()), after_row_id: after.map(|_| record_id.clone()), tier: Some(HoldTier::Original), // THE ONE PLACE THIS IS EVER TRUE. `captured_here` is what makes // these bytes permanent on this phone: the budgeted cache may drop // a picture this device merely looked at, and may never drop one it // took. Every other writer of `_media` — the hydrate, the thumb // sweep, an import — leaves it false, because none of them is the // camera. captured_here: !from_photos, now: now.clone(), }, ) .map_err(|error| error.to_string())?; let upload = &args.upload; cotton_store::media_ledger::rule_media(ctx.db(), &key, upload.network.as_deref(), upload.asked_by.as_deref(), upload.source.as_deref(), fresh_original, &now) .map_err(|error| error.to_string())?; // 6. THE RENDITIONS, each its own object with its own ledger row, so the // drain uploads them exactly the way it uploads everything else. A tier is // not a special kind of upload; it is a file. // // A film's POSTER is enqueued at `original`, not at a tier of its own: it // is the still's own bytes under its own key, and the film's thumbnail and // display rendition are derived FROM it (which is why a film costs one // decode). Its `_media` row carries `captured_here: false` — this phone // made it, but the fence that protects a capture for ever is about the // bytes a person cannot get back, and a poster can always be cut again // from the film beside it. let derived: [(&Option, &str, HoldTier); 3] = [ (&args.tiers.thumb, thumb_key.as_str(), HoldTier::Thumb), (&args.tiers.display, display_key.as_str(), HoldTier::Display), (&args.tiers.poster, poster_key.as_str(), HoldTier::Original), ]; for (source, tier_key, tier) in derived { let Some(source) = source.as_ref() else { continue; }; // Content-addressed like everything else in the store, so two pictures // that happen to reduce to the same 256 px JPEG share one file on disk // under two keys. That is the store's own rule and not a new one. let fresh_rendition = media_by_key(ctx.db(), tier_key).map_err(|error| error.to_string())?.is_none(); let rendition = put_media_file(layout, &workspace_id, source, "jpg").map_err(|error| { io_refusal( "the rendition could not be copied into this device's store", source, &error, ) })?; enqueue_media( ctx.db(), &MediaEnqueueInput { key: tier_key.to_string(), workspace_id: workspace_id.clone(), sha256: rendition.sha256.clone(), // Every rendition this method writes is a JPEG, which is what // `MediaTiers` encodes and what `PHOTO_TYPES` and `VIDEO_TYPES` // both already accept — so the server will take these keys with // no change at all. content_type: "image/jpeg".to_string(), size_bytes: size_i64(rendition.size_bytes), local_path: Some(rendition.path.to_string_lossy().to_string()), state: None, after: None, after_row_id: None, tier: Some(tier), captured_here: false, now: now.clone(), }, ) .map_err(|error| error.to_string())?; // The renditions go by the original's rule and stay on this phone: // they are what a grid draws, so they carry no source. cotton_store::media_ledger::rule_media(ctx.db(), tier_key, upload.network.as_deref(), upload.asked_by.as_deref(), None, fresh_rendition, &now) .map_err(|error| error.to_string())?; } // 7. THE HOLD, for the ORIGINAL and nothing else. // // The table's question is "who can give me these bytes", and it is only // ever asked about an original: a thumbnail is "everybody, eventually", // answered locally off `_media`, and a row per thumbnail would triple the // table for an answer nobody reads. This is the row that later lets a Mac // know there is a second copy to pull — and the row a phone checks before // it ever deletes anything. // // Under this device's KEY — the id every reader of the ledger joins on — // never the replica's author id. A phone whose row has not reached this // copy never gets here: its write is refused before the body runs // (`authoring::owner_actor`), so the refusing arm below is the revoked // and no-key cases `holder_in` still names. let holder = cotton_client::media::holds::holder_in(ctx.db(), &workspace_id, device_key)?; match holder { Ok(device_id) => { let now_ms = cotton_tools::mcp::handlers::common::now_ms(ctx); // The holding's op ids from the context's own random, and the // holding this write really has: a phone's copy is a replica (the // store queues the hold for the serving Mac); the Mac's window // writing through its served file is `Served` (nothing queued). // A context that does not say is refused rather than guessed. let held = match ctx.services.this_file.as_ref().map(|file| file.held) { Some(cotton_tools::rails::FileHeld::Replica) => cotton_store::mint::Held::Replica, Some(cotton_tools::rails::FileHeld::Served) => cotton_store::mint::Held::Served, None => { return Err("this capture does not say how the file is held, so its hold \ cannot be written" .to_string(), ) } }; let random = std::sync::Arc::clone(&ctx.random); let mut ids = cotton_store::protocol::ulid::Monotonic::new(move |out: &mut [u8]| { random.fill(out); }); record_holding( ctx.db(), &workspace_id, &device_id, &key, HoldTier::Original, size_i64(stored.size_bytes), now_ms, &mut ids, held, ) .map_err(|error| error.to_string())?; } Err(sentence) => { tracing::warn!("capture.media: {key} is here and its hold waits — {sentence}") } } // A film's POSTER KEY rides the answer beside the film's own, so the tile // that stages the clip draws a frame rather than the film's key, which no // image decoder reads. Null for a photo, a document, and a film sent with // no still: a key naming an object nobody wrote would be a broken tile. let answered_poster = if args.kind == MediaKind::Video && args.tiers.poster.is_some() { Value::from(poster_key) } else { Value::Null }; let mut answer = json!({ "key": key, "recordId": record_id, "posterKey": answered_poster }); if args.kind == MediaKind::Book { answer["table"] = Value::from(BOOK_TABLE); answer["coverKey"] = cover_key; answer["existing"] = Value::from(existing_book.is_some()); } Ok(answer) } /// The books kit's table (`kits/personal/tables/book.json`). pub const BOOK_TABLE: &str = "book"; /// The live book whose file is `key`, when this file holds one: the same EPUB /// or PDF shared again is that book, never a second. fn book_with_file(ctx: &Ctx<'_>, key: &str) -> Result, String> { use cotton_tools::mcp::handlers::tables::made_table; let table = made_table(BOOK_TABLE); let held = ctx .db() .get("SELECT 1 AS found FROM sqlite_master WHERE type = 'table' AND name = ?", &[rusqlite::types::Value::Text(table.clone())]) .map_err(|error| error.to_string())? .is_some(); if !held { return Err("this database holds no books: the books kit's table has not reached this phone".to_string()); } let row = ctx .db() .get( &format!("SELECT id FROM {table} WHERE workspace_id = ? AND deleted_at IS NULL AND file = ? LIMIT 1"), &[rusqlite::types::Value::Text(ctx.workspace_id.to_string()), rusqlite::types::Value::Text(key.to_string())], ) .map_err(|error| error.to_string())?; Ok(row.and_then(|row| row.text("id").map(str::to_string))) } /// The cover's bytes into the store under a picture key (`/photos/.`), /// queued up like any picture; no Photos row names it, the book does. fn keep_cover(ctx: &mut Ctx<'_>, layout: &Layout, workspace_id: &str, path: &Path, now: &str) -> Result { keep_picture(ctx, layout, workspace_id, path, now, "a book's cover") } /// A picture cut from a file beside it (a book's cover, an album's), into the /// store under a picture key and queued up; no Photos row names it. pub(crate) fn keep_picture(ctx: &mut Ctx<'_>, layout: &Layout, workspace_id: &str, path: &Path, now: &str, what: &str) -> Result { let ext = path.extension().and_then(std::ffi::OsStr::to_str).map(str::to_lowercase).unwrap_or_default(); let ext = if ext == "jpeg" { "jpg".to_string() } else { ext }; let content_type = cover_type(&ext).ok_or_else(|| format!("{what} is a .jpg, .png, .gif or .webp"))?; let stored = put_media_file(layout, workspace_id, path, &ext) .map_err(|error| io_refusal(format!("{what} could not be copied into this device's store"), path, &error))?; let key = photo_key(ctx.file.id(), &stored.sha256, &ext); enqueue_media( ctx.db(), &MediaEnqueueInput { key: key.clone(), workspace_id: workspace_id.to_string(), sha256: stored.sha256.clone(), content_type: content_type.to_string(), size_bytes: size_i64(stored.size_bytes), local_path: Some(stored.path.to_string_lossy().to_string()), state: None, after: None, after_row_id: None, tier: Some(HoldTier::Original), // Cut from the book beside it, so it can always be cut again. captured_here: false, now: now.to_string(), }, ) .map_err(|error| error.to_string())?; Ok(key) } /// A book's Add file: the book `into` given its file and format, and what /// the file says filling only the columns it holds nothing in; a book that /// has a file already is refused. Answers its id. fn attach_file(ctx: &mut Ctx<'_>, into: &str, book: &CaptureBook, key: &str, cover: Option) -> Result { let held = cotton_tools::mcp::handlers::tables::get_record_by_table(ctx, json!({"table": BOOK_TABLE, "id": into}).as_object().expect("an object")) .map_err(|_| "that book is no longer here".to_string())?; let data = &held["data"]; let empty = |column: &str| matches!(data.get(column), None | Some(Value::Null)) || data[column].as_str() == Some(""); if !empty("file") { return Err("that book has its file already".to_string()); } let mut patch = Map::new(); patch.insert("file".to_string(), Value::from(key.to_string())); patch.insert("format".to_string(), Value::from(book.format.clone())); let mut filled = Vec::new(); for (column, value) in &book.columns { if empty(column) { patch.insert(column.clone(), value.clone()); filled.push(column.as_str()); } } if let (Some(from), false) = (book.columns_from, filled.is_empty()) { patch.insert("filled_from".to_string(), Value::from(stamped(data.get("filled_from").and_then(Value::as_str), filled, from))); } if let (Some(pages), true) = (book.pages, empty("pages")) { patch.insert("pages".to_string(), Value::from(pages)); } if let (Some(cover), true) = (cover, empty("cover")) { patch.insert("cover".to_string(), Value::from(cover)); } let args = json!({ "table": BOOK_TABLE, "id": into, "patch": Value::Object(patch) }); cotton_tools::mcp::handlers::tables::update_produced_record(ctx, args.as_object().expect("an object")).map_err(|failure| failure.to_string())?; Ok(into.to_string()) } /// The book row, made by the records' producer path (its file, format and /// source are read only to a person, never to the capture that is their /// source); answers its id. fn make_book(ctx: &mut Ctx<'_>, book: &CaptureBook, key: &str, cover: Option) -> Result { let mut data = Map::new(); data.insert("title".to_string(), Value::from(book.title.clone())); for (column, value) in &book.columns { data.insert(column.clone(), value.clone()); } if let (Some(from), false) = (book.columns_from, book.columns.is_empty()) { data.insert("filled_from".to_string(), Value::from(stamped(None, book.columns.keys().map(String::as_str), from))); } if let Some(pages) = book.pages { data.insert("pages".to_string(), Value::from(pages)); } if let Some(cover) = cover { data.insert("cover".to_string(), Value::from(cover)); } data.insert("file".to_string(), Value::from(key.to_string())); data.insert("format".to_string(), Value::from(book.format.clone())); data.insert("source".to_string(), Value::from("file")); data.insert("status".to_string(), Value::from("want_to_read")); let now_ms = cotton_tools::mcp::handlers::common::now_ms(ctx); let today = cotton_tools::mcp::handlers::common::today_in(&book.zone, now_ms).map_err(|failure| failure.to_string())?; data.insert("added_on".to_string(), Value::from(today)); let args = json!({ "table": BOOK_TABLE, "data": Value::Object(data) }); let made = cotton_tools::mcp::handlers::tables::create_produced_record(ctx, args.as_object().expect("an object")) .map_err(|failure| failure.to_string())?; made.pointer("/record/id") .and_then(Value::as_str) .map(str::to_string) .ok_or_else(|| "the book was made and named no id".to_string()) } // ── capture.avatar ────────────────────────────────────────────────────────── /// The photograph of somebody already in the file. /// /// **Why this is not a `kind` on `capture.media`.** That method's refusal says /// what the difference is, and it is true: an avatar "belongs to a record /// something else writes first, and this method mints its own". A person is /// that record. So the shape is an owning id, the bytes and the ledger — the /// shape `capture.messageMedia` had until the sharing data plane took it in /// 5m — with one addition it did not need: the row it belongs to is UPDATED to /// carry the key, because a person's photograph that nothing points at is /// bytes on a disk. #[derive(Debug)] pub struct CaptureAvatarArgs { /// Whose face this is. Proved to exist in THIS workspace before a byte /// moves — the key is built out of the id, and a key naming a person the /// file does not have is an object no screen will ever draw. pub person_id: String, /// Where the bytes are NOW — the app's own square, already cropped and /// re-encoded. Copied into the store, never referenced in place. pub path: PathBuf, pub mime: String, pub filename: Option, /// The photo this print was cut from (B7: the Mac cuts a person's print /// from the original in Photos). Written to `avatar_photo_id` in the same /// write; absent clears it, because a picture picked by hand came from /// nowhere Cotton can open. pub photo_id: Option, } pub fn validate_avatar(request: &Value) -> Result { if request.get("bytes").is_some() { // The same refusal the other two captures make, for the same reason. return Err(MethodError::new( "bad_request", "bytes never cross this boundary — write the file to disk and pass its `path`", )); } let person_id = request .get("personId") .and_then(Value::as_str) .map(str::trim) .filter(|person| !person.is_empty()) .ok_or_else(|| { MethodError::new("bad_request", "`personId` is whose photograph this is") })?; let path = request .get("path") .and_then(Value::as_str) .map(str::trim) .filter(|path| !path.is_empty()) .ok_or_else(|| MethodError::new("bad_request", "`path` is where the bytes are now"))?; let mime = request .get("mime") .and_then(Value::as_str) .map(str::trim) .filter(|mime| !mime.is_empty()) .ok_or_else(|| MethodError::new("bad_request", "`mime` is what kind of file this is"))? .to_ascii_lowercase(); // EVERY REFUSAL BEFORE THE COPY — `write_media`'s own hard-won order. Both // limits are read from the kind's declaration rather than from numbers // written here, and both are what the server would refuse when the upload // URL is minted. let limit = media_limits(MediaKind::Avatar); if !limit.content_types.contains(&mime.as_str()) { return Err(MethodError::new( "bad_request", format!( "the server will not take a photograph of type `{mime}` — it accepts {}", limit.content_types.join(", ") ), )); } let size_bytes = std::fs::metadata(path) .map_err(|error| { MethodError::new( "bad_request", format!("there is no file at `{path}` to capture: {error}"), ) })? .len(); if size_bytes > limit.max_bytes { return Err(MethodError::new( "too_large", format!( "this photograph is {size_bytes} bytes, over the {} the server will accept for one", limit.max_bytes ), )); } Ok(CaptureAvatarArgs { person_id: person_id.to_string(), path: PathBuf::from(path), mime, filename: request .get("filename") .and_then(Value::as_str) .map(str::trim) .filter(|name| !name.is_empty()) .map(str::to_string), photo_id: request .get("photoId") .and_then(Value::as_str) .map(str::trim) .filter(|id| !id.is_empty()) .map(str::to_string), }) } /// `capture.avatar` — the person, the bytes, the row, the ledger. pub fn capture_avatar(handle: &CottonHandle, request: &Value) -> Result { let args = validate_avatar(request)?; let client = handle.client(); let layout = client.layout().clone(); let answer = client .write_rows("capture.avatar", &mut |ctx| { write_avatar(ctx, &layout, &args) }) .map_err(|reason| MethodError::new("capture_refused", reason))?; Ok(crate::authoring::own_answer(answer)) } /// The act, so a test can drive it over a `Ctx` and a temp layout. /// /// ORDER. The person FIRST, because the key is built out of their id. Then the /// bytes, because a row pointing at a key whose bytes were never copied is a /// face the person can open and find empty. Then the row, because the key is /// what makes the photograph theirs. The ledger LAST, because it is what makes /// the upload happen and there is nothing to upload until the rest is true. /// /// **The old key is not deleted.** An avatar key carries the sha, so choosing a /// new photograph writes a new object and leaves the old one for the sweep — /// which is the same arrangement every other kind of byte in this file has, and /// the reason a photograph can be changed on a train. pub fn write_avatar( ctx: &mut Ctx<'_>, layout: &Layout, args: &CaptureAvatarArgs, ) -> Result { let workspace_id = ctx.workspace_id.to_string(); let file_id = ctx.file.id(); // 1. THE PERSON. One answer for "absent" and "not this workspace" — the // probe-resistance rule the rest of this file follows. let person = ctx .db() .get( "SELECT id FROM cotton_people WHERE workspace_id = ? AND id = ?", &[ rusqlite::types::Value::Text(workspace_id.clone()), rusqlite::types::Value::Text(args.person_id.clone()), ], ) .map_err(|error| error.to_string())? .ok_or_else(|| "no such person in this workspace".to_string())?; let person_id = person.text("id").unwrap_or(&args.person_id).to_string(); // 1b. THE PHOTO the print was cut from, when it was — the same answer for // absent and another workspace's. Checked before a byte moves. if let Some(photo_id) = &args.photo_id { ctx.db() .get( "SELECT id FROM cotton_photos WHERE workspace_id = ? AND id = ?", &[ rusqlite::types::Value::Text(workspace_id.clone()), rusqlite::types::Value::Text(photo_id.clone()), ], ) .map_err(|error| error.to_string())? .ok_or_else(|| "no such photo in this workspace".to_string())?; } // 2. THE BYTES. Content-addressed, so the same face picked twice is copied // once and keyed once. let ext = extension_of(args.filename.as_deref(), &args.path); let stored = put_media_file(layout, &workspace_id, &args.path, &ext).map_err(|error| { io_refusal("the file could not be copied into this device's store", &args.path, &error) })?; // 3. THE KEY, from `cotton_core::media::keys` and nowhere else — and read // BACK through the one function that decides what a key means, which is // the same one the server checks it against. let key = avatar_key(file_id, &person_id, &stored.sha256, &ext); let read_back = media_kind_for(&key, file_id).map_err(|error| error.to_string())?; if read_back != MediaKind::Avatar { return Err(format!( "the key this would write reads back as {read_back}, not a photograph" )); } // A serving Mac has no replica drain. Publish into the same ObjectStore // its phones read BEFORE pointing the person at this key; a refused copy // leaves the person and ledger unchanged. Replicas keep their upload queue. let published = { { false } }; // 4. Point the person at their media-store object. let mut patch = Map::new(); patch.insert("avatar_key".to_string(), Value::from(key.clone())); patch.insert( "avatar_photo_id".to_string(), args.photo_id.clone().map_or(Value::Null, Value::from), ); update_row(ctx, "cotton_people", &person_id, patch).map_err(|failure| failure.to_string())?; // 5. THE LEDGER. No trigger: nothing on the server runs off an avatar // arriving, and a `after` naming a worker that does not exist is a queue // entry nobody drains. let now = cotton_tools::mcp::handlers::common::now_iso(ctx); enqueue_media( ctx.db(), &MediaEnqueueInput { key: key.clone(), workspace_id, sha256: stored.sha256.clone(), content_type: args.mime.clone(), size_bytes: size_i64(stored.size_bytes), local_path: Some(stored.path.to_string_lossy().to_string()), state: None, after: None, after_row_id: None, now: now.clone(), tier: None, captured_here: false, }, ) .map_err(|error| error.to_string())?; if published { // Re-enqueue preserves an existing pending/backoff row. Publication is // what proves it synced, for a new capture and a retry of the same key. cotton_store::media_ledger::mark_media_synced(ctx.db(), &key, &now) .map_err(|error| error.to_string())?; } Ok(json!({ "key": key, "personId": person_id })) } // ── media.ensure and read.mediaPath ───────────────────────────────────────── /// Where these bytes are on this device, if they are. /// /// `ensureLocal`'s first half, and the whole of `read.mediaPath`. The ledger is /// asked first because it is the one place that knows where a file was PUT; the /// path is then checked on disk, because a ledger row that names a file the OS /// has since evicted is a row, not a file. pub fn local_path_of(db: &cotton_store::driver::Driver, key: &str) -> Option { let row = media_by_key(db, key).ok().flatten()?; let path = PathBuf::from(row.local_path?); path.exists().then_some(path) } /// What a caller wants back from `read.mediaPath`. /// /// A TIER rather than a second read name, because it is the same question /// asked about the same key and the answer is the same shape. The default is /// [`Tier::Best`] — the tile's own resolve order — so every renderer in the app /// gets the thumbnail without saying anything; a HERO says `largest`; and the /// film page, which needs the captured bytes and nothing that stands in for /// them, says `original`. /// /// **Three words, declared here and nowhere else.** The Swift side spells the /// two non-default ones at exactly two call sites, and `ThumbFetchSweepTests` /// holds every other renderer to asking with the key alone. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Tier { /// The thumbnail if this device has it, else the bytes the key names. /// A GRID's order: the cheapest decode that fills a tile. Best, /// The biggest copy this device holds: the original, else the 1600 px /// display rendition, else the thumbnail. A DETAIL VIEW's order — a /// full-width print asked with `best` was handed the 256 px thumbnail /// enlarged to the screen while the original sat on disk beside it. Largest, /// The bytes the key names, and nothing else — never a rendition. /// /// The FILM PAGE's word: a film's key resolves under `best` to its /// `.t256.jpg`, so a player that asked without saying was handed a JPEG /// path as `.ready` and never fetched the film. Original, } fn tier_arg(args: &Map) -> Result { match args.get("tier").and_then(Value::as_str).map(str::trim) { None | Some("") | Some("best") => Ok(Tier::Best), Some("largest") => Ok(Tier::Largest), Some("original") => Ok(Tier::Original), Some(other) => Err(format!( "`tier` is `best`, `largest` or `original`, not `{other}`" )), } } /// The `data` event the shell sends when BYTES moved on this device. /// /// The SAME shape a pull carries (`shell/client.rs`, `origin: "pull"`) so the /// Swift side maps it through the one `InvalidationMap` entry for `_media` and /// nothing new has to be decoded: the origin is the one word that says no row /// changed, a file did. `moved` rides along for a log line. pub fn media_moved_event(workspace_id: &str, moved: cotton_client::media::MediaMoved) -> Value { json!({ "workspaceId": workspace_id, "tables": ["_media"], "origin": MEDIA_EVENT_ORIGIN, "moved": moved, }) } /// The origin word on a `_media` data event whose cause is LOCAL bytes. pub const MEDIA_EVENT_ORIGIN: &str = "media"; /// `read.mediaPath` — the path if the bytes are here, and never a fetch. /// /// Separate from `media.ensure` on purpose: a grid drawing two hundred /// thumbnails asks this one, and a read that could start two hundred downloads /// would be a screen that opens the radio. The renderer asks for what is here; /// the person tapping a picture is what asks for the rest. /// /// ## The tile's resolve order lives HERE, not in Swift /// /// **Thumbnail → original → nothing.** A photo or a film key gets its 256 px /// thumbnail first: the eager sweep /// (`cotton_client::media::thumbs`) collects one for every picture this device /// knows about, so on an ordinary phone it is the answer nearly every time, and /// it costs a tenth of the decode a 4 MB HEIC does at 120 points. The original /// is the fallback for a picture whose thumbnail has not been made or has not /// arrived; `present: false` is the third state, and it is what hands the tile /// over to the row's own blur and then to a glyph. **None of the three is a /// spinner**, and none of them fetches. /// /// The order is decided here rather than in each renderer because there are /// four of them and they would eventually disagree — and because a renderer /// asking twice would be two boundary crossings per tile on a scrolling grid. /// /// ## `largest` is the other order, for a detail view /// /// **Original → display → thumbnail.** The same three files, walked from the /// top: a hero drawn at the width of the screen wants the most pixels this /// device holds and nothing here fetches for it either. `tier` in the answer /// says which rung came back, so a viewer can tell a thumbnail it is enlarging /// from the original it asked for. pub fn media_path( client: &crate::shell::client::ClientController, args: &Map, ) -> Result { let key = key_arg(args)?; let tier = tier_arg(args)?; client.with_file(|replica| { let key = object_key_of(replica.driver, &replica.identity.id().to_string(), key); let path_of = |key: &str| local_path_of(replica.driver, key); if tier == Tier::Largest { if let Some(path) = path_of(&key) { return Ok(json!({ "present": true, "path": path.to_string_lossy(), "tier": "original" })); } if let Some(display) = cotton_core::media::keys::display_key_for(&key) { if let Some(path) = path_of(&display) { return Ok(json!({ "present": true, "path": path.to_string_lossy(), "tier": "display" })); } } if let Some(thumb) = cotton_core::media::keys::thumb_key_for(&key) { if let Some(path) = path_of(&thumb) { return Ok(json!({ "present": true, "path": path.to_string_lossy(), "tier": "thumb" })); } } return Ok(json!({ "present": false })); } if tier == Tier::Best { // The key the thumbnail sits under is DERIVED from this one // (`cotton_core::media::keys`), never carried in a column: the // renditions are content-addressed off the original's digest, so the // key IS the answer and a column would be a second place for it to be // wrong. A key with no thumbnail — a document, a meeting's audio, a // thumbnail itself — answers `None` and falls straight through. if let Some(thumb) = cotton_core::media::keys::thumb_key_for(&key) { if let Some(path) = path_of(&thumb) { return Ok(json!({ "present": true, "path": path.to_string_lossy(), "tier": "thumb", })); } } } Ok(match path_of(&key) { Some(path) => json!({ "present": true, "path": path.to_string_lossy(), "tier": "original", }), None => json!({ "present": false }), }) }) } /// What `media.ensure` refuses a status's media with on a phone that never /// keeps statuses — the code `keep.open` refuses a status's row with. pub const STATUS_NOT_KEPT_CODE: &str = "not_kept"; pub const STATUS_NOT_KEPT: &str = "Statuses are not kept on this phone. They are on your Macs."; /// `media.ensure` — the path, fetching the bytes first if they are not here. pub fn ensure(handle: &CottonHandle, request: &Value) -> Result { let args = request .get("args") .and_then(Value::as_object) .cloned() .unwrap_or_else(|| match request { Value::Object(map) => map.clone(), _ => Map::new(), }); let key = key_arg(&args).map_err(|reason| MethodError::new("bad_request", reason))?; let tier = tier_arg(&args).map_err(|reason| MethodError::new("bad_request", reason))?; let client = handle.client(); let landed = land(&client, key, tier, Asker::Person)?; if let Some(workspace_id) = &landed.fetched_into { // AND THE WORD: the same `_media` data event the sweep's tick sends, so // every OTHER tile drawing this key — the grid behind the viewer, the // strip on the person's page — learns the bytes are here without being // rebuilt. One event per ensure; an ensure is one picture. handle.events().emit( crate::events::EventKind::Data, media_moved_event(workspace_id, cotton_client::media::MediaMoved { landed: 1, evicted: 0 }), ); } Ok(json!({ "path": landed.path.to_string_lossy(), "fetched": landed.fetched_into.is_some() })) } /// Who asked for bytes: a person (a tap, a picture drawn large), whose asking /// is a view the budget orders by, or the pictures sweep, which is no view. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Asker { Person, Sweep, } /// Where one key's bytes are now, and the database they were fetched into /// when they had to be fetched. pub(crate) struct Landed { pub path: PathBuf, pub fetched_into: Option, } /// `media.ensure`'s whole work for one key, with no event said: the bytes /// here, else fetched into the store and the ledger. The pictures sweep /// (`phone::media_sweep`) lands its thumbnails through this same door. pub(crate) fn land( client: &crate::shell::client::ClientController, key: String, tier: Tier, asker: Asker, ) -> Result { let asked = key.clone(); let layout = client.layout().clone(); let key = client .with_file(|replica| Ok(object_key_of(replica.driver, &replica.identity.id().to_string(), key))) .map_err(|reason| MethodError::new("unreadable", reason))?; // A view drawing ONE picture large (a card in hand, a detail view) asks // with `tier: largest` and is handed the 1600 px display rendition of a // photo or a film, which the personal object resizes from the original — // never the 4 MB HEIC itself; a key with no rendition shape is the file. let key = if tier == Tier::Largest { cotton_core::media::keys::display_key_for(&key).unwrap_or(key) } else { key }; // ONE FETCH OF A KEY AT A TIME: the kept-files sweep may be fetching it // now, and it is waited for, then looked at again, rather than streamed a // second time (`cotton_client::media::fetching`). let _turn = cotton_client::media::fetching::turn(&key); // Already here? Then nothing else happens — no request, no radio, no // second copy of bytes that are content-addressed anyway. if let Some(path) = client .with_file(|replica| Ok(local_path_of(replica.driver, &key))) .map_err(|reason| MethodError::new("unreadable", reason))? { if asker == Asker::Person { stamp_view(client, &key); } return Ok(Landed { path, fetched_into: None }); } // A STATUS IS NEVER ON A PHONE — not its row (`keep::PHONE_DEFAULTS`), not // its thumbnail (the sweep), and not its bytes: the architect's ruling of // 12 Oct 2026, "never a thumbnail, never an original". Asked of the one // judge, so a phone whose owner chose to keep statuses still opens them, // and a Mac is never refused. After the read above: bytes already here // answer until the Storage pass takes them. if let Some(device) = client.self_device_id() { let never = client .with_file(|replica| { cotton_store::keep::status_bytes_never(replica.driver, &device, &key).map_err(|error| error.to_string()) }) .map_err(|reason| MethodError::new("unreadable", reason))?; if never { return Err(MethodError::new(STATUS_NOT_KEPT_CODE, STATUS_NOT_KEPT)); } } // DEAD BYTES ARE NOT FETCHED BACK: a record erased and nothing naming its // key now (`cotton_client::media::bytes_are_dead`) — the unlink pass is // taking them off this device, and a fetch would land them again. if client .with_file(|replica| { cotton_client::media::bytes_are_dead(replica.driver, &key).map_err(|error| error.to_string()) }) .map_err(|reason| MethodError::new("unreadable", reason))? { return Err(MethodError::new( cotton_core::media::keys::DEAD_KEY_REFUSAL_CODE, "This file belonged to something that was erased, so it is gone.".to_string(), )); } let workspace_id = client .with_file(|replica| Ok(replica.workspace_id.to_string())) .map_err(|reason| MethodError::new("unreadable", reason))?; // A TOOL'S PICTURE IS IN THE FILE: a package carries its pictures as // `cotton_tool_assets` rows, synced with the database, so a tool's // `photo:` is drawn from them on this device — never fetched from a // Mac, and never blank while its photo record is yet to be written (290 // walk: the Disk and Quotas tiles drew no picture). let carried = client .with_file(|replica| Ok(tool_asset_bytes(replica.driver, replica.workspace_id, &asked))) .map_err(|reason| MethodError::new("unreadable", reason))?; let landed = if let Some(bytes) = carried { store_carried(&layout, &workspace_id, &key, &bytes).map_err(NotFetched::from) } else { let Some(fetch) = client.media_fetch() else { return Err(MethodError::new("no_media_fetch", NO_MEDIA_FETCH)); }; // A KEY THE OBJECT SAID IT DOES NOT HOLD WAITS (`cotton_client::media:: // absent`): the sweep after every pass and a card's picture on every // drawing asked the same missing keys again, a 404 storm on live. The // same refusal comes back, with no request, until its wait is over. let now_ms = client.now().timestamp_millis(); if let Some((until_ms, status)) = client.absent_media().waits(&key, now_ms) { let until = chrono::DateTime::from_timestamp_millis(until_ms).map(cotton_client::seams::iso).unwrap_or_default(); let held = NotFetched { waiting: None, reason: format!("the object answered {status} when last asked; asked again from {until}"), status: Some(status) }; return Err(not_fetched(&key, &held, false)); } let fetched = fetch_into_store(fetch.as_ref(), &layout, &workspace_id, &key); match &fetched { Err(NotFetched { waiting: None, status: Some(status), .. }) if cotton_client::media::absent::is_held_answer(*status) => { client.absent_media().note(&key, *status, now_ms); } Ok(_) => client.absent_media().forget(&key), Err(_) => {} } fetched }; // THE DOWNLOAD RUNS WITH NO LOCK HELD. The writer's mutex is one file, one // connection, one writer — every write on this device queues behind it — // and a fetch is a network call of unbounded length. Holding it across one // would stop every write for as long as the radio takes. let (path, sha256, size_bytes) = landed.map_err(|trouble| not_fetched(&key, &trouble, super::sync_state::serving_away(client)))?; // ONLY the ledger write takes the writer, and it is one statement. ledger_synced(client, &key, &path, sha256, size_bytes)?; if asker == Asker::Person { stamp_view(client, &key); } Ok(Landed { path, fetched_into: Some(workspace_id) }) } /// The ledger learns bytes that came DOWN from the bucket: where they are, and /// that they are already up. fn ledger_synced( client: &crate::shell::client::ClientController, key: &str, path: &Path, sha256: String, size_bytes: u64, ) -> Result<(), MethodError> { client .with_writer(|replica| { // The ledger learns where the bytes are AND that they are already // up: a row downloaded from the bucket is by definition synced, and // leaving it `pending` would queue an upload of what is already // there. enqueue_media( replica.driver, &MediaEnqueueInput { key: key.to_string(), workspace_id: replica.workspace_id.to_string(), sha256, // The ledger wants a content type and the bytes did not come // with one this layer can trust. The generic answer is the // honest one: nothing on this device reads it back as a // claim about the file, and the record row already carries // the type the writer declared. content_type: "application/octet-stream".to_string(), size_bytes: size_i64(size_bytes), local_path: Some(path.to_string_lossy().to_string()), state: Some("synced".to_string()), after: None, after_row_id: None, now: cotton_client::seams::iso(chrono::Utc::now()), // THE TIER COMES OFF THE KEY. A fetched row that left this // NULL would be a row the budgeted cache may never reason // about (`MediaRow::tier`) — so every picture a person // opened would be held for ever and the budget would only // ever be able to take rows some other path had labelled. // `None` stays `None` for a document, a meeting's audio or // a poster, which have no tier ladder at all. tier: cotton_core::media::keys::rendition_of(key), // NOT a capture. These bytes came DOWN from the bucket; // `captured_here` is the fence for pictures this phone took // and nothing else may set it. captured_here: false, }, ) .map_err(|error| error.to_string()) }) .map_err(|reason| MethodError::new("unreadable", reason))?; Ok(()) } /// A book's, a song's or a film's file the platform downloaded itself /// (`books.here.write { from }`, a background download from the object's /// signed address): moved into the store under its digest, which must be /// `expected` — the one its key names (a book's, a song's), or the one its /// record holds where the key is no digest (a film's `whole.`) — and /// written to the ledger as already up. Answers where the bytes now are. pub(crate) fn adopt_download( client: &crate::shell::client::ClientController, key: &str, downloaded: &Path, expected: Expected, ) -> Result { let unwritable = |why: String| MethodError::new("unwritable", why); let (workspace_id, key) = client .with_file(|replica| { let workspace = replica.workspace_id.to_string(); let key = object_key_of(replica.driver, &workspace, key.to_string()); Ok((workspace, key)) }) .map_err(|reason| MethodError::new("unreadable", reason))?; let named = Path::new(&key).file_stem().and_then(|stem| stem.to_str()).unwrap_or_default().to_string(); let layout = client.layout().clone(); let folder = layout.client_media_dir().join(&workspace_id); std::fs::create_dir_all(&folder).map_err(|error| unwritable(error.to_string()))?; let scratch = cotton_client::media::fetching::partial_path(&folder, &key); // The download sits in the platform's own folder: renamed where it can be, // copied where the store is on another volume. // not a copy: media files. if std::fs::rename(downloaded, &scratch).is_err() { // not a copy: media files. std::fs::copy(downloaded, &scratch).map_err(|error| unwritable(format!("the download: {error}")))?; // not a copy: media files. let _ = std::fs::remove_file(downloaded); } // A person's own file comes down sealed (R6): opened here with its own // key before its digest is checked, so the store holds the file itself. let database = key.split('/').next().unwrap_or_default(); let files = super::personal_object::person_files_of(client, database); if files.seals(&key) && cotton_client::media::sealed::looks_sealed(&scratch).unwrap_or(false) { let fk = files.key_for_download(&key, &scratch).map_err(|refusal| { // not a copy: media files. let _ = std::fs::remove_file(&scratch); MethodError::new(if refusal.code.as_deref() == Some("seal_does_not_open") { "seal_does_not_open" } else { "seal_key_missing" }, refusal.message) })?; let opened = scratch.with_extension("opened"); cotton_client::media::sealed::open_download(&fk, &key, &scratch, &opened).map_err(|why| MethodError::new("seal_does_not_open", why))?; // not a copy: media files. std::fs::rename(&opened, &scratch).map_err(|error| unwritable(error.to_string()))?; } let (sha256, size_bytes) = sha256_file(&scratch).map_err(|error| { // not a copy: media files. let _ = std::fs::remove_file(&scratch); unwritable(error.to_string()) })?; let (wanted, refusal) = match &expected { Expected::Named => (named.as_str(), ("not_this_book", "what came down is not this book's file")), Expected::Held(digest) => (digest.as_str(), ("not_this_film", "what came down is not this film's file")), }; if sha256 != wanted { // not a copy: media files. let _ = std::fs::remove_file(&scratch); return Err(MethodError::new(refusal.0, refusal.1)); } let path = media_file_path(&layout, &workspace_id, &sha256, &extension_of(Some(&key), Path::new(&key))); if path.exists() { // not a copy: media files. let _ = std::fs::remove_file(&scratch); } else { path.parent() .map_or(Ok(()), std::fs::create_dir_all) // not a copy: media files. .and_then(|()| std::fs::rename(&scratch, &path)) .map_err(|error| { // not a copy: media files. let _ = std::fs::remove_file(&scratch); unwritable(error.to_string()) })?; } ledger_synced(client, &key, &path, sha256, size_bytes)?; Ok(path) } /// The digest a downloaded file must have ([`adopt_download`]). pub(crate) enum Expected { /// The one its key is named by: a book's or a song's. Named, /// The one its record holds: a film's or an episode's `sha256`. Held(String), } /// `media.viewed` — a detail view opened these bytes. /// /// The LRU stamp the budgeted cache orders by /// (`cotton_client::media::evict`), and the reason it is a method of its own /// rather than a side effect of a read: **the grid must never stamp it.** /// `read.mediaPath` is asked two hundred times by a scrolling finger, and a /// least-recently-viewed rule fed by that would mean "most recently scrolled /// past" — the phone would evict exactly the pictures somebody keeps opening /// and keep the ones they scrolled through once. /// /// So the two callers are the two surfaces that show an ORIGINAL: the /// full-screen photo viewer, on a tap, and the film page, which opening IS the /// asking. `media.ensure` stamps as well, because the only things that call it /// are those same surfaces and the seams behind them /// (`MediaFetchSweepTests`). /// /// Answers `viewed: false` for a key the ledger does not have, which is not an /// error: a screen may open bytes that arrived by a path with no row yet, and /// refusing would put a failure on a picture that drew perfectly well. pub fn viewed(handle: &CottonHandle, request: &Value) -> Result { let args = request .get("args") .and_then(Value::as_object) .cloned() .unwrap_or_else(|| match request { Value::Object(map) => map.clone(), _ => Map::new(), }); let key = key_arg(&args).map_err(|reason| MethodError::new("bad_request", reason))?; let stamped = handle .client() .with_writer(|replica| { mark_viewed( replica.driver, &key, &cotton_client::seams::iso(chrono::Utc::now()), ) .map_err(|error| error.to_string()) }) .map_err(|reason| MethodError::new("unreadable", reason))?; Ok(json!({ "viewed": stamped })) } /// The most keys one `media.uploads` asks about: an album of ten thousand is /// asked in pages, so one read never holds the file for long. pub const UPLOADS_MOST_KEYS: usize = 10_000; /// `media.network { path }` — the network the phone is on now: `wifi`, `mobile`, `constrained` (Low Data Mode) or /// `none` (MEDIA DRAIN 1 item 2). The shell says it at launch and on every change; a file queued for Wi-Fi only /// waits until it has said `wifi`, and goes at once when it does. Answers `{path}` as the core now holds it. pub fn network(handle: &CottonHandle, request: &Value) -> Result { let word = request .get("args") .unwrap_or(request) .get("path") .and_then(Value::as_str) .ok_or_else(|| MethodError::new("bad_request", "`path` is wifi, mobile, constrained or none"))?; let path = cotton_client::media::network::Path::parse(word) .ok_or_else(|| MethodError::new("bad_request", format!("`{word}` is no network: wifi, mobile, constrained or none")))?; if cotton_client::media::network::set(path) { handle.client().wake_media_drain(); } Ok(serde_json::json!({ "path": cotton_client::media::network::now().word() })) } /// `media.uploads { keys }` — where each of these files is on its way up /// (MEDIA DRAIN 1, item 3). /// /// Answers `{ files: [{ key, phase, sent?, total, code?, line?, attempts, /// nextTryAt?, network, askedBy? }], counts }`, the files in the order asked. /// `phase` is `queued`, `waiting` (`code`: `space_full`, `dead_key`), /// `uploading` (`sent` of `total` bytes), `retrying`, `uploaded` (the object /// answered that it holds the bytes), `failed` (`code`: `too_big`, /// `cotton_full`, `file_gone`, `refused`), `removing`, or `unknown` (no upload /// of that key on this device). Reads the ledger and the uploads in the air; /// asks the network nothing. pub fn uploads(handle: &CottonHandle, request: &Value) -> Result { let args = request .get("args") .and_then(Value::as_object) .cloned() .unwrap_or_else(|| match request { Value::Object(map) => map.clone(), _ => Map::new(), }); let keys: Vec = args .get("keys") .and_then(Value::as_array) .ok_or_else(|| MethodError::new("bad_request", "`keys` is the list of files to say about"))? .iter() .map(|key| key.as_str().map(str::to_string).ok_or_else(|| MethodError::new("bad_request", "every key is a string"))) .collect::>()?; if keys.len() > UPLOADS_MOST_KEYS { return Err(MethodError::new("bad_request", format!("at most {UPLOADS_MOST_KEYS} keys at once: ask in pages"))); } let client = handle.client(); let rows = client .with_file(|file| cotton_store::media_ledger::media_by_keys(file.driver, &keys).map_err(|error| error.to_string())) .map_err(|reason| MethodError::new("unreadable", reason))?; let answer = cotton_client::media::uploads_of(&keys, &rows, &client.upload_watch()); serde_json::to_value(answer).map_err(|error| MethodError::new("unreadable", error.to_string())) } /// The names this module claims that are NOT `media.*`. /// /// One entry, and it is the reason the list exists: `settings.mediaBudget` /// carries the `settings.` prefix and is answered HERE, so the partition guard /// (`phone::owner_tests`) has a module to point at rather than an exception to /// carry. pub const METHODS: [&str; 1] = ["settings.mediaBudget"]; /// `settings.mediaBudget` — move how much of this DEVICE the media store may /// use. /// /// A method rather than one of `settings_writes.rs`' five, and for the opposite /// of their reason: those are rows the app writes through the outbox because /// they belong to the person's life and travel with it. **A budget is about /// this machine's disk.** A phone with 64 GB and a Mac with 4 TB have no /// business agreeing on a number, so it is a file beside `connection.json` /// (`Layout::media_budget_json`), it is never an op, and no assistant can reach /// it. /// /// Refuses anything that is not one of `MEDIA_BUDGET_CHOICES` — see /// `cotton_client::media::evict::set_budget` for why a clamp would be worse /// than a refusal. pub fn set_media_budget(handle: &CottonHandle, request: &Value) -> Result { let args = request .get("args") .and_then(Value::as_object) .cloned() .unwrap_or_else(|| match request { Value::Object(map) => map.clone(), _ => Map::new(), }); let bytes = args .get("bytes") .and_then(Value::as_u64) .ok_or_else(|| MethodError::new("bad_request", "`bytes` is the budget, in bytes"))?; let client = handle.client(); let bytes = cotton_client::media::set_budget(client.layout(), bytes) .map_err(|reason| MethodError::new("bad_request", reason))?; Ok(json!({ "budgetBytes": bytes })) } /// Stamp a view from inside `media.ensure`, best effort. /// /// BEST EFFORT on purpose, and it is the one place in this module where that is /// right: the person asked for a picture and the picture is there. A ledger /// write that failed changes which file the budget takes FIRST in three weeks' /// time; turning it into a refusal would put an error over a photograph that /// opened. fn stamp_view(client: &crate::shell::client::ClientController, key: &str) { let _ = client.with_writer(|replica| { mark_viewed( replica.driver, key, &cotton_client::seams::iso(chrono::Utc::now()), ) .map_err(|error| error.to_string()) }); } /// Fetch one key into the store: scratch, hash, rename. /// /// Separated from [`ensure`] so the whole of it — the network call included — /// happens with no database lock held, and so a test can drive it against a /// fake seam without a replica at all. pub(crate) fn fetch_into_store( fetch: &dyn MediaFetch, layout: &Layout, workspace_id: &str, key: &str, ) -> Result<(PathBuf, String, u64), NotFetched> { let folder = layout.client_media_dir().join(workspace_id); std::fs::create_dir_all(&folder).map_err(|error| NotFetched::from(error.to_string()))?; // The key's ONE partial file, shared with the kept-files sweep: a fetch // cut part way keeps what arrived and the next resumes from its last // byte (`cotton_client::media::fetching`). One fetch per key at a time is // the caller's turn. let scratch = cotton_client::media::fetching::partial_path(&folder, key); if let Err(error) = fetch.fetch_to(workspace_id, key, &scratch) { if !error.keeps_partial() { // not a copy: media files. let _ = std::fs::remove_file(&scratch); } return Err(error); } store_fetched(layout, workspace_id, key, &scratch).map_err(NotFetched::from) } /// The bytes of the picture a tool package carries for `key` (`photo:`, /// its file named `.` in `cotton_tool_assets`), decoded; nil for /// any other key or a picture no package here carries. pub(crate) fn tool_asset_bytes(db: &cotton_store::driver::Driver, workspace_id: &str, key: &str) -> Option> { use base64::Engine as _; let sha = key.strip_prefix("photo:").filter(|sha| !sha.is_empty() && sha.chars().all(|c| c.is_ascii_hexdigit()))?; let row = db .get( &format!( "SELECT bytes FROM {} WHERE workspace_id = ? AND (name = ? OR name LIKE ?) LIMIT 1", cotton_tools::tool_pictures::TOOL_ASSETS ), &[ rusqlite::types::Value::Text(workspace_id.to_string()), rusqlite::types::Value::Text(sha.to_string()), rusqlite::types::Value::Text(format!("{sha}.%")), ], ) .ok() .flatten()?; let bytes = base64::engine::general_purpose::STANDARD.decode(row.text("bytes")?).ok()?; // Content-addressed: bytes that are not the picture the key names are none. use sha2::{Digest as _, Sha256}; hex::encode(Sha256::digest(&bytes)).eq_ignore_ascii_case(sha).then_some(bytes) } /// A package's carried picture into the content-addressed store, as a fetch /// lands one: written to the key's scratch file, then stored under its digest. fn store_carried(layout: &Layout, workspace_id: &str, key: &str, bytes: &[u8]) -> Result<(PathBuf, String, u64), String> { let folder = layout.client_media_dir().join(workspace_id); std::fs::create_dir_all(&folder).map_err(|error| error.to_string())?; let scratch = cotton_client::media::fetching::partial_path(&folder, key); // not a copy: media files. std::fs::write(&scratch, bytes).map_err(|error| error.to_string())?; store_fetched(layout, workspace_id, key, &scratch) } /// A written scratch file into the content-addressed store, under its digest. /// /// The file is hashed WHERE IT LIES with /// `cotton_client::media::store::sha256_file` — the store's own hasher, which /// streams in chunks, so there is one digest function on this device and /// nothing here holds the file in memory — and only then renamed into the place /// the digest names. A run killed mid-write can therefore never leave half a /// file under a name that promises a digest. /// /// The rename is skipped when the digest is already there: the same bytes /// fetched twice are one file, which is the whole meaning of a /// content-addressed store. /// /// Answers the digest as well as the path: the ledger row needs it and reading /// it back off disk would be the same work twice. fn store_fetched( layout: &Layout, workspace_id: &str, key: &str, scratch: &Path, ) -> Result<(PathBuf, String, u64), String> { let hashed = sha256_file(scratch); let (sha256, size_bytes) = match hashed { Ok(answer) => answer, Err(error) => { // not a copy: media files. let _ = std::fs::remove_file(scratch); return Err(error.to_string()); } }; let ext = extension_of(Some(key), Path::new(key)); let path = media_file_path(layout, workspace_id, &sha256, &ext); if path.exists() { // The same bytes are already here under the same digest. Drop the // scratch rather than renaming over a file something may be reading. // not a copy: media files. let _ = std::fs::remove_file(scratch); return Ok((path, sha256, size_bytes)); } let landed = path .parent() .map_or(Ok(()), std::fs::create_dir_all) // not a copy: media files. .and_then(|()| std::fs::rename(scratch, &path)); match landed { Ok(()) => Ok((path, sha256, size_bytes)), Err(error) => { // not a copy: media files. let _ = std::fs::remove_file(scratch); Err(error.to_string()) } } } /// The object key a photo RECORD's bytes sit under, for a caller that holds /// the record's id (`photo:`) — a tool's `{"photo": …}` picture, a photo /// column. The store keeps bytes by key and the row says which; anything that /// is not a photo id, or names no photo in this file, is answered as it came. pub(crate) fn object_key_of(db: &cotton_store::driver::Driver, workspace_id: &str, key: String) -> String { if !key.starts_with("photo:") { return key; } db.get( "SELECT key FROM cotton_photos WHERE workspace_id = ? AND id = ?", &[ rusqlite::types::Value::Text(workspace_id.to_string()), rusqlite::types::Value::Text(key.clone()), ], ) .ok() .flatten() .and_then(|row| row.text("key").map(str::to_string)) .unwrap_or(key) } fn key_arg(args: &Map) -> Result { args.get("key") .and_then(Value::as_str) .map(str::trim) .filter(|key| !key.is_empty()) .map(str::to_string) .ok_or_else(|| "`key` is the object key of the file".to_string()) } /// The extension, lower-cased, from the name the picker gave or from the path. /// /// Empty is a legal answer and every key builder handles it: a file with no /// extension is a file, and inventing one from the mime type would put a `.bin` /// on a key the server later reads back. fn extension_of(filename: Option<&str>, path: &Path) -> String { filename .and_then(|name| { Path::new(name) .extension() .and_then(std::ffi::OsStr::to_str) }) .or_else(|| path.extension().and_then(std::ffi::OsStr::to_str)) .map(str::to_lowercase) .unwrap_or_default() } /// A size that fits the ledger's own column. `u64` cannot exceed `i64` here — /// the ceiling check above is smaller than either — and saturating is the /// honest answer rather than a wrap. fn size_i64(size: u64) -> i64 { i64::try_from(size).unwrap_or(i64::MAX) } #[cfg(test)] mod no_mac_tests { /// A phone signed in to Cotton keeps its files in Cotton, not on a Mac: /// a fetch that failed never says a Mac keeps them (only `mac_away`, /// said when this copy names a serving Mac that is away). #[test] fn a_file_not_fetched_names_no_mac() { for status in [Some(404), Some(500), Some(0), None] { let said = super::not_fetched("k", &super::NotFetched { waiting: None, reason: String::new(), status }, false); assert!(!said.message.contains("Mac"), "{status:?}: {}", said.message); } assert!(!super::NO_MEDIA_FETCH.contains("Mac"), "{}", super::NO_MEDIA_FETCH); } }