Cotton code
864 lines · 40.2 KB · RustRaw
//! Films on this phone: the stream address the object signs, and what this//! device alone keeps of each film and episode (Cinemas definition, 4 Nov//! 2026, section 7).//!//! - `media.stream { key }` → `{ url, expires_at }`: a film's HLS master, a//!   whole film's file (`films/<id>/whole.<ext>`), a book's or a song's,//!   signed at the person's own object (`POST /v1/media/stream`, through the//!   door `personal.connect` held, [`ObjectDoor`]). The player reads the//!   address (and every playlist and segment under a master) with no bearer;//!   the credential never reaches Swift.//! - `films.here.read { key }` → `{ key, bookmark, state }`: what this device//!   keeps of a film's file, by its key: an HLS master kept as Apple's asset//!   bundle (its bookmark), or a whole file kept in this phone's media store.//! - `films.here.write { key, state, bookmark?, from? }`: `state` keeping,//!   kept or null. A kept master names its bundle's bookmark; a kept whole//!   file names the downloaded file (`from`), adopted into the media store as//!   a song's is.//! - `films.remove { key }`: a whole file's Remove download, as//!   `songs.remove` (a master's bundle is deleted by the platform, then//!   `films.here.write { state: null }`).//! - `films.keepEverything { on? }` → `{ on, said? }`: this phone's Keep//!   everything, read without `on`, set with it.//!//! WHAT IS KEPT HERE NEVER SYNCS: `films-here.json` beside the client's other//! device-local files. Where a film was stopped is NOT kept here: it is the//! record's `position`, which the player writes (`film_player`) and every//! phone reads.//!//! A film's or an episode's record answers what this device keeps of it in//! `on_phone` (absent, keeping, kept) when it has a file; a season and a//! series answer from their episodes (kept when every episode with a file//! is, keeping while any comes down). Their acts (Keep on phone, Keep season,//! Keep series, Remove download) are offered by that column, so which one a//! card shows is the definition's, not the app's.use std::collections::BTreeMap;use std::path::Path;use std::sync::{Arc, Mutex, MutexGuard};use serde::{Deserialize, Serialize};use serde_json::{json, Map, Value};use cotton_client::media::storage::EvictOneError;use cotton_client::media::ObjectMediaTransport;use cotton_client::transport::ServerRefusal;use super::songs::{data_of, records_of, rows_where, text_of, Row};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::phone::personal_object::ObjectDoor;use crate::shell::client::ClientController;pub const METHODS: [&str; 8] = ["media.stream", "films.here.read", "films.here.write", "films.remove", "films.keepEverything", "films.keeping", "films.onPhone", "films.keepPlan"];/// The storage budgets this phone may keep films within, in GB (Cinemas/// definition, section 7); the first is the default.pub const BUDGETS_GB: [u32; 4] = [64, 128, 256, 32];/// The device-local file, in the client's own folder.pub const FILE: &str = "films-here.json";/// The tables whose records are films (`film.json`, `film_season.json`,/// `film_episode.json`), and the column a film or an episode plays from.pub const FILM_TABLE: &str = "film";pub const SEASON_TABLE: &str = "film_season";pub const EPISODE_TABLE: &str = "film_episode";pub const TABLES: [&str; 3] = [FILM_TABLE, SEASON_TABLE, EPISODE_TABLE];pub const PLAYER_COLUMN: &str = "file";/// What a film's record says of this device (`film.json`'s `on_phone`).pub const ON_PHONE: &str = "on_phone";pub const ABSENT: &str = "absent";pub const KEEPING: &str = "keeping";pub const KEPT: &str = "kept";/// A list read by `on_phone` that this device keeps nothing of reads this/// key, which no film holds.pub const NOTHING_KEPT: &str = "nothing-kept";/// A film's file the player streams: an HLS master playlist.pub const MASTER_SUFFIX: &str = ".m3u8";/// The flows the acts open (`settings.openFlow`), each with what `on_phone`/// says while it is there to take: Keep on phone (a film, an episode), Keep/// season and Keep series download, Remove download deletes.pub const FLOWS: [&str; 2] = ["keepFilm", "removeFilmDownload"];fn flow_holds(flow: &str) -> &'static [&'static str] {    match flow {        "keepFilm" => &[ABSENT],        "removeFilmDownload" => &[KEEPING, KEPT],        _ => &[],    }}/// A film's flow comes only from a film's, a season's or an episode's own/// record, and only while what this device keeps of it says the act is there/// to take — the `on_phone` its acts are offered by — so no page can make the/// phone download.pub(crate) fn flow_origin(client: &ClientController, flow: &str, table: &str, id: &str) -> Result<(), MethodError> {    if !TABLES.contains(&table) {        return Err(MethodError::new("bad_request", "this flow comes only from a film's, a season's or an episode's own record"));    }    let record = crate::phone::records::call(client, "records.get", &json!({"table": table, "id": id}))?;    let on_phone = record["data"][ON_PHONE].as_str().unwrap_or_default();    if !flow_holds(flow).contains(&on_phone) {        return Err(MethodError::new("flow_refused", "this film is not one this act is for just now"));    }    Ok(())}/// Serializes read-modify-write of the file in this process.static WRITE_LOCK: Mutex<()> = Mutex::new(());/// What this device keeps of one film's file.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]pub struct Here {    /// A master's kept bundle's bookmark, base64, as the platform made it.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub bookmark: Option<String>,    /// [`KEEPING`] or [`KEPT`].    #[serde(default, skip_serializing_if = "Option::is_none")]    pub state: Option<String>,}#[derive(Debug, Clone, Default, Serialize, Deserialize)]struct Stored {    #[serde(default)]    keep_everything: bool,    /// Downloads may use mobile data; Wi-Fi only when false (the default).    #[serde(default)]    cellular: bool,    /// The most this phone keeps of films, in GB; absent is the default.    #[serde(default, skip_serializing_if = "Option::is_none")]    budget_gb: Option<u32>,    #[serde(default)]    films: BTreeMap<String, Here>,}pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    let client = handle.client();    match method {        "media.stream" => {            let door = client                .object_door()                .ok_or_else(|| MethodError::new("not_connected", "this phone is not connected to its database yet"))?;            stream(&door, request)        }        "films.here.read" => read(&client, request),        "films.here.write" => write(&client, request),        "films.remove" => remove(&client, request),        "films.keepEverything" => keep_everything(&client, request),        "films.keeping" => keeping(&client, request),        "films.onPhone" => on_phone_counts(&client),        "films.keepPlan" => keep_plan(&client, request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a films method"))),    }}fn bad(why: &str) -> MethodError {    MethodError::new("bad_request", why.to_string())}/// `media.stream` through a NAMED door: a suite drives one over a scripted/// exchange.pub fn stream(door: &ObjectDoor, request: &Value) -> Result<Value, MethodError> {    let key = streamed_key(request)?;    let transport = ObjectMediaTransport::new(door.address.clone(), Arc::clone(&door.exchange), door.credential.clone());    let grant = transport.stream(key).map_err(refused)?;    Ok(json!({ "url": grant.url, "expires_at": grant.expires_at }))}/// The object's refusal by its own word, its status beside it; a request that/// reached nothing is `offline`.fn refused(refusal: ServerRefusal) -> MethodError {    let code = match (refusal.status, refusal.code.as_deref()) {        (0, _) => "offline".to_string(),        (_, Some(code)) if !code.is_empty() => code.to_string(),        (status, _) => format!("http_{status}"),    };    MethodError::new(&code, refusal.message).with_details(json!({ "status": refusal.status }))}fn key_of<'a>(request: &'a Value, allowed: &[&str]) -> Result<&'a str, MethodError> {    let fields = request.as_object().ok_or_else(|| bad("a films method takes an object"))?;    if fields.keys().any(|key| !allowed.contains(&key.as_str())) {        return Err(bad("a films method has an unknown field"));    }    fields        .get("key")        .and_then(Value::as_str)        .map(str::trim)        .filter(|key| !key.is_empty())        .ok_or_else(|| bad("a film is named by its file's key"))}/// A key the object signs an address for: a film's HLS master or whole/// file, or a book's or a song's one file, which the phone plays or/// downloads in the background from it.fn streamed_key(request: &Value) -> Result<&str, MethodError> {    use cotton_core::media::keys::MediaKind;    let key = key_of(request, &["key"])?;    let whole_file = cotton_core::media::keys::media_kind_of_verified_key(key)        .is_ok_and(|kind| matches!(kind, MediaKind::Book | MediaKind::Song));    if !streams(key) && !whole(key) && !whole_file {        return Err(bad("only a film's stream or file, a book's or a song's file streams"));    }    Ok(key)}/// A key naming a film's file this device may keep: a master or a whole file.fn film_key<'a>(request: &'a Value, allowed: &[&str]) -> Result<&'a str, MethodError> {    let key = key_of(request, allowed)?;    if !streams(key) && !whole(key) {        return Err(bad("only a film's stream or whole file is kept"));    }    Ok(key)}/// Whether `file` is a film the player streams as HLS.pub fn streams(file: &str) -> bool {    file.trim().to_ascii_lowercase().ends_with(MASTER_SUFFIX)}/// Whether `file` is a film kept whole: `<db>/films/<id>/whole.<ext>`.pub fn whole(file: &str) -> bool {    let parts: Vec<&str> = file.trim().split('/').collect();    matches!(parts.as_slice(), [db, "films", id, name] if !db.is_empty() && !id.is_empty()        && name.strip_prefix("whole.").is_some_and(|ext| cotton_core::films::WHOLE_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str())))}fn read(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let key = film_key(request, &["key"])?;    let here = stored(client)?.films.remove(key).unwrap_or_default();    Ok(answer(key, &here))}fn answer(key: &str, here: &Here) -> Value {    json!({ "key": key, "bookmark": here.bookmark, "state": here.state })}pub(crate) fn write(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let key = film_key(request, &["key", "state", "bookmark", "from"])?.to_string();    let state = match request.get("state") {        None => return Err(bad("films.here.write names the state, or null")),        Some(Value::Null) => None,        Some(Value::String(state)) if state == KEEPING || state == KEPT => Some(state.clone()),        Some(_) => return Err(bad("a film is keeping or kept on this phone")),    };    let kept = state.as_deref() == Some(KEPT);    if whole(&key) {        if request.get("bookmark").is_some() {            return Err(bad("a whole film is kept as a file, not a bundle"));        }        // RULE (owner on Cotton Cinemas 1.0 (4), 7 Nov 2026): a whole file        // whose record holds no digest is refused before it comes down, in a        // person's words — never a download refused once it has landed.        if state.as_deref() == Some(KEEPING) { digest_of(client, &key)?; }        match request.get("from") {            None => {}            Some(Value::String(from)) if kept && !from.trim().is_empty() => {                super::media::adopt_download(client, &key, Path::new(from.trim()), super::media::Expected::Held(digest_of(client, &key)?))?;            }            Some(_) => return Err(bad("`from` is the downloaded file's path, given with kept")),        }        let now = super::songs::iso_now(client)?;        client            .with_writer(|f| {                if kept && super::media::local_path_of(f.driver, &key).is_none() {                    return Ok(Err(MethodError::new("not_here", "a film is kept only once its file is on this phone")));                }                cotton_store::media_ledger::set_media_pinned(f.driver, &key, kept, &now).map_err(|error| error.to_string())?;                Ok(Ok(()))            })            .map_err(|reason| MethodError::new("unwritable", reason))??;    } else if request.get("from").is_some() {        return Err(bad("a stream is kept as its bundle, named by its bookmark"));    }    let here = {        let _guard = write_lock();        let mut all = stored(client)?;        let mut here = all.films.remove(&key).unwrap_or_default();        here.state = state;        if let Some(bookmark) = request.get("bookmark") {            here.bookmark = match bookmark {                Value::Null => None,                value => Some(value.as_str().filter(|text| !text.is_empty()).ok_or_else(|| bad("a bookmark is the platform's bytes, base64"))?.to_string()),            };        }        if here.state.is_none() {            here.bookmark = None;        }        if streams(&key) && here.state.as_deref() == Some(KEPT) && here.bookmark.is_none() {            return Err(bad("a kept film names its bundle"));        }        if here != Here::default() {            all.films.insert(key.clone(), here.clone());        }        write_locked(client, &all)?;        here    };    changed(client);    Ok(answer(&key, &here))}/// The film tables read again: their cards' acts follow `on_phone`./// The digest the film or episode playing `key` holds (`sha256`, stamped as/// its file came in): what a download of it must be.fn digest_of(client: &ClientController, key: &str) -> Result<String, MethodError> {    let mut digest = None;    let mut title = String::new();    client        .read_rows("films.here.write", &mut |ctx| {            let args = [rusqlite::types::Value::Text(key.to_string())];            let rows: Vec<_> = rows_where(ctx, FILM_TABLE, "sha256, title", "file = ?", &args)?                .into_iter()                .chain(rows_where(ctx, EPISODE_TABLE, "sha256, title", "file = ?", &args)?)                .collect();            title = rows.iter().map(|row| text_of(row, "title")).find(|title| !title.trim().is_empty()).unwrap_or_default();            digest = rows.iter().map(|row| text_of(row, "sha256")).find(|sha| !sha.is_empty());            Ok(Value::Null)        })        .map_err(|why| MethodError::new("unreadable", why))?;    match digest {        Some(digest) => Ok(digest),        None => {            let said = if title.trim().is_empty() { super::film_player::line("keep.unchecked_untitled", &[])? } else { super::film_player::line("keep.unchecked", &[("title", title.trim())])? };            Err(MethodError::new("no_digest", said))        }    }}fn changed(client: &ClientController) {    if let Ok(workspace) = client.with_file(|file| Ok::<String, String>(file.workspace_id.to_string())) {        let mut tables: Vec<String> = TABLES.iter().map(|table| format!("cotton_{table}")).collect();        tables.push("_media".into());        client.emit_data(&workspace, tables, "local");    }}fn remove(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let key = film_key(request, &["key"])?.to_string();    if !whole(&key) {        return Err(bad("a stream's bundle is removed by the platform; this removes a whole film's file"));    }    let device = client.self_device_id().ok_or_else(not_backed_up)?;    let now = client.clock().now().timestamp_millis();    let mut ids = cotton_client::seams::op_ids(client.random());    let freed = client        .with_writer(|f| {            Ok(cotton_client::media::storage::evict_one(                f.driver,                f.workspace_id,                &device,                client.layout(),                &cotton_client::media::SystemEvictDisk,                &key,                now,                &mut ids,                super::storage::held(f),            ))        })        .map_err(|reason| MethodError::new("unwritable", reason))?;    let freed_bytes = freed.map_err(|error| match error {        EvictOneError::NotBackedUp => not_backed_up(),        EvictOneError::SharedFileKept(_) => MethodError::new("kept_by_another", "another record keeps this film's file on this phone"),        EvictOneError::OutsideMediaFolder => MethodError::new("refused", error.to_string()),        EvictOneError::Failed(why) => MethodError::new("unwritable", why),    })?;    {        let _guard = write_lock();        let mut all = stored(client)?;        if all.films.remove(&key).is_some() {            write_locked(client, &all)?;        }    }    changed(client);    client.nudge_sync();    Ok(json!({ "key": key, "freed_bytes": freed_bytes }))}fn not_backed_up() -> MethodError {    MethodError::new("not_backed_up", "This film's file has not synced yet, so it stays on this phone.")}/// Whether this phone keeps every film.pub(crate) fn keeps_everything(client: &ClientController) -> Result<bool, MethodError> {    Ok(stored(client)?.keep_everything)}fn keep_everything(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = request.as_object().ok_or_else(|| bad("films.keepEverything takes an object"))?;    if fields.keys().any(|key| key != "on") {        return Err(bad("films.keepEverything takes only `on`"));    }    match fields.get("on") {        None | Some(Value::Null) => Ok(json!({ "on": keeps_everything(client)? })),        Some(Value::Bool(on)) => call_keep_everything(client, *on),        Some(_) => Err(bad("`on` is true or false")),    }}/// This phone's Keep everything set, answered with the words it says.pub(crate) fn call_keep_everything(client: &ClientController, on: bool) -> Result<Value, MethodError> {    {        let _guard = write_lock();        let mut all = stored(client)?;        all.keep_everything = on;        write_locked(client, &all)?;    }    let said = super::film_player::line(if on { "acts.keeping_everything" } else { "acts.stopped_keeping_everything" }, &[])?;    Ok(json!({ "on": on, "said": said }))}/// This phone's keeping knobs, read with no fields, set with them:/// `{ keep_everything, cellular, budget_gb }`. Facts of this phone alone.fn keeping(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = request.as_object().ok_or_else(|| bad("films.keeping takes an object"))?;    if fields.keys().any(|key| key != "cellular" && key != "budget_gb") {        return Err(bad("films.keeping takes cellular and budget_gb"));    }    let _guard = write_lock();    let mut all = stored(client)?;    if let Some(cellular) = fields.get("cellular") {        all.cellular = cellular.as_bool().ok_or_else(|| bad("cellular is true or false"))?;    }    if let Some(budget) = fields.get("budget_gb") {        let budget = budget.as_u64().and_then(|gb| u32::try_from(gb).ok()).filter(|gb| BUDGETS_GB.contains(gb)).ok_or_else(|| bad("a budget is 32, 64, 128 or 256 GB"))?;        all.budget_gb = Some(budget);    }    if !fields.is_empty() {        write_locked(client, &all)?;    }    Ok(json!({ "keep_everything": all.keep_everything, "cellular": all.cellular, "budget_gb": all.budget_gb.unwrap_or(BUDGETS_GB[0]) }))}/// This phone's keeping knobs, as the tool acts' status reads them.pub(crate) fn call_keeping(client: &ClientController) -> Result<Value, MethodError> {    keeping(client, &json!({}))}/// Turn this phone's mobile-data rule over, answered with its words.pub(crate) fn turn_cellular(client: &ClientController) -> Result<Value, MethodError> {    let on = !stored(client)?.cellular;    keeping(client, &json!({ "cellular": on }))?;    let said = super::film_player::line(if on { "keep.cellular_on" } else { "keep.cellular_off" }, &[])?;    Ok(json!({ "on": on, "said": said }))}/// Step this phone's storage budget to the next of [`BUDGETS_GB`] in size.pub(crate) fn next_budget(client: &ClientController) -> Result<Value, MethodError> {    let held = stored(client)?.budget_gb.unwrap_or(BUDGETS_GB[0]);    let mut sizes = BUDGETS_GB;    sizes.sort_unstable();    let next = sizes.iter().copied().find(|gb| *gb > held).unwrap_or(sizes[0]);    keeping(client, &json!({ "budget_gb": next }))?;    Ok(json!({ "budget_gb": next, "said": budget_said(next)? }))}/// The budget's words: "Keep at most 64 GB".pub(crate) fn budget_said(gb: u32) -> Result<String, MethodError> {    super::film_player::line("keep.budget", &[("size", &format!("{gb} GB"))])}/// What this phone keeps, for On this phone's top line, read as its list is/// (`narrow_where`, kept and keeping): the films it lists, the episodes kept/// beside them (a series holds no file of its own, so it is never counted as/// one), and the bytes of the whole files kept (a stream's bundle is the/// platform's to measure).pub(crate) fn on_phone_counts(client: &ClientController) -> Result<Value, MethodError> {    let all = stored(client)?;    let listed: Vec<String> = all.films.iter().filter(|(_, here)| here.state.as_deref().is_some_and(|state| state == KEPT || state == KEEPING)).map(|(key, _)| key.clone()).collect();    if listed.is_empty() {        return Ok(json!({ "films": 0, "episodes": 0, "bytes": 0 }));    }    let (mut films, mut episodes) = (0usize, 0usize);    let mut hidden_files: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();    client        .read_rows("films.onPhone", &mut |ctx| {            let marks = vec!["?"; listed.len()].join(", ");            let args: Vec<rusqlite::types::Value> = listed.iter().cloned().map(rusqlite::types::Value::Text).collect();            // Hidden titles are not counted outside Hidden, nor their bytes (re-review item 3).            let shut = super::cinemas_home::hidden_titles(ctx)?;            let mut count = |table: &str| -> Result<usize, String> {                let rows = rows_where(ctx, table, "id, file", &format!("file IN ({marks})"), &args)?;                let mut n = 0;                for row in rows {                    if shut.contains(&text_of(&row, "id")) {                        hidden_files.insert(text_of(&row, "file"));                    } else {                        n += 1;                    }                }                Ok(n)            };            films = count(FILM_TABLE)?;            episodes = count(EPISODE_TABLE)?;            Ok(Value::Null)        })        .map_err(|why| MethodError::new("unreadable", why))?;    let kept: Vec<String> = kept_keys(client)?.into_iter().filter(|key| !hidden_files.contains(key)).collect();    let bytes = client        .with_writer(|f| {            let mut bytes = 0u64;            for key in kept.iter().filter(|key| whole(key)) {                if let Some(row) = cotton_store::media_ledger::media_by_key(f.driver, key).map_err(|error| error.to_string())? {                    bytes += u64::try_from(row.size_bytes).unwrap_or(0);                }            }            Ok(bytes)        })        .map_err(|reason| MethodError::new("unreadable", reason))?;    Ok(json!({ "films": films, "episodes": episodes, "bytes": bytes }))}/// One file a keep brings down: its record, its key, its title, whether it is/// a stream (a master the platform keeps as its own bundle) or a whole file,/// and the bytes it is guessed to take (its length at its bitrate).#[derive(Debug, Clone, PartialEq)]struct Keepable {    table: &'static str,    id: String,    key: String,    title: String,    bytes: u64,}impl Keepable {    fn of(table: &'static str, row: &Row) -> Option<Keepable> {        let key = text_of(row, PLAYER_COLUMN);        if key.trim().is_empty() { return None }        let number = |column: &str| row.get(column).and_then(Value::as_f64).filter(|n| n.is_finite() && *n > 0.0);        let bytes = match (number("minutes"), number("bitrate")) {            (Some(minutes), Some(bitrate)) => (minutes * 60.0 * bitrate * 1000.0 / 8.0) as u64,            _ => 0,        };        Some(Keepable { table, id: text_of(row, "id"), key, title: text_of(row, "title"), bytes })    }}const KEEPABLE_COLUMNS: &str = "id, file, title, minutes, bitrate";/// `films.keepPlan { table, id } | { everything: true }, bundle_bytes? }` —/// what a keep brings down, decided here so no shell counts or budgets/// (Android Cinemas, 12 Nov 2026). Keep on phone, Keep season and Keep/// series name a record: a film its own file, a series every episode of it in/// its seasons' order, a season its episodes, an episode its own. Keep/// everything (`everything`, only while it is on) names every film and/// episode. Of those, the ones this phone keeps nothing of yet are taken in/// order while they fit the budget beside what it keeps already (the whole/// files' bytes, and `bundle_bytes`, the kept streams' bundles the platform/// measured); the first that would pass it stops the plan, and the plan says/// so in the kit's words (`refusal`). Answers `{ files: [{ table, id, key,/// title, streams }], cellular, refusal? }`; the shell marks each keeping/// (`films.here.write`) as it starts it. With `held`, Remove download's: the/// record's files this phone keeps or is keeping, budget aside.fn keep_plan(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = request.as_object().ok_or_else(|| bad("films.keepPlan takes an object"))?;    if let Some(unknown) = fields.keys().find(|key| !["table", "id", "everything", "bundle_bytes", "held"].contains(&key.as_str())) {        return Err(bad(&format!("films.keepPlan takes table and id, or everything; and bundle_bytes — not {unknown}")));    }    let all = stored(client)?;    let everything = fields.get("everything").and_then(Value::as_bool).unwrap_or(false);    let asked: Vec<Keepable> = if everything {        if !all.keep_everything { return Ok(json!({ "files": [], "cellular": all.cellular })) }        // HIDDEN (review A4): Keep everything never hands the shell a hidden title's name for its download queue; one        // is kept from inside Hidden, by its own page.        let shut = super::cinemas_home::hidden_titles_of(client)?;        every_keepable(client)?.into_iter().filter(|film| !shut.contains(&film.id)).collect()    } else {        let table = fields.get("table").and_then(Value::as_str).filter(|table| TABLES.contains(table))            .ok_or_else(|| bad("films.keepPlan names a film's, a season's or an episode's table"))?;        let id = fields.get("id").and_then(Value::as_str).filter(|id| !id.trim().is_empty())            .ok_or_else(|| bad("films.keepPlan names the record"))?;        keepable(client, table, id)?    };    let holds = |key: &str| all.films.get(key.trim()).and_then(|here| here.state.as_ref()).is_some();    if fields.get("held").and_then(Value::as_bool).unwrap_or(false) {        let files: Vec<Value> = asked.iter().filter(|film| holds(&film.key))            .map(|film| json!({ "table": film.table, "id": film.id, "key": film.key, "title": film.title, "streams": streams(&film.key) })).collect();        return Ok(json!({ "files": files, "cellular": all.cellular }));    }    let budget = u64::from(all.budget_gb.unwrap_or(BUDGETS_GB[0])) * 1_000_000_000;    let mut held = on_phone_counts(client)?["bytes"].as_u64().unwrap_or(0)        + fields.get("bundle_bytes").and_then(Value::as_u64).unwrap_or(0);    let mut files = Vec::new();    for film in asked {        if holds(&film.key) { continue }        if held + film.bytes > budget {            let size = format!("{} GB", all.budget_gb.unwrap_or(BUDGETS_GB[0]));            let refusal = super::film_player::line("keep.over_budget", &[("size", &size)])?;            return Ok(json!({ "files": files, "cellular": all.cellular, "refusal": refusal }));        }        held += film.bytes;        files.push(json!({ "table": film.table, "id": film.id, "key": film.key, "title": film.title, "streams": streams(&film.key) }));    }    Ok(json!({ "files": files, "cellular": all.cellular }))}/// The files one record names, in the order they are kept./// An episode's season's number: a computed lookup, so read through its season.fn season_order() -> String {    let (season, episode) = (cotton_tools::mcp::handlers::tables::made_table(SEASON_TABLE), cotton_tools::mcp::handlers::tables::made_table(EPISODE_TABLE));    format!("(SELECT s.number FROM {season} s WHERE s.id = {episode}.season)")}fn keepable(client: &ClientController, table: &str, id: &str) -> Result<Vec<Keepable>, MethodError> {    let mut found = Vec::new();    client        .read_rows("films.keepPlan", &mut |ctx| {            let one = vec![rusqlite::types::Value::Text(id.to_string())];            let episodes = |condition: &str| -> Result<Vec<Keepable>, String> {                Ok(rows_where(ctx, EPISODE_TABLE, KEEPABLE_COLUMNS, condition, &one)?.iter().filter_map(|row| Keepable::of(EPISODE_TABLE, row)).collect())            };            found = match table {                FILM_TABLE => {                    let rows = rows_where(ctx, FILM_TABLE, &format!("{KEEPABLE_COLUMNS}, kind"), "id = ?", &one)?;                    match rows.first() {                        Some(row) if text_of(row, "kind") == "series" => episodes(&format!("series = ? ORDER BY {}, number", season_order()))?,                        Some(row) => Keepable::of(FILM_TABLE, row).into_iter().collect(),                        None => Vec::new(),                    }                }                SEASON_TABLE => episodes("season = ? ORDER BY number")?,                _ => episodes("id = ?")?,            };            Ok(Value::Null)        })        .map_err(|why| MethodError::new("unreadable", why))?;    Ok(found)}/// Every film (a series holds no file of its own) and every episode, by title and order.fn every_keepable(client: &ClientController) -> Result<Vec<Keepable>, MethodError> {    let mut found = Vec::new();    client        .read_rows("films.keepPlan", &mut |ctx| {            let films = rows_where(ctx, FILM_TABLE, KEEPABLE_COLUMNS, "kind = 'film' ORDER BY title", &[])?;            let episodes = rows_where(ctx, EPISODE_TABLE, KEEPABLE_COLUMNS, &format!("1 = 1 ORDER BY series, {}, number", season_order()), &[])?;            found = films.iter().filter_map(|row| Keepable::of(FILM_TABLE, row))                .chain(episodes.iter().filter_map(|row| Keepable::of(EPISODE_TABLE, row))).collect();            Ok(Value::Null)        })        .map_err(|why| MethodError::new("unreadable", why))?;    Ok(found)}/// Mark files kept on this phone: a film brought in here is on it.pub(crate) fn mark_kept(client: &ClientController, keys: &[String]) -> Result<(), MethodError> {    if keys.is_empty() {        return Ok(());    }    {        let _guard = write_lock();        let mut all = stored(client)?;        for key in keys {            all.films.insert(key.clone(), Here { bookmark: None, state: Some(KEPT.to_string()) });        }        write_locked(client, &all)?;    }    changed(client);    Ok(())}/// Signed in, the films this phone kept stay kept under the object's keys:/// the backup re-keys each file (`<local>/films/…` becomes `<object>/films/…`),/// and a keep left under the old key names no record, so On this phone would/// list nothing this phone holds and the player would stream it.pub(crate) fn rekey_here(client: &ClientController, rekey: &dyn Fn(&str) -> String) -> Result<(), MethodError> {    let moved: Vec<(String, String)> = stored(client)?.films.keys().map(|key| (key.clone(), rekey(key))).filter(|(key, again)| key != again).collect();    if moved.is_empty() {        return Ok(());    }    let kept: Vec<String> = {        let _guard = write_lock();        let mut all = stored(client)?;        let mut kept = Vec::new();        for (key, again) in &moved {            let Some(here) = all.films.remove(key) else { continue };            if whole(again) && here.state.as_deref() == Some(KEPT) {                kept.push(again.clone());            }            all.films.insert(again.clone(), here);        }        write_locked(client, &all)?;        kept    };    let now = super::songs::iso_now(client)?;    client        .with_writer(|f| {            for key in &kept {                cotton_store::media_ledger::set_media_pinned(f.driver, key, true, &now).map_err(|error| error.to_string())?;            }            Ok(())        })        .map_err(|reason| MethodError::new("unwritable", reason))?;    changed(client);    Ok(())}// ── on_phone, answered ──────────────────────────────────────────────────────/// What a set of episodes' states says of their season or series.pub fn whole_state<'a>(states: impl IntoIterator<Item = Option<&'a str>>) -> Option<&'static str> {    let (mut all, mut kept, mut keeping) = (0, 0, 0);    for state in states {        all += 1;        match state {            Some(KEPT) => kept += 1,            Some(KEEPING) => keeping += 1,            _ => {}        }    }    match () {        _ if all == 0 => None,        _ if kept == all => Some(KEPT),        _ if keeping > 0 => Some(KEEPING),        _ => Some(ABSENT),    }}/// Fill `on_phone` on every record of a records answer of `table`: a film's/// or an episode's from its file, a season's and a series' from their/// episodes' files. A record with nothing to keep is left without it, so no/// act of keeping is offered on it.pub(crate) fn answer_on_phone(client: &ClientController, table: &str, answer: &mut Value) -> Result<(), MethodError> {    let kept = stored(client)?;    let state_of = |file: &str| kept.films.get(file.trim()).and_then(|here| here.state.as_deref()).unwrap_or(ABSENT);    let mut wholes = Vec::new();    for record in records_of(answer) {        let id = record.get("id").and_then(Value::as_str).map(str::to_string);        let Some(data) = data_of(record) else { continue };        data.remove(ON_PHONE);        let id = id.or_else(|| data.get("id").and_then(Value::as_str).map(str::to_string)).unwrap_or_default();        let file = data.get(PLAYER_COLUMN).and_then(Value::as_str).map(str::trim).filter(|file| streams(file) || whole(file));        match (table, file) {            (FILM_TABLE | EPISODE_TABLE, Some(file)) => {                data.insert(ON_PHONE.to_string(), Value::from(state_of(file)));            }            (FILM_TABLE, None) if data.get("kind").and_then(Value::as_str) == Some("series") => wholes.push(id),            (SEASON_TABLE, _) => wholes.push(id),            _ => {}        }    }    if wholes.is_empty() {        return Ok(());    }    let link = if table == SEASON_TABLE { "season" } else { "series" };    let mut files: BTreeMap<String, Vec<String>> = BTreeMap::new();    client        .read_rows("films.onPhone", &mut |ctx| {            let marks = vec!["?"; wholes.len()].join(", ");            let args: Vec<rusqlite::types::Value> = wholes.iter().cloned().map(rusqlite::types::Value::Text).collect();            for row in rows_where(ctx, EPISODE_TABLE, &format!("{link} AS whole, file"), &format!("{link} IN ({marks}) AND file IS NOT NULL AND file != ''"), &args)? {                files.entry(text_of(&row, "whole")).or_default().push(text_of(&row, "file"));            }            Ok(Value::Null)        })        .map_err(|why| MethodError::new("unreadable", why))?;    for record in records_of(answer) {        let id = record.get("id").and_then(Value::as_str).map(str::to_string);        let Some(data) = data_of(record) else { continue };        let id = id.or_else(|| data.get("id").and_then(Value::as_str).map(str::to_string)).unwrap_or_default();        let Some(episodes) = files.get(&id) else { continue };        if let Some(state) = whole_state(episodes.iter().map(|file| Some(state_of(file)))) {            data.insert(ON_PHONE.to_string(), Value::from(state));        }    }    Ok(())}/// A list of films or episodes read by `where.on_phone`, as the files this/// device keeps in those states (`songs::narrow_where`'s rule, for films)./// A series is in no such list: it holds no file of its own.pub(crate) fn narrow_where(client: &ClientController, args: &mut Map<String, Value>) -> Result<(), MethodError> {    if !matches!(args.get("table").and_then(Value::as_str), Some(FILM_TABLE | EPISODE_TABLE)) {        return Ok(());    }    let Some(conditions) = args.get_mut("where").and_then(Value::as_object_mut) else { return Ok(()) };    let Some(wanted) = conditions.remove(ON_PHONE) else { return Ok(()) };    let refused = || bad("on_phone reads absent, or keeping and kept");    let states: Vec<&str> = match &wanted {        Value::String(state) => vec![state.as_str()],        Value::Array(states) => states.iter().map(|state| state.as_str().ok_or_else(refused)).collect::<Result<_, _>>()?,        _ => return Err(refused()),    };    let stored = stored(client)?;    let keys = |held: &[&str]| -> Vec<Value> {        stored.films.iter().filter(|(_, here)| here.state.as_deref().is_some_and(|state| held.contains(&state))).map(|(key, _)| Value::from(key.as_str())).collect()    };    let condition = match states.as_slice() {        [ABSENT] => {            let held = keys(&[KEEPING, KEPT]);            if held.is_empty() {                json!({ "present": true })            } else {                json!({ "not": held })            }        }        states if !states.is_empty() && states.iter().all(|state| *state == KEEPING || *state == KEPT) => {            let held = keys(states);            Value::Array(if held.is_empty() { vec![Value::from(NOTHING_KEPT)] } else { held })        }        _ => return Err(refused()),    };    if conditions.contains_key(PLAYER_COLUMN) {        return Err(bad("a list reads on_phone or file, not both"));    }    conditions.insert(PLAYER_COLUMN.to_string(), condition);    Ok(())}/// The files this phone holds whole (kept, not still coming down): what On/// this phone's top line weighs./// What this device keeps of the film file `key` (the player's source).pub(crate) fn here(client: &ClientController, key: &str) -> Result<Here, MethodError> {    Ok(stored(client)?.films.remove(key.trim()).unwrap_or_default())}/// What this phone holds of each file it keeps or is keeping, by its key (`kept`, `keeping`): Cinemas' home reads it/// for the posters' marks (`phone::cinemas_home`).pub(crate) fn file_states(client: &ClientController) -> Result<BTreeMap<String, String>, MethodError> {    Ok(stored(client)?.films.into_iter().filter_map(|(key, here)| here.state.filter(|state| state == KEPT || state == KEEPING).map(|state| (key, state))).collect())}pub(crate) fn kept_keys(client: &ClientController) -> Result<Vec<String>, MethodError> {    Ok(stored(client)?.films.into_iter().filter(|(_, here)| here.state.as_deref() == Some(KEPT)).map(|(key, _)| key).collect())}fn path(client: &ClientController) -> std::path::PathBuf {    client.layout().client_dir().join(FILE)}fn stored(client: &ClientController) -> Result<Stored, MethodError> {    let path = path(client);    let bytes = match std::fs::read(&path) {        Ok(bytes) => bytes,        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Stored::default()),        Err(error) => return Err(MethodError::new("unreadable", format!("{FILE}: {error}"))),    };    serde_json::from_slice(&bytes).map_err(|error| MethodError::new("unreadable", format!("{FILE} is not valid JSON: {error}")))}fn write_locked(client: &ClientController, all: &Stored) -> Result<(), MethodError> {    let path = path(client);    if let Some(parent) = path.parent() {        std::fs::create_dir_all(parent).map_err(|error| MethodError::new("unwritable", format!("{FILE}: {error}")))?;    }    // The pid keeps a second Cotton process from renaming this one's file.    let partial = path.with_extension(format!("json.{}.partial", std::process::id()));    // not a copy: film files.    std::fs::write(&partial, serde_json::to_vec_pretty(all).expect("films serialise"))        .map_err(|error| MethodError::new("unwritable", format!("{FILE}: {error}")))?;    // not a copy: film files.    std::fs::rename(&partial, path).map_err(|error| MethodError::new("unwritable", format!("{FILE}: {error}")))}pub(crate) fn write_lock() -> MutexGuard<'static, ()> {    WRITE_LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())}#[cfg(test)]#[path = "films_tests.rs"]mod tests;