//! The Downloads chat in Comms (DLCHAT, 22 Nov 2026): a chat every signed-in //! person has, made by the core, with only the person in it. It is Cotton's, //! not a person's: no number, a small mark for its picture, never deleted, //! muted on this phone if the person likes. //! //! ```text //! chat.downloads { before? } → the page (below) //! chat.downloads.send { text } → { fetch: [id], items } | { said } //! chat.downloads.act { act, fetch? } → open | retry | mute | unmute //! chat.act { thread: "downloads", act: mute | unmute } (the list's swipe) //! ``` //! //! **Nothing in it is a message.** Each item is one `fetch` row, the queue the //! Downloads app and an assistant's `create_record` write too: the person's //! link is the row's own `source`, and Cotton's line under it is drawn from //! the row's state by `cotton_rules::downloads_chat::line`, changed in place //! as the row moves. Every phone of the person draws the same from the same //! rows. The phone writes the row itself, in its own copy, and it goes up //! sealed (the queue's `seal`: the link and title sealed, the state clear), //! so no server reads the link; the person's Mac opens it to download. //! //! What the person writes that holds no link is answered at once with the //! kit's line ("Send a link here and Cotton will download it.") and kept //! nowhere. //! //! Done and failed downloads are told once per phone (`chat.notices`'s //! `downloads`), never while the chat is muted on that phone, and never for //! one that finished before this phone first asked. use serde_json::{json, Map, Value}; use cotton_core::cotton_rules::downloads_chat::{self as rules, Fetch, Landed, Words}; use cotton_core::kit::AppKit; use cotton_core::messages::app::list::say; use cotton_core::rules::shell_lines::LineSet; use cotton_tools::mcp::dispatch::Ctx; use rusqlite::types::Value as SqlValue; use super::{list, ms, read, rows, s, text, ws, Clock}; use crate::methods::MethodError; use crate::shell::client::ClientController; /// The Downloads chat's id wherever a thread's is asked. pub const THREAD: &str = "downloads"; /// What this phone keeps of it: whether it is muted, since when it tells, what it told. const KEPT: &str = "chat-downloads.json"; /// Items a page holds. const PAGE: usize = 40; /// Told downloads remembered at most (the newest). const TOLD_MAX: usize = 400; const FETCH: &str = "cotton_fetch"; const FETCH_FILE: &str = "cotton_fetch_file"; /// The landed record's file, by its `fetch_file` link column: (link column, table, its table on the phone, file column). const FILES: [(&str, &str, &str, &str); 6] = [ ("film", "film", "cotton_film", "file"), ("episode", "film_episode", "cotton_film_episode", "file"), ("song", "song", "cotton_song", "file"), ("book", "book", "cotton_book", "file"), ("photo", "photo", "cotton_photos", "key"), ("document", "document", "cotton_documents", "storage_path"), ]; /// Whether this app holds the Downloads chat: a phone signed in (the queue /// lives in the person's object) whose kit keeps the queue. pub fn shows(client: &ClientController) -> bool { client.object_door().is_some() && keeps_queue(client) } fn keeps_queue(client: &ClientController) -> bool { match AppKit::at(client.layout().root()) { Ok(Some(kit)) => kit.keeps_table("fetch") && kit.keeps_table("fetch_file"), // The whole object (Cotton's own) keeps every table. Ok(None) => true, Err(_) => false, } } fn words(lines: &LineSet) -> Words { let w = |line: &str| say(lines, &format!("app.downloads.{line}"), &[]); Words { queued: w("queued"), queued_waiting: w("queued_waiting"), progress: w("progress"), fetching: w("fetching"), done: w("done"), done_unsized: w("done_unsized"), done_many: w("done_many"), opens_in: w("opens_in"), saved: w("saved"), failed: w("failed"), failed_unsaid: w("failed_unsaid"), cancelled: w("cancelled"), open: w("open"), show: w("show"), retry: w("retry"), unnamed: w("unnamed"), row: w("row"), done_short: w("done_short"), failed_short: w("failed_short"), apps: APPS.iter().map(|app| (app.to_string(), w(&format!("apps.{app}")))).filter(|(_, name)| !name.is_empty()).collect(), } } /// The Cotton apps a download may open in (`rules::opener`), whose names the kit says. const APPS: [&str; 4] = ["cinemas", "music", "books", "photos"]; /// What is said where something written holds no link. pub(crate) fn not_a_link() -> String { say(&list::lines(), "app.downloads.not_a_link", &[]) } /// A link as the chat shows it: without its `https://` (the drawing's `example.com/talks/…`). fn shown(link: &str) -> String { ["https://", "http://"].iter().find_map(|scheme| link.strip_prefix(scheme)).unwrap_or(link).trim_start_matches("www.").to_string() } // ── what this phone keeps ─────────────────────────────────────────────── fn kept(client: &ClientController) -> Map { std::fs::read(client.layout().client_dir().join(KEPT)).ok().and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_default() } fn keep(client: &ClientController, kept: &Map) -> Result<(), MethodError> { let path = client.layout().client_dir().join(KEPT); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(|why| MethodError::new("unwritable", why.to_string()))?; } // not a copy: the downloads list. std::fs::write(path, Value::Object(kept.clone()).to_string()).map_err(|why| MethodError::new("unwritable", why.to_string())) } /// Whether the chat is muted on this phone. pub fn muted(client: &ClientController) -> bool { kept(client).get("muted").and_then(Value::as_bool).unwrap_or(false) } fn set_muted(client: &ClientController, on: bool) -> Result<(), MethodError> { let mut held = kept(client); held.insert("muted".into(), json!(on)); keep(client, &held) } // ── the rows ──────────────────────────────────────────────────────────── /// One download as the chat draws it. #[derive(Debug, Clone)] struct Item { fetch: Fetch, source: String, /// When the link was sent (`added_on`, else the row's birth). sent: String, /// When the row last moved. moved: String, /// What it landed: each file and the record it is. landed: Vec>, } fn number(row: &Map, key: &str) -> Option { row.get(key).and_then(Value::as_f64) } /// The downloads, newest sent first: `limit` of them, those sent before `before` (`sent` and id) when given, or the one `only`. fn items(ctx: &mut Ctx<'_>, limit: usize, before: Option<(String, String)>, only: Option<&str>) -> Result, String> { let mut sql = format!( "SELECT id, source, title, state, progress, error, of_bytes, coalesce(added_on, created_at) AS sent, coalesce(updated_at, created_at) AS moved FROM {FETCH} WHERE workspace_id = ? AND deleted_at IS NULL" ); let mut params = vec![ws(ctx)]; // HIDDEN (re-review 3, finding 3; CORE 5 M2): a download that landed a hidden title is left out in the read, before // the page is cut, so a hidden one among the newest never hides older visible ones or empties the list's row. let shut = crate::phone::cinemas_home::hidden_titles(ctx)?; if !shut.is_empty() { sql.push_str(" AND id NOT IN (SELECT value FROM json_each(?))"); params.push(text(Value::from(shut.into_iter().collect::>()).to_string())); } if let Some(id) = only { sql.push_str(" AND id = ?"); params.push(text(id.to_string())); } if let Some((sent, id)) = &before { sql.push_str(" AND (coalesce(added_on, created_at) < ? OR (coalesce(added_on, created_at) = ? AND id < ?))"); params.extend([text(sent.clone()), text(sent.clone()), text(id.clone())]); } sql.push_str(" ORDER BY sent DESC, id DESC LIMIT ?"); params.push(SqlValue::Integer(limit as i64)); let found = rows(ctx, &sql, ¶ms)?; let ids: Vec = found.iter().filter_map(|row| s(row, "id")).collect(); let landed = super::rows_in(ctx, &format!("SELECT id, \"fetch\", name, kind, bytes, film, episode, song, book, photo, document FROM {FETCH_FILE} WHERE workspace_id = ? AND deleted_at IS NULL"), "\"fetch\"", &ids)?; Ok(found .into_iter() .filter_map(|row| { let id = s(&row, "id")?; let mut files: Vec> = landed.iter().filter(|file| s(file, "fetch").as_deref() == Some(id.as_str())).cloned().collect(); files.sort_by_key(|file| s(file, "name").unwrap_or_default()); let fetch = Fetch { id: id.clone(), state: s(&row, "state").unwrap_or_else(|| "queued".into()), progress: number(&row, "progress"), title: s(&row, "title"), error: s(&row, "error"), of_bytes: number(&row, "of_bytes"), files: files .iter() .map(|file| Landed { id: s(file, "id").unwrap_or_default(), name: s(file, "name").unwrap_or_default(), bytes: number(file, "bytes"), kind: s(file, "kind"), record: None }) .collect(), waited_ms: None, }; Some(Item { fetch, source: s(&row, "source").unwrap_or_default(), sent: s(&row, "sent").unwrap_or_default(), moved: s(&row, "moved").unwrap_or_default(), landed: files }) }) .collect()) } fn one_item(ctx: &mut Ctx<'_>, fetch: &str) -> Result, String> { Ok(items(ctx, 1, None, Some(fetch))?.into_iter().next()) } /// Cotton's line for `item` now: a queued one knows how long it has stood since it was queued (its last move: sent, or tried again). fn line_of(clock: &Clock, words: &Words, item: &Item) -> rules::Line { let mut fetch = item.fetch.clone(); if fetch.state == "queued" && !item.moved.is_empty() { fetch.waited_ms = Some(clock.now.timestamp_millis() - ms(&item.moved)); } rules::line(&fetch, words) } /// When a queued item's line next changes on its own (a minute after it was queued), for the phone to ask again then. fn turns_at(clock: &Clock, item: &Item) -> Option { let at = ms(&item.moved) + rules::UNCLAIMED_MS; (item.fetch.state == "queued" && !item.moved.is_empty() && at > clock.now.timestamp_millis()).then_some(at) } fn item_json(clock: &Clock, words: &Words, item: &Item) -> Value { let line = line_of(clock, words, item); let (sent_clock, _, _) = clock.slip(&item.sent); let (moved_clock, _, _) = clock.slip(&item.moved); json!({ "fetch": item.fetch.id, "link": { "text": item.source, "shown": shown(&item.source), "at": item.sent, "time": sent_clock }, "cotton": { "at": item.moved, "time": moved_clock, "line": line }, }) } // ── the list row ──────────────────────────────────────────────────────── /// The newest download's moment and its line, or none before the first. pub(crate) fn newest(client: &ClientController) -> Result, MethodError> { let words = words(&list::lines()); let found = read(client, "chat.downloads.row", |ctx| Ok(items(ctx, 1, None, None)?.into_iter().next()))?; let clock = Clock::of(client); Ok(found.map(|item| (item.moved.clone(), line_of(&clock, &words, &item).row))) } /// The Downloads chat as a row of the list: Cotton's mark, no number, its /// last line the newest download's state (the kit's invitation before the /// first), muted or not on this phone, its only acts Mute and Unmute. pub(crate) fn row(client: &ClientController, newest: Option<&(String, String)>) -> Value { let lines = list::lines(); let clock = Clock::of(client); let muted = muted(client); let swipe = if muted { json!({ "act": "unmute", "label": say(&lines, "app.swipe.unmute", &[]) }) } else { json!({ "act": "mute", "label": say(&lines, "app.swipe.mute", &[]) }) }; let last = newest.map_or_else(|| say(&lines, "app.downloads.not_a_link", &[]), |(_, line)| line.clone()); let mut row = json!({ "thread": THREAD, "kind": THREAD, "name": say(&lines, "app.downloads.name", &[]), "group": false, "source": "cotton", "picture": { "initials": "", "tint": 0, "mark": THREAD }, "lastLine": { "text": last, "mine": false }, "unread": 0, "markedUnread": false, "pinned": false, "muted": muted, "archived": false, "sendable": false, "leading": [], "trailing": [swipe.clone()], "hold": [swipe], }); if let Some(when) = newest.and_then(|(at, _)| clock.recent(at)) { row["when"] = json!(when); } row } /// Where the row stands on a page of the list: among the unpinned /// conversations by its newest download's moment, after every pinned one; /// before any download, last. `page` holds each row's moment and pin; /// `after` is the moment the page began after (none on the first page); /// `more` whether another page follows. `None`: on another page. pub(crate) fn place(page: &[(Option, bool)], after: Option<(bool, Option)>, more: bool, at: Option<&str>) -> Option { let Some(at) = at else { return (!more).then_some(page.len()) }; // It went on an earlier page when that page's last unpinned row was older. if let Some((false, Some(edge))) = &after { if ms(edge) < ms(at) { return None; } } let index = page.iter().position(|(moment, pinned)| !pinned && moment.as_deref().is_none_or(|moment| ms(moment) < ms(at))); match index { Some(index) => Some(index), None if !more => Some(page.len()), None => None, } } // ── the page ──────────────────────────────────────────────────────────── /// Each item, the first of its day carrying the day's numeral above it (`day: { date, words }`), as a conversation draws its days. fn with_days(clock: &Clock, lines: &LineSet, items: Vec<(String, Value)>) -> Vec { let mut last = None; items .into_iter() .map(|(sent, mut item)| { let (_, _, day) = clock.slip(&sent); if last != Some(day) { let (date, words) = clock.numeral(lines, day); item["day"] = json!({ "date": date, "words": words }); last = Some(day); } item }) .collect() } fn cursor(item: &Item) -> String { format!("{}\u{1f}{}", item.sent, item.fetch.id) } fn parse_cursor(cursor: &str) -> Option<(String, String)> { let (sent, id) = cursor.split_once('\u{1f}')?; Some((sent.to_string(), id.to_string())) } /// `chat.downloads { before? }`: the newest forty downloads, oldest first, and `earlier` while older ones remain. pub fn page(client: &ClientController, request: &Value) -> Result { let lines = list::lines(); let words = words(&lines); let clock = Clock::of(client); let before = request.get("before").and_then(Value::as_str).and_then(parse_cursor); let mut found = read(client, "chat.downloads", |ctx| items(ctx, PAGE + 1, before.clone(), None))?; let more = found.len() > PAGE; found.truncate(PAGE); let earlier = if more { found.last().map(cursor) } else { None }; found.reverse(); let muted = muted(client); let hold = if muted { json!([{ "act": "unmute", "label": say(&lines, "app.swipe.unmute", &[]) }]) } else { json!([{ "act": "mute", "label": say(&lines, "app.swipe.mute", &[]) }]) }; let mut answer = json!({ "thread": THREAD, "kind": THREAD, "title": say(&lines, "app.downloads.name", &[]), "by": say(&lines, "app.downloads.by", &[]), "picture": { "initials": "", "tint": 0, "mark": THREAD }, "about": say(&lines, "app.downloads.about", &[]), "placeholder": say(&lines, "app.downloads.placeholder", &[]), "muted": muted, "hold": hold, "items": with_days(&clock, &lines, found.iter().map(|item| (item.sent.clone(), item_json(&clock, &words, item))).collect()), }); if let Some(earlier) = earlier { answer["earlier"] = json!(earlier); } // A queued line says "waiting for your Mac" a minute on: the phone asks again then, with nothing else moving. if let Some(at) = found.iter().filter_map(|item| turns_at(&clock, item)).min() { answer["askAgainAt"] = json!(at); } Ok(answer) } // ── sending a link ────────────────────────────────────────────────────── /// How the phone asks its object: `object.act` (a test hands a fake). pub(crate) type Object<'a> = &'a dyn Fn(&Value) -> Result; /// The object's own door, as `object.act` asks it. pub(crate) fn object_of(client: &ClientController) -> impl Fn(&Value) -> Result + '_ { move |request: &Value| crate::phone::object_acts::call_on(client, request) } /// `chat.downloads.send { text }`: each link in what the person wrote /// becomes a `fetch` row this phone writes in its own copy /// (`rules::queued`), sealed on its way up like every row of the queue, so /// the object stores a link it cannot read and the person's Mac, a device /// holding the key, opens it to download. The row stands at once, Queued. /// Words with no link in them are answered with the kit's line and kept nowhere. pub fn send(client: &ClientController, request: &Value) -> Result { let written = request.get("text").and_then(Value::as_str); let links = crate::phone::share_fetch::fetch_links(true, request.get("url").and_then(Value::as_str), written); if links.is_empty() { return Ok(json!({ "fetch": [], "said": not_a_link() })); } queue(client, &links, request.get("title").and_then(Value::as_str)) } /// Each link on the queue, as this phone's own `fetch` rows; `title` names a lone link (a share's card). pub(crate) fn queue(client: &ClientController, links: &[String], title: Option<&str>) -> Result { if !shows(client) { return Err(refuse(crate::phone::object_acts::SIGN_IN_FIRST, say(&list::lines(), "app.downloads.sign_in", &[]))); } let lines = list::lines(); let words = words(&lines); let clock = Clock::of(client); let now = clock.now_iso(); let title = title.map(str::trim).filter(|title| !title.is_empty() && links.len() == 1 && *title != links[0]); let mut made = Vec::new(); let mut shown = Vec::new(); for link in links { let mut row = rules::queued(link, &now); if let Some(title) = title { row["title"] = json!(title); } let answer = crate::phone::records::call(client, "records.create", &json!({ "table": "fetch", "data": row }))?; let id = answer.pointer("/record/id").or_else(|| answer.get("id")).and_then(Value::as_str).ok_or_else(|| refuse("unwritable", "the download was made with no id"))?.to_string(); let item = Item { fetch: Fetch { id: id.clone(), state: "queued".into(), progress: None, title: row["title"].as_str().map(str::to_string), error: None, of_bytes: None, files: Vec::new(), waited_ms: None }, source: link.clone(), sent: now.clone(), moved: now.clone(), landed: Vec::new(), }; shown.push(item_json(&clock, &words, &item)); made.push(json!(id)); } Ok(json!({ "fetch": made, "items": shown })) } // ── the acts ──────────────────────────────────────────────────────────── fn refuse(code: &str, message: impl Into) -> MethodError { MethodError::new(code, message.into()) } /// The scheme the Cotton app `app` answers on this build's side. fn scheme(client: &ClientController, app: &str) -> String { match client.flavor() { Some(cotton_core::flavor::Flavor::Real) => format!("cotton{app}"), _ => format!("cotton{app}dev"), } } /// What Open does for a done download: the Cotton app that plays it, by its /// own link (`://lists//`, which its `link.open` opens on /// the record); else the file itself, for the phone's own viewer. Where /// nothing on the phone opens it, the phone saves it to Files and draws the /// line's `unopened`. fn open(client: &ClientController, item: &Item) -> Result { let lines = list::lines(); let Some(file) = item.landed.first() else { return Err(refuse("not_landed", say(&lines, "app.downloads.not_landed", &[]))); }; let kind = s(file, "kind").unwrap_or_default(); let mut apps = Vec::new(); let mut key = None; for (column, table, held_in, file_column) in FILES { let Some(record) = s(file, column) else { continue }; if let Some((app, opener_table)) = rules::opener(&kind) { if opener_table == table { apps.push(json!({ "app": app, "url": format!("{}://lists/{table}/{record}", scheme(client, app)) })); } } let found = read(client, "chat.downloads.open", |ctx| { // A table this app's kit does not keep is not on the phone: no file, and the app is the way. let sql = format!("SELECT {file_column} AS key FROM {held_in} WHERE id = ?"); Ok(rows(ctx, &sql, &[text(record.clone())]).unwrap_or_default().into_iter().next().and_then(|row| s(&row, "key"))) })?; if found.is_some() { key = found; break; } } let mut answer = json!({ "apps": apps, "name": s(file, "name").unwrap_or_default(), }); if let Some(key) = key { answer["file"] = json!({ "key": key }); } Ok(json!({ "open": answer })) } /// `chat.downloads.act { act, fetch? }`. pub fn act(client: &ClientController, request: &Value, object: Object<'_>) -> Result { let lines = list::lines(); let name = request.get("act").and_then(Value::as_str).unwrap_or_default(); match name { "mute" | "unmute" => { set_muted(client, name == "mute")?; Ok(json!({ "muted": name == "mute", "row": row(client, newest(client)?.as_ref()) })) } "open" | "retry" => { let fetch = request.get("fetch").and_then(Value::as_str).filter(|id| !id.is_empty()).ok_or_else(|| refuse("bad_request", "`fetch` names the download"))?.to_string(); let item = read(client, "chat.downloads.act", |ctx| one_item(ctx, &fetch))?.ok_or_else(|| refuse("not_found", say(&lines, "app.downloads.gone", &[])))?; if name == "open" { if item.fetch.state != "done" { return Err(refuse("not_landed", say(&lines, "app.downloads.not_landed", &[]))); } return open(client, &item); } if !matches!(item.fetch.state.as_str(), "failed" | "cancelled") { return Err(refuse("not_stopped", say(&lines, "app.downloads.not_stopped", &[]))); } object(&json!({ "act": "fetch_retry", "args": { "fetch": fetch } }))?; // As the object left it, until sync brings the row: queued again, its last try forgotten. let mut queued = item.clone(); queued.fetch = Fetch { state: "queued".into(), progress: None, error: None, ..item.fetch.clone() }; queued.moved = Clock::of(client).now_iso(); Ok(json!({ "item": item_json(&Clock::of(client), &words(&lines), &queued) })) } other => Err(refuse("bad_request", format!("`{other}` is not an act of the Downloads chat (open, retry, mute, unmute)"))), } } // ── telling ───────────────────────────────────────────────────────────── /// The downloads to tell this phone of now: each done or failed one that /// finished since this phone first asked and that it has not told, newest /// first, as `{ fetch, key, title, text, state, at }`; none while muted (and /// those are taken as told, so unmuting does not bring them all at once). pub(crate) fn notices(client: &ClientController) -> Result, MethodError> { if !shows(client) { return Ok(Vec::new()); } let lines = list::lines(); let words = words(&lines); let mut held = kept(client); let clock = Clock::of(client); let now = clock.now_iso(); let Some(since) = held.get("since").and_then(Value::as_str).map(str::to_string) else { held.insert("since".into(), json!(now)); keep(client, &held)?; return Ok(Vec::new()); }; let told: Vec = held.get("told").and_then(Value::as_array).map(|told| told.iter().filter_map(|id| id.as_str().map(str::to_string)).collect()).unwrap_or_default(); let found = read(client, "chat.downloads.notices", |ctx| items(ctx, TOLD_MAX, None, None))?; let fresh: Vec<&Item> = found.iter().filter(|item| matches!(item.fetch.state.as_str(), "done" | "failed") && ms(&item.moved) >= ms(&since) && !told.contains(&item.fetch.id)).collect(); if fresh.is_empty() { return Ok(Vec::new()); } let mut now_told = told; now_told.extend(fresh.iter().map(|item| item.fetch.id.clone())); let skip = now_told.len().saturating_sub(TOLD_MAX); held.insert("told".into(), json!(now_told[skip..])); keep(client, &held)?; if muted(client) { return Ok(Vec::new()); } let title = say(&lines, "app.downloads.name", &[]); Ok(fresh .into_iter() .map(|item| { let line = line_of(&clock, &words, item); json!({ "fetch": item.fetch.id, "key": format!("{THREAD}:{}", item.fetch.id), "thread": THREAD, "title": title, "name": line.name, "text": line.text, "state": line.state, "at": item.moved }) }) .collect()) } #[cfg(test)] #[path = "chat_downloads_tests.rs"] pub(crate) mod tests;