Cotton code
370 lines · 15.7 KB · RustRaw
//! The Downloads chat in Comms (DLCHAT, 22 Nov 2026): what Cotton says under//! each link the person sent, decided once here so every phone of theirs//! draws the same line from the same `fetch` row. PURE: the phone core//! (cotton-ffi `phone::chat_downloads`) reads the rows and hands them here//! as [`Fetch`]es with the kit's words; what comes back is what a phone draws.//!//! - [`line`]: the one line under a link, changed in place as the row moves://!   the file's name, and under it Queued, a percentage, Done with its size,//!   the app it opens in and Open (or, where nothing on the phone opens it,//!   Saved to Files and Show), Failed with the reason in plain words and//!   Retry, Cancelled and Retry; and the chat list's last line for it.//!   As drawn in `assets/design/chat/you-grouped.html`, its last two screens.//! - [`opener`]: which Cotton app plays what a download landed as.//! - [`size`]: a size the way a person reads it.//! - [`queued`]: the `fetch` row a link becomes when the phone writes it//!   itself, sealed: beside the seal its kind, what it wants and when it was//!   sent, spelled by the Worker's own rule (`apps/business/src/fetch.ts`://!   `sourceKindOf`, `wantsOf`, `provisionalTitle`), since the object cannot//!   read a sealed link and takes a sealed row's kind as the device says it.//!//! Words are the kit's (`kits/shell/lines/chat.json`, `downloads.*`), handed//! in as [`Words`]; nothing here holds a sentence.use serde::{Deserialize, Serialize};/// A file a download landed, as `fetch_file` holds it.#[derive(Debug, Clone, PartialEq, Deserialize)]pub struct Landed {    pub id: String,    pub name: String,    #[serde(default)]    pub bytes: Option<f64>,    /// `film`, `episode`, `song`, `book`, `photo` or `document`.    #[serde(default)]    pub kind: Option<String>,    /// The record it landed as, `(table, id)`.    #[serde(default)]    pub record: Option<(String, String)>,}/// A download as the line needs it: its `fetch` row and what it landed.#[derive(Debug, Clone, PartialEq, Deserialize)]pub struct Fetch {    pub id: String,    /// `queued`, `fetching`, `landing`, `done`, `failed` or `cancelled`.    pub state: String,    #[serde(default)]    pub progress: Option<f64>,    #[serde(default)]    pub title: Option<String>,    #[serde(default)]    pub error: Option<String>,    #[serde(default)]    pub of_bytes: Option<f64>,    #[serde(default)]    pub files: Vec<Landed>,    /// How long it has stood queued, when the caller knows (now less when it was sent or tried again).    #[serde(default)]    pub waited_ms: Option<i64>,}/// How long a queued download waits before its line says no fetcher has/// taken it: a fetcher running claims a queued row within seconds (the Mac's/// pass), so one still queued after a minute has none (owner, 22 Nov 2026).pub const UNCLAIMED_MS: i64 = 60_000;/// The kit's words for the lines (`downloads.*`).#[derive(Debug, Clone, Default, Deserialize)]pub struct Words {    pub queued: String,    /// Queued for longer than [`UNCLAIMED_MS`]: no fetcher has taken it.    pub queued_waiting: String,    /// `{n}`: the percentage.    pub progress: String,    /// Fetching with no figure yet.    pub fetching: String,    /// `{size}`.    pub done: String,    /// When no size is known.    pub done_unsized: String,    /// `{n}`: how many files, `{size}`: all of them.    pub done_many: String,    /// `{app}`: the Cotton app that plays it, said after the size ("opens in Cinemas").    pub opens_in: String,    /// Done, where nothing on this phone opens it: saved to the phone's files.    pub saved: String,    /// `{why}`: the fetcher's reason.    pub failed: String,    /// A failure that gave no reason.    pub failed_unsaid: String,    pub cancelled: String,    pub open: String,    pub show: String,    pub retry: String,    /// A file with no name of its own.    pub unnamed: String,    /// The list row's last line: `{state}` (the short word) and `{name}`.    pub row: String,    pub done_short: String,    pub failed_short: String,    /// Each Cotton app's name as the line says it, by its slug.    #[serde(default)]    pub apps: std::collections::BTreeMap<String, String>,}/// What a line offers.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct Act {    /// `open`, `show` or `retry`.    pub act: String,    pub label: String,}/// The Cotton app a done line says it opens in.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct Opens {    /// Its slug (`cinemas`).    pub app: String,    /// Its name (`Cinemas`).    pub name: String,}/// A done line where nothing on this phone opens the file: the phone draws/// this in its place (its words and Show) once the file is saved to Files.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct Unopened {    pub text: String,    pub act: Act,}/// The line Cotton says under one link.#[derive(Debug, Clone, PartialEq, Serialize)]pub struct Line {    /// `queued`, `progress`, `done`, `failed` or `cancelled`: how the line is drawn.    pub state: String,    /// The file's name above the state (the file landed, else the title, else the kit's word).    pub name: String,    /// The state in words: `Queued`, `40%`, `Done · 412 MB · opens in Cinemas`, `Failed · the site didn't answer`.    pub text: String,    /// The list row's last line for it: `Done: river-walk-talk.mp4`.    pub row: String,    /// 0–99 while fetching, when the fetcher says.    #[serde(skip_serializing_if = "Option::is_none")]    pub percent: Option<u8>,    #[serde(skip_serializing_if = "Option::is_none")]    pub size: Option<String>,    /// How many files it landed, when done (1 for most).    #[serde(skip_serializing_if = "Option::is_none")]    pub count: Option<usize>,    #[serde(skip_serializing_if = "Option::is_none")]    pub opens: Option<Opens>,    #[serde(skip_serializing_if = "Option::is_none")]    pub act: Option<Act>,    #[serde(skip_serializing_if = "Option::is_none")]    pub unopened: Option<Unopened>,}fn fill(words: &str, fills: &[(&str, &str)]) -> String {    fills.iter().fold(words.to_string(), |said, (slot, value)| said.replace(&format!("{{{slot}}}"), value))}/// A size as a person reads it: `820 KB`, `4.2 MB`, `38 MB`, `1.4 GB`./// Decimal units, as phones and stores say them; never more than it is.pub fn size(bytes: f64) -> Option<String> {    if !bytes.is_finite() || bytes < 0.0 {        return None;    }    const KB: f64 = 1_000.0;    const MB: f64 = 1_000_000.0;    const GB: f64 = 1_000_000_000.0;    let tenths = |n: f64| (n * 10.0).floor() / 10.0;    Some(if bytes < MB {        format!("{} KB", (bytes / KB).floor().max(1.0) as u64)    } else if bytes < 10.0 * MB {        format!("{:.1} MB", tenths(bytes / MB))    } else if bytes < GB {        format!("{} MB", (bytes / MB).floor() as u64)    } else {        format!("{:.1} GB", tenths(bytes / GB))    })}/// The Cotton app that plays what a file landed as, and the table its record is in.pub fn opener(kind: &str) -> Option<(&'static str, &'static str)> {    match kind {        "film" => Some(("cinemas", "film")),        "episode" => Some(("cinemas", "film_episode")),        "song" => Some(("music", "song")),        "book" => Some(("books", "book")),        "photo" => Some(("photos", "photo")),        // A document has no Cotton app of its own: the phone's viewer opens it.        _ => None,    }}fn one_line(text: &str) -> String {    text.split_whitespace().collect::<Vec<_>>().join(" ")}/// The name a download goes by: the file it landed, else its title, else the kit's word.fn name_of(fetch: &Fetch, words: &Words) -> String {    let named = fetch.files.first().map(|file| one_line(&file.name)).filter(|name| !name.is_empty());    named.or_else(|| fetch.title.as_deref().map(one_line).filter(|title| !title.is_empty())).unwrap_or_else(|| words.unnamed.clone())}/// The line under `fetch`'s link.pub fn line(fetch: &Fetch, words: &Words) -> Line {    let act = |act: &str, label: &str| Some(Act { act: act.to_string(), label: label.to_string() });    let name = name_of(fetch, words);    let row = |short: &str| fill(&words.row, &[("state", short), ("name", &name)]);    let plain = |state: &str, text: String, short: &str| Line { state: state.into(), name: name.clone(), row: row(short), text, percent: None, size: None, count: None, opens: None, act: None, unopened: None };    match fetch.state.as_str() {        "done" => {            let summed: Option<f64> = if fetch.files.is_empty() { None } else { fetch.files.iter().map(|file| file.bytes).sum() };            let size = summed.or(fetch.of_bytes).and_then(size);            let count = fetch.files.len().max(1);            let opens = fetch.files.first().and_then(|file| file.kind.as_deref()).and_then(opener).and_then(|(app, _)| words.apps.get(app).map(|name| Opens { app: app.to_string(), name: name.clone() }));            let mut text = match (&size, count) {                (Some(size), n) if n > 1 => fill(&words.done_many, &[("n", &n.to_string()), ("size", size)]),                (Some(size), _) => fill(&words.done, &[("size", size)]),                (None, _) => words.done_unsized.clone(),            };            if let Some(opens) = &opens {                text = format!("{text} · {}", fill(&words.opens_in, &[("app", &opens.name)]));            }            Line {                size,                count: Some(count),                opens,                act: act("open", &words.open),                unopened: Some(Unopened { text: words.saved.clone(), act: Act { act: "show".into(), label: words.show.clone() } }),                ..plain("done", text, &words.done_short)            }        }        "failed" => {            let why = fetch.error.as_deref().map(one_line).filter(|why| !why.is_empty());            let text = why.map_or_else(|| words.failed_unsaid.clone(), |why| fill(&words.failed, &[("why", &why)]));            Line { act: act("retry", &words.retry), ..plain("failed", text, &words.failed_short) }        }        "cancelled" => Line { act: act("retry", &words.retry), ..plain("cancelled", words.cancelled.clone(), &words.cancelled) },        "fetching" | "landing" => match fetch.progress.filter(|n| n.is_finite()) {            // Never more than it has: 99.6 % is 99 %, and only a row that is done says 100.            Some(progress) => {                let percent = progress.clamp(0.0, 99.0).floor() as u8;                let text = fill(&words.progress, &[("n", &percent.to_string())]);                Line { percent: Some(percent), ..plain("progress", text.clone(), &text) }            }            None => plain("progress", words.fetching.clone(), &words.fetching),        },        // `queued`, and a state this build does not know, wait; past a minute untaken, it says no fetcher has it.        _ => {            let text = if fetch.waited_ms.is_some_and(|waited| waited >= UNCLAIMED_MS) { words.queued_waiting.clone() } else { words.queued.clone() };            plain("queued", text, &words.queued)        }    }}// ── a link, as the queue takes it ───────────────────────────────────────/// A file's own extensions, as a link's path ends: what makes a link a plain/// file rather than a page. The Worker's `FILE_EXTENSIONS`, word for word.const FILE_EXTENSIONS: [&str; 30] = [    "mp4", "mkv", "mov", "m4v", "webm", "avi", "mp3", "m4a", "flac", "ogg", "opus", "wav", "aac", "epub", "pdf", "jpg", "jpeg", "png", "heic", "webp", "gif", "zip", "iso", "srt", "txt", "7z", "rar", "tar",    "gz", "dmg",];fn is_magnet(link: &str) -> bool {    link.get(..7).is_some_and(|head| head.eq_ignore_ascii_case("magnet:"))}/// An http(s) link's host and path (no leading `/`), or none for anything else.fn host_and_path(link: &str) -> Option<(&str, &str)> {    let rest = ["https://", "http://"].iter().find_map(|scheme| link.get(..scheme.len()).filter(|head| head.eq_ignore_ascii_case(scheme)).map(|_| &link[scheme.len()..]))?;    let rest = rest.split(['?', '#']).next().unwrap_or_default();    let (host, path) = rest.split_once('/').unwrap_or((rest, ""));    (!host.is_empty()).then_some((host, path))}/// `%xx` decoded, as JavaScript's `decodeURIComponent`; none when it is not UTF-8 or a `%` is not followed by two hex digits.fn decoded(text: &str) -> Option<String> {    let bytes = text.as_bytes();    let mut out = Vec::with_capacity(bytes.len());    let mut at = 0;    while at < bytes.len() {        if bytes[at] == b'%' {            out.push(u8::from_str_radix(text.get(at + 1..at + 3)?, 16).ok()?);            at += 3;        } else {            out.push(bytes[at]);            at += 1;        }    }    String::from_utf8(out).ok()}/// A path segment's extension, when it ends in one (`[a-z0-9]+` after a dot).fn extension(segment: &str) -> Option<&str> {    segment.rsplit_once('.').map(|(_, extension)| extension).filter(|extension| !extension.is_empty() && extension.chars().all(|c| c.is_ascii_alphanumeric()))}/// What a link is, by its spelling alone: a magnet or a `.torrent` a/// `torrent`, a path ending in a file's extension a `file`, anything else a/// `page` (the Worker's `sourceKindOf`).pub fn source_kind(link: &str) -> &'static str {    if is_magnet(link) {        return "torrent";    }    let Some((_, path)) = host_and_path(link) else { return "page" };    let path = path.to_ascii_lowercase();    if path.ends_with(".torrent") {        return "torrent";    }    match extension(&path) {        Some(extension) if !extension.contains('/') && FILE_EXTENSIONS.contains(&extension) => "file",        _ => "page",    }}/// What a link wants unless the person said: a page's video, a torrent's or a file's files (`wantsOf`).pub fn wants(kind: &str) -> &'static str {    if kind == "page" {        "video"    } else {        "files"    }}/// A title until the Mac knows the real one: a magnet's display name, else/// the file's name, else the host and path (`provisionalTitle`).pub fn provisional_title(link: &str) -> String {    if is_magnet(link) {        let query = link.split_once('?').map_or("", |(_, query)| query);        let named = query.split('&').find_map(|pair| pair.split_once('=').filter(|(key, _)| key.eq_ignore_ascii_case("dn")).map(|(_, value)| value)).filter(|name| !name.is_empty());        return match named {            Some(name) => match decoded(&name.replace('+', " ")) {                Some(said) if said.trim().is_empty() => "A torrent".to_string(),                Some(said) => said.trim().to_string(),                None => name.to_string(),            },            None => "A torrent".to_string(),        };    }    let Some((host, path)) = host_and_path(link) else { return link.chars().take(120).collect() };    if let Some(last) = path.split('/').filter(|part| !part.is_empty()).next_back().filter(|last| extension(last).is_some()) {        return decoded(last).unwrap_or_else(|| last.to_string());    }    let host = host.to_ascii_lowercase();    let shown = if path.is_empty() { host } else { format!("{host}/{path}") };    shown.chars().take(120).collect()}/// The `fetch` row a link becomes when the phone writes it itself. The link/// and the first title are sealed by the phone as every column the server/// does not need; beside the seal, what the object needs without reading/// it: the kind, what it wants, queued, when it was sent.pub fn queued(link: &str, at: &str) -> serde_json::Value {    let kind = source_kind(link);    serde_json::json!({        "source": link,        "source_kind": kind,        "wants": wants(kind),        "state": "queued",        "added_on": at,        "title": provisional_title(link),    })}#[cfg(test)]#[path = "downloads_chat_tests.rs"]mod tests;