Cotton code
590 lines · 33.2 KB · RustRaw
//! Cinemas' pages the streaming design draws past Home and a title (cinemas-3.html 8, 10, 11 and a title's//! Subtitles): what each says, worked out here so both phones draw the same thing.//!//! cinemas.subtitles { table, id }                      → { line, tracks, working, acts }//! cinemas.onPhone   { free_bytes? }                    → { space, flight, items, empty }//! cinemas.preparing { table, id }                      → { head, steps, queue, note }//! cinemas.remote    { table, id, at_s, length_s?, device? } → { playing, title, caption, at, left, next }//!//! Every word is `cinemas.json` `home.*` (the remote's buttons are `stream.tv_*`, which the phones already read).//! Nothing here guesses: the Mac's steps carry no minutes because nothing records how long a step takes, and a//! size is said only where the media ledger holds one.use super::*;pub const METHODS: [&str; 9] = ["cinemas.subtitles", "cinemas.onPhone", "cinemas.preparing", "cinemas.remote", "cinemas.bin", "cinemas.restore", "cinemas.erase", "cinemas.you", "cinemas.setting"];pub fn call(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "cinemas.you" => you(client, request),        "cinemas.setting" => setting(client, request),        "cinemas.bin" => bin(client, request),        "cinemas.restore" => restore(client, request),        "cinemas.erase" => erase(client, request),        "cinemas.subtitles" => subtitles(client, request),        "cinemas.onPhone" => on_phone(client, request),        "cinemas.preparing" => preparing(client, request),        "cinemas.remote" => remote(client, request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a cinemas method"))),    }}/// The table and id a page names, refused in the method's own words.fn named(request: &Value, method: &str) -> Result<(&'static str, String), MethodError> {    let table = match request.get("table").and_then(Value::as_str) {        Some(FILM_TABLE) => FILM_TABLE,        Some(EPISODE_TABLE) => EPISODE_TABLE,        _ => return Err(bad(format!("{method} names film or film_episode: table"))),    };    let id = request.get("id").and_then(Value::as_str).map(str::trim).filter(|id| !id.is_empty()).ok_or_else(|| bad(format!("{method} names the title: id")))?;    Ok((table, id.to_string()))}/// One row's columns, or "That title is no longer here".fn one_row(client: &ClientController, method: &str, table: &str, id: &str, columns: &str) -> Result<Row, MethodError> {    let mut found = None;    client        .read_rows(method, &mut |ctx| {            found = rows_where(ctx, table, columns, "id = ?", &[rusqlite::types::Value::Text(id.to_string())])?.into_iter().next();            Ok(Value::Null)        })        .map_err(unreadable)?;    found.ok_or_else(|| MethodError::new("not_found", say("no_title", &[])))}/// A size as a person reads it: "640 MB", "2.4 GB".fn size(bytes: u64) -> String {    let gb = bytes as f64 / 1_000_000_000.0;    if gb >= 1.0 { say("size_gb", &[("n", &format!("{gb:.1}"))]) } else { say("size_mb", &[("n", &format!("{:.0}", (bytes as f64 / 1_000_000.0).max(1.0)))]) }}/// A length in hours and minutes: "9 h 40 m", "48 m".fn length(minutes: f64) -> String {    let total = minutes.max(0.0).round() as u64;    if total >= 60 { say("length_hours", &[("h", &(total / 60).to_string()), ("m", &(total % 60).to_string())]) } else { say("length_minutes", &[("m", &total.to_string())]) }}/// A length in the page's words (for `cinemas.title`'s watched line).pub(super) fn minutes_said(minutes: f64) -> String {    length(minutes)}/// The size of a file the media ledger holds, said ("2.3 GB"); none where it holds none.pub(super) fn kept_size(client: &ClientController, key: &str) -> Result<Option<String>, MethodError> {    if key.is_empty() {        return Ok(None);    }    let bytes = client        .with_writer(|f| Ok(cotton_store::media_ledger::media_by_key(f.driver, key).map_err(|error| error.to_string())?.map(|row| u64::try_from(row.size_bytes).unwrap_or(0))))        .map_err(unreadable)?;    Ok(bytes.filter(|bytes| *bytes > 0).map(size))}/// The Subtitles act's second line from a row's `subtitles` and `subtitle_choice`: the track he chose, Off, or the/// first track; none while it has none.pub(super) fn subtitle_line(row: &Row) -> Option<String> {    let tracks = tracks_of(row);    let shown = |track: &Track| if track.name.trim().is_empty() { track.language.clone() } else { track.name.trim().to_string() };    match choice_of(row) {        Some(None) => Some(say("subtitles_off", &[])),        Some(Some((language, name))) => tracks            .iter()            .find(|track| (!name.is_empty() && track.name == name) || (name.is_empty() && track.language == language))            .or(tracks.first())            .map(shown),        None => tracks.first().map(shown),    }}// ---- the Bin ----/// Run `f` as the Bin inside Hidden when `inside` (`hidden::in_hidden_bin`), else as the shared Bin.fn in_bin<T>(inside: bool, f: impl FnOnce() -> T) -> T {    if inside { cotton_tools::mcp::handlers::tables::hidden::in_hidden_bin(f) } else { f() }}/// Whether the Bin asked now shows this binned row (THE Bin's gate, `hidden::bin_shows`).fn shows(hiding: &super::Hiding, row: &Row) -> bool {    let id = row.get("id").and_then(Value::as_str);    cotton_tools::mcp::handlers::tables::hidden::bin_shows(hiding, id, row)}/// `cinemas.bin { hidden? }` → `{ title, items: [{ item, line }], empty, hidden, count, restore, erase }`: the films,/// series and episodes in the Bin, newest binned first, each with the day it went in. They are still here until the/// Bin is emptied, with their files on the object kept too (0932bbdbc1), so a restore brings back a title that plays./// `count` is how many it holds, counted from the rows it lists. `restore` and `erase` are the acts each item takes,/// with the item's id added as `id`: `cinemas.restore { id }` and `cinemas.erase { id, hidden? }` (Delete forever)./// With `hidden: true` (open only by the core's unlock) it is the Bin inside Hidden: the hidden titles alone.pub(super) fn bin(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    // Inside Hidden (`hidden: true`, open by the core's unlock) the hidden titles' Bin alone; outside, never one of them.    let inside = request.get("hidden") == Some(&Value::Bool(true));    if inside {        super::inside_hidden(client, false)?;    }    let states = super::super::films::file_states(client)?;    let mut binned: Vec<(String, Value)> = Vec::new();    in_bin(inside, || client        .read_rows("cinemas.bin", &mut |ctx| {            if !holds_table(ctx, FILM_TABLE)? {                return Ok(Value::Null);            }            // HIDDEN (review A4): a hidden title binned is not named here; Stop hiding brings it back to the Bin. THE            // Bin's gate decides (`hidden::bin_shows`, CORE 4 L1).            let hiding = super::hiding(ctx)?;            let seasons = seasons_of(ctx)?;            let series: BTreeMap<String, (String, Option<String>)> = rows_where(ctx, FILM_TABLE, "id, title, poster", "kind = 'series'", &[])?                .iter()                .map(|row| (text_of(row, "id"), (text_of(row, "title"), words(row, "poster"))))                .collect();            let workspace = rusqlite::types::Value::Text(ctx.workspace_id.to_string());            for table in [FILM_TABLE, EPISODE_TABLE] {                if !holds_table(ctx, table)? {                    continue;                }                let made = cotton_tools::mcp::handlers::tables::made_table(table);                let rows = ctx                    .db()                    // Every column: THE gate judges a row by its links too (an episode by its series).                    .all(&format!("SELECT * FROM {made} WHERE workspace_id = ? AND deleted_at IS NOT NULL"), std::slice::from_ref(&workspace))                    .map_err(|error| error.to_string())?;                for row in rows.iter().map(super::super::songs::json_row) {                    if !shows(&hiding, &row) {                        continue;                    }                    let title = if table == FILM_TABLE { Title::film(&row) } else { Title::episode(&row, &seasons, &series) };                    let when = text_of(&row, "deleted_at");                    let day = when.get(..10).unwrap_or_default().to_string();                    binned.push((when, json!({ "item": title.item(&states), "line": say("binned_on", &[("day", &day)]) })));                }            }            Ok(Value::Null)        }))        .map_err(unreadable)?;    binned.sort_by(|a, b| b.0.cmp(&a.0));    let empty = binned.is_empty().then(|| say("bin_empty", &[]));    let erase_args = if inside { json!({ "hidden": true }) } else { json!({}) };    Ok(json!({        "title": say("bin_title", &[]),        "hidden": inside,        "count": binned.len(),        "items": binned.into_iter().map(|(_, item)| item).collect::<Vec<_>>(),        "empty": empty,        "restore": { "label": say("bin_restore", &[]), "method": "cinemas.restore", "args": {} },        "erase": { "label": say("bin_erase", &[]), "method": "cinemas.erase", "args": erase_args },    }))}/// `cinemas.restore { id }`: a title out of the Bin, as it was (the shared restore: `restore_binned`)./// `cinemas.you { free_bytes? }` (cinemas-3.html 12): Cinemas' own sections under the shell's account card, each row/// with its words, what it holds now, and the act that changes or opens it. A row with `switch` is turned by its act;/// one with `open` is a page the phone opens (`tv`: its own TV picker; `help_ready`: the help line, shown in place)./// Left out until something keeps them: the subtitle size, asking the Mac for missing subtitles by itself/// (DECISIONS 11) and how long a sent link lasts.fn you(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let library = Library::read(client)?;    let cinema = super::super::shell_player::kinds::Cinema::read(client)?;    let keeping = super::super::films::call_keeping(client)?;    let counts = super::super::films::on_phone_counts(client)?;    let free = request.get("free_bytes").and_then(Value::as_f64).filter(|n| *n >= 0.0).map(|n| n as u64);    let waiting = library.films.iter().chain(library.episodes.iter()).filter(|title| title.preparing).count();    let binned = bin(client, &json!({}))?["items"].as_array().map_or(0, Vec::len);    let used = counts["bytes"].as_u64().unwrap_or(0);    let downloads = match free {        Some(free) => say("space_free", &[("used", &size(used)), ("free", &size(free))]),        None => say("space", &[("used", &size(used))]),    };    let language = cinema.subtitle_language.as_deref().map(|code| {        let named = say(&format!("lang_{code}"), &[]);        if named.is_empty() { code.to_string() } else { named }    });    let setting = |key: &str, on: bool| json!({ "method": "cinemas.setting", "request": { "key": key, "value": !on } });    let cellular = keeping["cellular"].as_bool().unwrap_or(false);    Ok(json!({ "sections": [        { "id": "watching", "title": say("you_watching", &[]), "rows": [            { "id": "tv", "label": say("you_tv", &[]), "value": null, "act": { "open": "tv" } },            { "id": "mac", "label": say("you_mac", &[]), "value": if waiting == 0 { say("you_mac_idle", &[]) } else { say("you_mac_waiting", &[("n", &waiting.to_string())]) }, "act": { "method": "cinemas.row", "request": { "id": "getting_ready" } } },            { "id": "groups", "label": say("you_groups", &[]), "value": library.groups.len().to_string(), "act": { "method": "cinemas.groups" } },            { "id": "autoplay_next", "label": say("you_autoplay", &[]), "switch": cinema.autoplay_next, "act": setting("autoplay_next", cinema.autoplay_next) },        ]},        { "id": "on_phone", "title": say("on_phone", &[]), "rows": [            { "id": "downloads", "label": say("you_downloads", &[]), "value": downloads, "act": { "method": "cinemas.onPhone" } },            { "id": "mobile_data", "label": say("you_mobile_data", &[]), "sub": say("you_mobile_data_sub", &[]), "switch": cellular, "act": { "method": "films.keeping", "request": { "cellular": !cellular } } },        ]},        { "id": "subtitles", "title": say("you_subtitles", &[]), "rows": [            { "id": "subtitles_on", "label": say("you_subtitles_on", &[]), "switch": cinema.subtitles_on, "act": setting("subtitles_on", cinema.subtitles_on) },            // The phone offers its languages and sends the chosen code as `value` (null: the phone's own).            { "id": "subtitle_language", "label": say("you_language", &[]), "value": language.unwrap_or_else(|| say("you_language_phone", &[])), "act": { "method": "cinemas.setting", "request": { "key": "subtitle_language" } } },        ]},        { "id": "more", "title": say("you_more", &[]), "rows": [            { "id": "bin", "label": say("bin_title", &[]), "value": binned.to_string(), "act": { "method": "cinemas.bin" } },            { "id": "help_ready", "label": say("you_help", &[]), "value": say("you_help_ready", &[]), "sub": say("you_help_ready_line", &[]), "act": { "open": "help_ready" } },        ]},    ]}))}/// `cinemas.setting { key, value }`: one of Cinemas' watching settings kept on the cinema settings row, which the/// player reads (subtitles on, their language, the next episode playing itself). Answers `cinemas.you` again.fn setting(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let key = request.get("key").and_then(Value::as_str).ok_or_else(|| bad("cinemas.setting names its key: subtitles_on, subtitle_language or autoplay_next"))?;    let value = match (key, request.get("value")) {        ("subtitles_on" | "autoplay_next", Some(Value::Bool(on))) => json!(on),        ("subtitle_language", Some(Value::Null) | None) => Value::Null,        ("subtitle_language", Some(Value::String(code))) if (2..=8).contains(&code.trim().len()) => json!(code.trim()),        ("subtitles_on" | "autoplay_next" | "subtitle_language", _) => return Err(bad("cinemas.setting: a switch takes true or false, a language its code or null")),        _ => return Err(bad("cinemas.setting names its key: subtitles_on, subtitle_language or autoplay_next")),    };    let held = super::super::records::call(client, "records.list", &json!({ "table": "face_settings", "where": { "table": super::super::shell_player::kinds::CINEMA_ROW } }))?;    match held["records"].as_array().and_then(|rows| rows.first()).and_then(|row| row["id"].as_str()) {        // The one row changed in place, a null kept as null (Android builder, 26 Nov: a language set back to the        // phone's own still said English, the earlier value standing).        Some(id) => {            super::super::records::call(client, "records.update", &json!({ "table": "face_settings", "id": id, "patch": { key: value } }))?;        }        None => {            // Every settings row names a face; Cinemas has one look, so its row names the app.            let row = json!({ "table": super::super::shell_player::kinds::CINEMA_ROW, "face": "cinemas", key: value });            super::super::records::call(client, "records.create", &json!({ "table": "face_settings", "data": row }))?;        }    }    you(client, request)}/// `cinemas.erase { id? }`: the Bin emptied, or one title in it erased, for good. Each goes to the object as an erase/// (reason `bin`), which takes the film's folder there once no live film or episode names it. Only binned rows: a live/// title is never erased from here.fn erase(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let one = request.get("id").and_then(Value::as_str).map(str::trim).filter(|id| !id.is_empty()).map(str::to_string);    // Re-review 3, finding 8, and core 3: Empty erases only what the Bin it was asked from shows. From the Bin outside    // Hidden it leaves every hidden title, even while Hidden is open (he cannot see them there); from the Bin inside    // Hidden (`hidden: true`, open by the core's unlock) it erases the hidden titles alone. One asked by id outside Hidden    // that is hidden is refused.    let inside = request.get("hidden") == Some(&Value::Bool(true));    if inside {        super::inside_hidden(client, false)?;    }    let hidden = super::hidden_titles_of(client)?;    if !inside && one.as_ref().is_some_and(|id| hidden.contains(id)) {        return Err(MethodError::new("locked", super::said("hidden_locked", &[])));    }    let written = in_bin(inside, || client        .write_rows("cinemas.erase", &mut |ctx| {            let mut doomed: Vec<String> = Vec::new();            // THE Bin's gate (`hidden::bin_shows`, CORE 4 L1): this Bin erases what it shows, and nothing of the other.            let hiding = super::hiding(ctx)?;            for table in [FILM_TABLE, EPISODE_TABLE] {                if !holds_table(ctx, table)? {                    continue;                }                let made = cotton_tools::mcp::handlers::tables::made_table(table);                let workspace = rusqlite::types::Value::Text(ctx.workspace_id.to_string());                let rows = ctx.db().all(&format!("SELECT * FROM {made} WHERE workspace_id = ? AND deleted_at IS NOT NULL"), &[workspace]).map_err(|error| error.to_string())?;                doomed.extend(                    rows.iter()                        .map(super::super::songs::json_row)                        .filter(|row| shows(&hiding, row))                        .map(|row| text_of(&row, "id"))                        .filter(|id| one.as_ref().is_none_or(|one| one == id)),                );            }            if one.is_some() && doomed.is_empty() {                return Err(say("no_title", &[]));            }            for id in &doomed {                cotton_tools::mcp::handlers::tables::erase_record(ctx, id, "bin").map_err(|failure| failure.to_string())?;            }            Ok(json!({ "erased": doomed.len() }))        }))        .map_err(|why| MethodError::new("refused", why))?;    client.nudge_sync();    Ok(crate::authoring::own_answer(written))}fn restore(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request.get("id").and_then(Value::as_str).map(str::trim).filter(|id| !id.is_empty()).ok_or_else(|| bad("cinemas.restore names the title: id"))?.to_string();    // A hidden title (or category) is restored from the Bin inside Hidden alone: refused outside it, and restored    // through that Bin inside it (THE Bin's gate, `hidden::bin_shows`).    let inside = refuse_hidden(client, &id)?;    let written = in_bin(inside, || client        .write_rows("cinemas.restore", &mut |ctx| {            let restored = cotton_tools::mcp::handlers::tables::restore_binned(ctx, &id).map_err(|failure| failure.to_string())?;            match restored {                Some(_) => Ok(json!({ "id": id, "said": say("restored", &[]) })),                None => Err(say("no_title", &[])),            }        }))        .map_err(|why| MethodError::new("refused", why))?;    client.nudge_sync();    Ok(crate::authoring::own_answer(written))}/// A hidden title acted on by its id outside Hidden: refused, as locked (re-review 3, finding 8). Answers whether it/// is a hidden one (and so Hidden is open).fn refuse_hidden(client: &ClientController, id: &str) -> Result<bool, MethodError> {    // A hidden title, or a hidden category (live or binned), by its id: only inside Hidden.    let mut shut = BTreeSet::new();    client        .read_rows("cinemas.hidden", &mut |ctx| {            shut = super::hiding(ctx)?.all();            Ok(Value::Null)        })        .map_err(unreadable)?;    if shut.contains(id) && super::inside_hidden(client, false).is_err() {        return Err(MethodError::new("locked", super::said("hidden_locked", &[])));    }    Ok(shut.contains(id))}// ---- subtitles ----#[derive(serde::Deserialize)]struct Track {    #[serde(default)]    language: String,    #[serde(default)]    name: String,    #[serde(default)]    source: String,}/// The tracks the Mac wrote in `subtitles`, as JSON; anything else reads as none.fn tracks_of(row: &Row) -> Vec<Track> {    let text = text_of(row, "subtitles");    serde_json::from_str::<Vec<Track>>(&text).unwrap_or_default().into_iter().filter(|track| !track.language.is_empty() || !track.name.is_empty()).collect()}/// The track he chose last (`subtitle_choice`: its language and name as JSON, or `off`).fn choice_of(row: &Row) -> Option<Option<(String, String)>> {    let text = text_of(row, "subtitle_choice");    let text = text.trim();    if text.is_empty() {        return None;    }    if text == "off" || text == "\"off\"" {        return Some(None);    }    let chosen: Value = serde_json::from_str(text).ok()?;    Some(Some((chosen.get("language").and_then(Value::as_str).unwrap_or_default().to_string(), chosen.get("name").and_then(Value::as_str).unwrap_or_default().to_string())))}fn subtitles(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let (table, id) = named(request, "cinemas.subtitles")?;    refuse_hidden(client, &id)?;    let row = one_row(client, "cinemas.subtitles", table, &id, "id, file, needs_mac, subtitles, subtitle_work, subtitle_note, subtitle_choice")?;    let tracks = tracks_of(&row);    let chosen = choice_of(&row);    let shown = |track: &Track| if track.name.trim().is_empty() { track.language.clone() } else { track.name.trim().to_string() };    let listed: Vec<Value> = tracks        .iter()        .map(|track| {            let from = match track.source.as_str() {                "embedded" | "sidecar" | "opensubtitles" | "generated" | "translated" => Some(say(&format!("subtitle_from_{}", track.source), &[])),                _ => None,            };            let on = match &chosen {                Some(Some((language, name))) => (!name.is_empty() && *name == track.name) || (name.is_empty() && *language == track.language),                _ => false,            };            json!({ "language": track.language, "name": shown(track), "from": from, "chosen": on })        })        .collect();    // The act's line under its mark: the track he chose, Off, the first track, or none yet.    let line = match (&chosen, tracks.first()) {        (Some(None), _) => say("subtitles_off", &[]),        (Some(Some(_)), _) if listed.iter().any(|t| t["chosen"] == true) => listed.iter().find(|t| t["chosen"] == true).and_then(|t| t["name"].as_str()).unwrap_or_default().to_string(),        (_, Some(first)) => shown(first),        (_, None) => say("subtitles_none", &[]),    };    let work = text_of(&row, "subtitle_work");    let busy = matches!(work.as_str(), "find" | "generate" | "finding" | "generating" | "translating" | "file");    let working = if work.is_empty() || work == "ready" {        None    } else {        words(&row, "subtitle_note").or_else(|| Some(say(&format!("subtitle_work_{work}"), &[])).filter(|line| !line.is_empty()))    };    let has_file = !text_of(&row, "file").trim().is_empty();    let mut acts = Vec::new();    if has_file && !busy {        acts.push(json!({ "id": "find", "label": say("subtitles_find", &[]) }));        acts.push(json!({ "id": "make", "label": say("subtitles_make", &[]) }));    }    if !busy {        acts.push(json!({ "id": "give", "label": say("subtitles_give", &[]) }));    }    Ok(json!({ "title": say("subtitles_title", &[]), "line": line, "tracks": listed, "working": working, "acts": acts }))}// ---- on this phone ----fn on_phone(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let library = Library::read(client)?;    let states = super::super::films::file_states(client)?;    let free = request.get("free_bytes").and_then(Value::as_f64).filter(|n| *n >= 0.0).map(|n| n as u64);    let kept: Vec<&Title> = library.films.iter().chain(library.episodes.iter()).filter(|title| states.contains_key(title.file.trim())).collect();    // Sizes the media ledger holds for each kept file (a whole film's; a master's bundle has none there).    let keys: Vec<String> = kept.iter().map(|title| title.file.trim().to_string()).collect();    let sizes: BTreeMap<String, u64> = client        .with_writer(|f| {            let mut sizes = BTreeMap::new();            for key in &keys {                if let Some(row) = cotton_store::media_ledger::media_by_key(f.driver, key).map_err(|error| error.to_string())? {                    sizes.insert(key.clone(), u64::try_from(row.size_bytes).unwrap_or(0));                }            }            Ok(sizes)        })        .map_err(unreadable)?;    // Which kept titles carry subtitles, read once.    let mut subtitled: BTreeSet<String> = BTreeSet::new();    let ids: Vec<(&'static str, String)> = kept.iter().map(|title| (title.table, title.id.clone())).collect();    client        .read_rows("cinemas.onPhone", &mut |ctx| {            for (table, id) in &ids {                if let Some(row) = rows_where(ctx, table, "id, subtitles", "id = ?", &[rusqlite::types::Value::Text(id.clone())])?.into_iter().next() {                    if !tracks_of(&row).is_empty() {                        subtitled.insert(id.clone());                    }                }            }            Ok(Value::Null)        })        .map_err(unreadable)?;    if kept.is_empty() {        return Ok(json!({ "title": say("on_phone", &[]), "space": null, "flight": null, "items": [], "empty": say("on_phone_empty", &[]) }));    }    let used: u64 = keys.iter().filter_map(|key| sizes.get(key)).sum();    let space = match free {        Some(free) => say("space_free", &[("used", &size(used)), ("free", &size(free))]),        None => say("space", &[("used", &size(used))]),    };    // Ready for a flight: what is wholly here (kept, not still coming down), its length, and whether every one of    // them carries subtitles.    let ready: Vec<&&Title> = kept.iter().filter(|title| states.get(title.file.trim()).map(String::as_str) == Some("kept")).collect();    let flight = (!ready.is_empty()).then(|| {        let minutes: f64 = ready.iter().filter_map(|title| title.minutes).sum();        let films = ready.iter().filter(|title| title.table == FILM_TABLE).count();        let episodes = ready.len() - films;        let count = |n: usize, one: &str, other: &str| say(if n == 1 { one } else { other }, &[("n", &n.to_string())]);        let what = match (films, episodes) {            (0, e) => count(e, "episodes_one", "episodes_other"),            (f, 0) => count(f, "films_one", "films_other"),            (f, e) => say("films_and_episodes", &[("films", &count(f, "films_one", "films_other")), ("episodes", &count(e, "episodes_one", "episodes_other"))]),        };        let all_subtitled = ready.iter().all(|title| subtitled.contains(&title.id));        json!({            // A length only where the files said one: a whole minute or more; never "0 min".            "line": if minutes >= 1.0 { say("flight", &[("length", &length(minutes))]) } else { say("flight_plain", &[]) },            "what": say(if all_subtitled { "flight_what_subtitled" } else { "flight_what" }, &[("what", &what)]),        })    });    let mut listed: Vec<&&Title> = kept.iter().collect();    listed.sort_by(|a, b| a.title.to_lowercase().cmp(&b.title.to_lowercase()).then_with(|| a.caption.cmp(&b.caption)));    let items: Vec<Value> = listed        .iter()        .map(|title| {            let key = title.file.trim();            let line = match (states.get(key).map(String::as_str), sizes.get(key)) {                (Some("keeping"), _) => say("keeping", &[]),                (_, Some(bytes)) if subtitled.contains(&title.id) => say("kept_size_subtitled", &[("size", &size(*bytes))]),                (_, Some(bytes)) => size(*bytes),                (_, None) if subtitled.contains(&title.id) => say("kept_subtitled", &[]),                _ => say("kept", &[]),            };            json!({ "item": title.item(&states), "line": line })        })        .collect();    Ok(json!({ "title": say("on_phone", &[]), "space": space, "flight": flight, "items": items, "empty": null }))}// ---- still being prepared by the Mac ----fn preparing(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let (table, id) = named(request, "cinemas.preparing")?;    // A hidden title's page opens only inside Hidden (review A4).    if super::hidden_titles_of(client)?.contains(&id) && super::inside_hidden(client, false).is_err() {        return Err(MethodError::new("not_found", say("no_title", &[])));    }    let row = one_row(client, "cinemas.preparing", table, &id, "id, created_at, needs_mac, source_file, file, subtitle_work")?;    let converting = truthy(&row, "needs_mac");    let work = text_of(&row, "subtitle_work");    let state = |done: bool, now: bool| if done { "done" } else if now { "now" } else { "next" };    let mut steps = vec![        json!({ "label": say("step_received", &[]), "state": "done" }),        json!({ "label": say("step_copy", &[]), "state": state(!converting, converting) }),    ];    let subtitles_now = matches!(work.as_str(), "finding" | "generating" | "translating");    if matches!(work.as_str(), "find" | "generate" | "file") || subtitles_now || (work == "ready" && converting) {        steps.push(json!({ "label": say("step_subtitles", &[]), "state": state(work == "ready", subtitles_now && !converting) }));    }    // What waits for the Mac before it: rows still converting that came in earlier.    let created = text_of(&row, "created_at");    let mut ahead = 0usize;    client        .read_rows("cinemas.preparing", &mut |ctx| {            let args = [rusqlite::types::Value::Text(created.clone()), rusqlite::types::Value::Text(id.clone())];            for waiting in [FILM_TABLE, EPISODE_TABLE] {                if holds_table(ctx, waiting)? {                    ahead += rows_where(ctx, waiting, "id", "needs_mac = 1 AND created_at < ? AND id <> ?", &args)?.len();                }            }            Ok(Value::Null)        })        .map_err(unreadable)?;    let queue = if !converting { None } else if ahead == 0 { Some(say("queue_none", &[])) } else { Some(say("queue_some", &[("n", &ahead.to_string())])) };    let head = say(if table == EPISODE_TABLE { "preparing_episode" } else { "preparing_film" }, &[]);    Ok(json!({ "head": head, "steps": steps, "queue": queue, "note": say("preparing_note", &[]), "ready": !converting }))}// ---- the remote ----fn remote(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let (table, id) = named(request, "cinemas.remote")?;    let at = request.get("at_s").and_then(Value::as_f64).filter(|n| n.is_finite() && *n >= 0.0).unwrap_or(0.0);    // What plays now, hidden or not (review A6): the remote names only the title on the TV.    let library = Library::read_all(client)?;    let by_id = library.by_id();    let found = by_id.get(id.as_str()).copied().filter(|title| title.table == table).ok_or_else(|| MethodError::new("not_found", say("no_title", &[])))?;    let whole = request.get("length_s").and_then(Value::as_f64).filter(|n| n.is_finite() && *n > 0.0).or_else(|| found.minutes.map(|m| m * 60.0));    let playing = match request.get("device").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) {        Some(device) => say("remote_on", &[("device", device)]),        None => say("remote_on_tv", &[]),    };    let mut title = found.title.clone();    let mut caption = found.year.clone();    let mut next = Value::Null;    if table == EPISODE_TABLE {        let mut episodes = Vec::new();        let mut series = String::new();        client            .read_rows("cinemas.remote", &mut |ctx| {                let held = super::super::film_player::row(ctx, EPISODE_TABLE, "id, series, season", &id)?;                series = super::super::film_player::series_of(ctx, &held)?;                episodes = super::super::film_player::episodes_of(ctx, &series)?;                Ok(Value::Null)            })            .map_err(unreadable)?;        if let Some(place) = episodes.iter().position(|episode| episode.id == id) {            let this = &episodes[place];            let named = if this.title.trim().is_empty() { say("episode_caption", &[("season", &this.season.to_string()), ("episode", &this.number.to_string())]) } else { this.title.clone() };            caption = Some(say("remote_episode", &[("series", &found.title), ("season", &this.season.to_string()), ("episode", &this.number.to_string())]));            title = named;            if let Some(after) = episodes[place + 1..].iter().find(|episode| !episode.file.trim().is_empty()) {                next = json!({ "table": EPISODE_TABLE, "id": after.id, "label": say("remote_next", &[]) });            }        }    }    // A hidden title on the TV (HIDE FROM SCREEN): the remote says the app's name, never the title or its series.    let shut = super::super::cinemas_home::hidden_titles_of(client)?;    if shut.contains(&found.id) || shut.contains(&found.art_key) {        title = super::super::film_player::line("stream.hidden_now_playing", &[]).unwrap_or_else(|_| "Cinemas".to_string());        caption = None;    }    Ok(json!({        "playing": playing,        "title": title,        "caption": caption,        "at": clock(at),        "left": whole.map(|whole| say("remote_left", &[("left", &clock((whole - at).max(0.0)))])),        "next": next,        "volume": say("remote_volume", &[]),    }))}