//! A Cotton chat's files on this phone (20 Nov 2026): a //! received file opened, and every file kept past the chat store's thirty //! days. //! //! ```text //! chat.file { message, index?, dir } → { path, mime, name?, kind?, kept } (refused file_gone, file_offline) //! chat.keep { unmetered?, limit? } → { kept, left, gone } //! ``` //! //! **Where a chat's file lives.** The sender puts it in the chat store //! (R2 `chat-files/`, sealed on the phone under a key that travels inside //! the message), and the Worker sweeps it thirty days on. So the first of the //! person's phones to hold its bytes KEEPS it: it goes into the person's own //! media under the conversation's folder (`/messages//.`, //! sealed under the person's own key when the drain uploads it, as every file //! of theirs is), the message's `media` names it, and the picture's entry //! says `kept`. The sender keeps their own copy as it goes up. Every other //! phone of theirs, and a new phone signed in later, opens it from there //! (`media.ensure`'s door), not from the chat store, whenever it asks. //! //! The shell runs `chat.keep` when the app comes to the front and after a //! push lands: it fetches and keeps what no phone of the person's has kept, //! newest first, a few at a time; pictures and voice messages on any network, //! videos and other files only when `unmetered`. A file is lost only when no //! phone of the person's opened Chat for the whole thirty days after it came //! (then `chat.file` refuses `file_gone`, in the kit's words), as WhatsApp's //! undelivered media is. //! //! Nothing new is readable by the Worker: the chat store's bytes are the //! sender's sealed file, and the kept copy is sealed under the person's own //! key like every file of theirs. use serde_json::{json, Map, Value}; use cotton_core::chat::payload::Picture; use cotton_core::chat::{files, seal}; use cotton_core::messages::app::list::{self, say}; use cotton_client::transport::object::bearer; use rusqlite::types::Value as SqlValue; use super::cotton_chat::{self, meta_value, one, read, rows, write, ws, MESSAGES}; fn text(value: String) -> SqlValue { SqlValue::Text(value) } use crate::methods::MethodError; use crate::shell::client::ClientController; /// How long the chat store keeps a file (the Worker's `HELD_MS`). pub const STORE_DAYS: i64 = 30; /// Files one `chat.keep` keeps at most, unless it says. pub const KEEP_EACH: usize = 6; /// A picture's kind as the bubble draws it: these are kept on any network. fn light(picture: &Picture) -> bool { matches!(picture.kind.as_deref(), None | Some("photo") | Some("voice") | Some("image")) && !picture.mime.starts_with("video/") } /// Where `chat.file` writes a file in `dir`: under the name it was sent with /// (it travels sealed in the box), in a folder of its own named by its hash so /// two files called "scan.pdf" never meet, so the viewer the phone hands it to /// titles it by its name, not its hash (21 Nov 2026). A name /// that says nothing usable is the hash's start under the type's extension. pub(crate) fn opened_path(dir: &std::path::Path, picture: &Picture) -> std::path::PathBuf { let hash = &picture.sha256[..picture.sha256.len().min(16)]; let plain = picture.name.as_deref().map(file_name).unwrap_or_default(); let ext = extension(Some(plain.as_str()).filter(|p| !p.is_empty()), &picture.mime); let name = if plain.is_empty() { format!("{hash}.{ext}") } else if cotton_core::import::media_plan::extension_of(&plain).eq_ignore_ascii_case(&ext) { plain } else { format!("{plain}.{ext}") }; dir.join(hash).join(name) } /// A sent name made safe as one file name: its last part only, no control /// characters, no leading dots, at most 120 characters. fn file_name(name: &str) -> String { let last = name.rsplit(['/', '\\']).next().unwrap_or_default(); let clean: String = last.chars().filter(|c| !c.is_control() && !matches!(c, ':' | '*' | '?' | '"' | '<' | '>' | '|')).collect(); let clean = clean.trim().trim_start_matches('.').trim(); clean.chars().take(120).collect::().trim_end().to_string() } /// The file's extension: its own name's, else its type's, else `bin`. pub(crate) fn extension(name: Option<&str>, mime: &str) -> String { let named = name.map(cotton_core::import::media_plan::extension_of).filter(|e| !e.is_empty() && e.len() <= 8 && e.chars().all(|c| c.is_ascii_alphanumeric())); if let Some(ext) = named { return ext.to_ascii_lowercase(); } match mime { "image/png" => "png", "image/heic" => "heic", "image/gif" => "gif", "image/webp" => "webp", "image/jpeg" | "image/jpg" => "jpg", "video/mp4" => "mp4", "video/quicktime" => "mov", "video/3gpp" => "3gp", "video/webm" => "webm", "audio/mp4" | "audio/m4a" | "audio/x-m4a" | "audio/aac" => "m4a", "audio/ogg" | "audio/opus" => "ogg", "audio/mpeg" => "mp3", "application/pdf" => "pdf", "text/plain" => "txt", "application/zip" => "zip", _ => "bin", } .to_string() } fn pictures_of(meta: &Value) -> Vec { serde_json::from_value(meta["cotton"]["pictures"].clone()).unwrap_or_default() } fn lines_refusal(code: &str, line: &str) -> MethodError { MethodError::new(code, say(&list::lines(), line, &[])) } /// `chat.file`: the file a message carries, written into `dir` under its own /// extension and opened: from this phone's copy of the person's own media /// when it is kept, else from the chat store, which keeps it then. /// One attachment of a message, by the index its bubble draws it at (`chat_app::media_of`: an /// import's `media` entries first, then the Cotton message's files). pub(crate) enum Attached { /// A file the importer put in the person's own media (a WhatsApp picture): opened through /// `media::land`, as every file of theirs is. Imported(cotton_core::messages::MessageMedia), /// A Cotton message's file (`meta.cotton.pictures[n]`), in the chat store or kept. Cotton(usize, Picture), /// A file this phone is still sending (`meta.cotton.pending_pictures[n]`): the phone's own /// file, opened from here at once, never asked of anyone. Pending(std::path::PathBuf, String), } /// The message's row (`id, thread_id, media, meta`, and what says when it was written and landed), or `not_found` in its words. pub(crate) fn message_row(client: &ClientController, label: &str, message: &str) -> Result { let m = message.to_string(); let row = read(client, label, move |ctx| Ok(one(ctx, &format!("SELECT id, thread_id, media, meta, origin, channel, direction, send_state, sent_at, created_at FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(m.clone())])?.map(Value::Object).unwrap_or(Value::Null)))?; if row.is_null() { return Err(MethodError::new("not_found", "This message isn't here any more.")); } Ok(row) } /// The attachment `index` of `row`, counted as its bubble counts them. pub(crate) fn attached(row: &Value, index: usize) -> Option { let parsed = match &row["media"] { Value::String(t) => serde_json::from_str::(t).unwrap_or(Value::Null), other => other.clone(), }; let imported: Vec = parsed .as_array() .into_iter() .flatten() .filter(|entry| entry["cottonKept"] != json!(true)) .filter_map(|entry| serde_json::from_value(entry.clone()).ok()) .collect(); if let Some(media) = imported.get(index) { return Some(Attached::Imported(media.clone())); } let at = index - imported.len(); let meta = meta_value(&row["meta"]); let pictures = pictures_of(&meta); if let Some(picture) = pictures.get(at) { return Some(Attached::Cotton(at, picture.clone())); } let pending = &meta["cotton"]["pending_pictures"][at - pictures.len()]; let path = pending["path"].as_str().filter(|p| !p.is_empty())?; Some(Attached::Pending(std::path::PathBuf::from(path), pending["mime"].as_str().unwrap_or("image/jpeg").to_string())) } /// Whether a missing file of this message may be said gone yet (`files::may_be_gone`): a live /// Cotton message still going out, or written or landed here within minutes, is never gone. An /// imported message's files are the person's own media, said gone as every key of theirs is. pub(crate) fn may_be_gone(client: &ClientController, row: &Value) -> bool { if row["origin"].as_str() == Some("imported") || row["channel"].as_str().is_some_and(|c| c != cotton_core::chat::CHANNEL) { return true; } let sending = row["direction"].as_str() == Some("out") && !matches!(row["send_state"].as_str(), Some("sent" | "delivered" | "read") | None); let ms = |t: &Value| t.as_str().and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok()).map(|t| t.timestamp_millis()); let written = meta_value(&row["meta"])["cotton"]["written_at"].clone(); let at = [ms(&row["sent_at"]), ms(&row["created_at"]), ms(&written)].into_iter().flatten().max(); files::may_be_gone(sending, at, cotton_chat::now_ms(client)) } /// An imported attachment's bytes on this phone: the person's own media, fetched when not here. pub(crate) fn imported_path(client: &ClientController, media: &cotton_core::messages::MessageMedia) -> Result { super::media::land(client, media.key.clone(), super::media::Tier::Original, super::media::Asker::Person).map(|landed| landed.path) } /// A message's file opened on this phone, with how Comms' own viewer shows it (`view`: `viewer::view_of`). pub(crate) fn file(client: &ClientController, request: &Value) -> Result { let mut opened = file_opened(client, request)?; with_view(&mut opened); Ok(opened) } /// `view` beside an opened file's `mime` and `name`: pdf, text, picture or other. pub(crate) fn with_view(opened: &mut Value) { let view = cotton_core::messages::app::viewer::view_of(opened["mime"].as_str(), opened["name"].as_str().or_else(|| opened["path"].as_str())); opened["view"] = serde_json::to_value(view).unwrap_or(Value::Null); } fn file_opened(client: &ClientController, request: &Value) -> Result { let message = cotton_chat::text(request, "message")?.to_string(); let asked = request.get("index").and_then(Value::as_u64).unwrap_or(0) as usize; let dir = std::path::PathBuf::from(cotton_chat::text(request, "dir")?); let row = message_row(client, "chat.file", &message)?; let meta = meta_value(&row["meta"]); let (index, picture) = match attached(&row, asked).ok_or_else(|| MethodError::new("not_found", "This message has no such file."))? { Attached::Cotton(index, picture) => (index, picture), Attached::Pending(path, mime) => { // Still going up: the phone's own file, at once. if !path.is_file() { return Err(lines_refusal("file_offline", "app.notice.file_offline")); } return Ok(json!({ "path": path.to_string_lossy(), "mime": mime, "kept": false })); } Attached::Imported(media) => { let landed = imported_path(client, &media).map_err(|_| lines_refusal("file_offline", "app.notice.file_offline"))?; let as_picture = Picture { name: media.name.clone(), mime: media.content_type.clone(), sha256: media.key.rsplit('/').next().unwrap_or_default().split('.').next().unwrap_or_default().to_string(), ..Picture::default() }; let path = opened_path(&dir, &as_picture); std::fs::create_dir_all(path.parent().unwrap_or(&dir)).map_err(|e| MethodError::new("unwritable", e.to_string()))?; if !path.exists() { // not a copy: chat files. std::fs::copy(&landed, &path).map_err(|e| MethodError::new("unwritable", e.to_string()))?; } return Ok(json!({ "path": path.to_string_lossy(), "mime": media.content_type, "name": media.name, "kind": media.kind, "kept": true })); } }; let picture = &picture; let kept = meta["cotton"]["pictures"][index]["kept"].as_str().map(str::to_string); let path = opened_path(&dir, picture); let folder = path.parent().map(std::path::Path::to_path_buf).unwrap_or_else(|| dir.clone()); let answer = |path: &std::path::Path, kept: bool| json!({ "path": path.to_string_lossy(), "mime": picture.mime, "name": picture.name, "kind": picture.kind, "kept": kept }); if let Some(key) = &kept { // Kept: this phone's copy of the person's own media, fetched when it is not here. if let Ok(landed) = super::media::land(client, key.clone(), super::media::Tier::Original, super::media::Asker::Person) { std::fs::create_dir_all(&folder).map_err(|e| MethodError::new("unwritable", e.to_string()))?; if !path.exists() { // not a copy: chat files. std::fs::copy(&landed.path, &path).map_err(|e| MethodError::new("unwritable", e.to_string()))?; } return Ok(answer(&path, true)); } } // Within minutes of it, a file the store does not hold yet is not gone: it is asked again. let plain = fetch(client, picture).map_err(|refusal| if refusal.code == "file_gone" && !may_be_gone(client, &row) { lines_refusal("file_offline", "app.notice.file_offline") } else { refusal })?; std::fs::create_dir_all(&folder).map_err(|e| MethodError::new("unwritable", e.to_string()))?; // not a copy: chat files. std::fs::write(&path, &plain).map_err(|e| MethodError::new("unwritable", e.to_string()))?; drop(plain); let kept_now = kept.is_some() || keep(client, &message, row["thread_id"].as_str().unwrap_or_default(), index, &path, picture).is_ok(); Ok(answer(&path, kept_now)) } /// A file's bytes from the chat store, opened and checked. fn fetch(client: &ClientController, picture: &Picture) -> Result, MethodError> { let key = seal::key_from_text(&picture.key).ok_or_else(|| MethodError::new("unreadable", "the file's key is not one"))?; let door = client.object_door().ok_or_else(cotton_chat::not_connected)?; let (status, bytes) = door .address .send_bytes(door.exchange.as_ref(), "GET", &cotton_chat::routes::file(&picture.file), bearer(&door.credential), None) .map_err(|_| lines_refusal("file_offline", "app.notice.file_offline"))?; match status { 200 => files::open_file(&key, &bytes, &picture.sha256).ok_or_else(|| MethodError::new("unreadable", "The file did not open.")), 404 | 410 => Err(lines_refusal("file_gone", "app.notice.file_gone")), _ => Err(lines_refusal("file_offline", "app.notice.file_offline")), } } /// The file at `path` kept in the person's own media under its conversation, /// named by the message (`media`) and its picture (`kept`). Answers its key. pub(crate) fn keep(client: &ClientController, message: &str, thread: &str, index: usize, path: &std::path::Path, picture: &Picture) -> Result { if thread.is_empty() { return Err(MethodError::new("not_found", "This message has no conversation.")); } let layout = client.layout().clone(); let clock = client.clock(); let name = picture.name.clone().unwrap_or_else(|| format!("{}.{}", &picture.sha256[..picture.sha256.len().min(12)], extension(None, &picture.mime))); let thread_id = thread.to_string(); let outcome = client .with_writer(|replica| { let file_id = replica.identity.id().clone(); let leg = cotton_client::messages_import::media::MediaLeg { layout: &layout, file: &file_id, thread_id: &thread_id, clock: clock.as_ref() }; let media = cotton_client::messages_import::MediaFile { external_id: message.to_string(), path: path.to_path_buf(), name: Some(name.clone()), content_type: Some(picture.mime.clone()) }; let outcome = cotton_client::messages_import::media::store_one_file(&leg, replica.driver, &media); // The file as it was sent, so Free up space may take it once it is in the person's // account (`shell_settings::FREEABLE`); seen again, it lands back from there. if let cotton_client::messages_import::media::MediaOutcome::Stored { key, .. } = &outcome { replica .driver .run("UPDATE _media SET tier = 'original' WHERE key = ? AND tier IS NULL", &[SqlValue::Text(key.clone())]) .map_err(|e| e.to_string())?; } Ok(outcome) }) .map_err(|why| MethodError::new("unwritable", why))?; let cotton_client::messages_import::media::MediaOutcome::Stored { key, content_type, size_bytes, name } = outcome else { return Err(MethodError::new("not_kept", format!("{outcome:?}"))); }; let (id, k) = (message.to_string(), key.clone()); let kind = picture.kind.clone(); let (duration, width, height) = (picture.duration_ms, picture.width, picture.height); write(client, "chat.keep", move |ctx| { let Some(row) = one(ctx, &format!("SELECT media, meta FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(id.clone())])? else { return Ok(Value::Null) }; let mut meta = meta_value(row.get("meta").unwrap_or(&Value::Null)); let Some(entry) = meta["cotton"]["pictures"].get_mut(index) else { return Ok(Value::Null) }; if entry["kept"].is_string() { return Ok(Value::Null); } entry["kept"] = json!(k); let mut media: Vec = match row.get("media") { Some(Value::String(t)) => serde_json::from_str(t).unwrap_or_default(), Some(Value::Array(a)) => a.clone(), _ => Vec::new(), }; let mut said = json!({ "key": k, "contentType": content_type, "name": name, "sizeBytes": size_bytes }); if let Some(kind) = &kind { said["kind"] = json!(kind); } if let Some(ms) = duration { said["durationMs"] = json!(ms); } if let (Some(w), Some(h)) = (width, height) { said["width"] = json!(w); said["height"] = json!(h); } said["cottonKept"] = json!(true); media.push(said); let mut patch = Map::new(); patch.insert("meta".into(), meta); patch.insert("media".into(), json!(media)); cotton_tools::mcp::handlers::common::update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?; Ok(Value::Null) })?; Ok(key) } /// `chat.keep`: what no phone of the person's has kept yet, from the chat /// store's last thirty days, newest first: kept now, a few at a time. pub(crate) fn keep_pass(client: &ClientController, request: &Value) -> Result { let unmetered = request.get("unmetered").and_then(Value::as_bool).unwrap_or(false); let limit = request.get("limit").and_then(Value::as_u64).map_or(KEEP_EACH, |n| n.clamp(1, 50) as usize); let since = cotton_chat::iso(cotton_chat::now_ms(client) - STORE_DAYS * 24 * 3_600_000); let found = read(client, "chat.keep", move |ctx| { let rows = rows( ctx, &format!("SELECT id, thread_id, meta, origin, channel, direction, send_state, sent_at, created_at FROM {MESSAGES} WHERE workspace_id = ? AND channel = 'cotton' AND trashed_at IS NULL AND deleted_at IS NULL AND sent_at > ? AND meta LIKE '%\"pictures\"%' ORDER BY sent_at DESC LIMIT 400"), &[ws(ctx), text(since.clone())], )?; Ok(Value::Array(rows.into_iter().map(Value::Object).collect())) })?; let dir = client.layout().root().join("chat-keep"); let (mut kept, mut left, mut gone) = (0usize, 0usize, 0usize); for row in found.as_array().into_iter().flatten() { let meta = meta_value(&row["meta"]); for (index, picture) in pictures_of(&meta).iter().enumerate() { if meta["cotton"]["pictures"][index]["kept"].is_string() || meta["cotton"]["pictures"][index]["gone"] == json!(true) || picture.file.is_empty() { continue; } if kept >= limit || (!unmetered && !light(picture)) { left += 1; continue; } let plain = match fetch(client, picture) { Ok(plain) => plain, // Gone only once it may be: never while it is new here (`files::may_be_gone`). Err(refusal) if refusal.code == "file_gone" && may_be_gone(client, &row) => { gone += 1; mark_gone(client, row["id"].as_str().unwrap_or_default(), index)?; continue; } Err(_) => { left += 1; continue; } }; std::fs::create_dir_all(&dir).map_err(|e| MethodError::new("unwritable", e.to_string()))?; let path = dir.join(format!("{}.{}", picture.sha256, extension(picture.name.as_deref(), &picture.mime))); // not a copy: chat files. std::fs::write(&path, &plain).map_err(|e| MethodError::new("unwritable", e.to_string()))?; drop(plain); let done = keep(client, row["id"].as_str().unwrap_or_default(), row["thread_id"].as_str().unwrap_or_default(), index, &path, picture); // not a copy: chat files. let _ = std::fs::remove_file(&path); if done.is_ok() { kept += 1; } else { left += 1; } } } // Then what the object still holds plain of the kind now sealed (chat pictures kept before 22 Nov 2026, and // the Mac's WhatsApp pictures): a page sealed here and put back (phone::seal_kept). A failure there is said // and tried again next time; it never stops what was kept above. let mut answer = json!({ "kept": kept, "left": left, "gone": gone }); match super::seal_kept::carry(client, unmetered) { Ok(sealed) if sealed.sealed > 0 || sealed.left > 0 || !sealed.waiting.is_empty() => answer["sealed"] = json!({ "files": sealed.sealed, "bytes": sealed.bytes, "left": sealed.left, "done": sealed.done, "waiting": sealed.waiting }), Ok(_) => {} Err(why) => { tracing::warn!("chat.keep: the plain kept pictures were not sealed this time — {why}"); answer["sealed"] = json!({ "error": why }); } } Ok(answer) } /// A file the chat store no longer holds and no phone kept: said once, never asked again. fn mark_gone(client: &ClientController, message: &str, index: usize) -> Result<(), MethodError> { let id = message.to_string(); write(client, "chat.gone", move |ctx| { let Some(row) = one(ctx, &format!("SELECT meta FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(id.clone())])? else { return Ok(Value::Null) }; let mut meta = meta_value(row.get("meta").unwrap_or(&Value::Null)); if let Some(entry) = meta["cotton"]["pictures"].get_mut(index) { entry["gone"] = json!(true); } let mut patch = Map::new(); patch.insert("meta".into(), meta); cotton_tools::mcp::handlers::common::update_row(ctx, MESSAGES, &id, patch).map_err(|f| f.to_string())?; Ok(Value::Null) }) .map(|_| ()) } #[cfg(test)] #[path = "chat_files_tests.rs"] mod tests;