//! Cinemas' streaming home (CONTRACT-2.md, 26 Nov 2026; the owner: "Let people classify the films into groups they//! want… apart from the easy to identify defaults"). One read of the film tables' columns and his groups, answered in//! the shape both phones draw: a featured title, then rows of posters. No genres.//!//! ```text//! cinemas.home {} → { featured, rows: [{ id, title, group, count, items, more }], empty }//! cinemas.row { id, after? } → { id, title, items, next? } (60 a page)//! cinemas.season { id } → { season, episodes: [Item] }//! cinemas.search { q } → { items: [Item], groups: [{ id, name }] }//! cinemas.kind { id, to } → { id, kind } (film | series | clip; kept as his)//! cinemas.groups {} → { groups: [{ id, name, count }] } (his groups, in his order)//! cinemas.groupsOrder { order: [ids] } → { groups: [ids] } (the rows' order on home)//! cinemas.title { table, id } → { item, play, groups: [{ id, name, in }], seasons?, source?, subtitles? }//! ```//!//! **Item** (one poster): `{ table, id, title, year, kind, poster, backdrop, caption, progress, on_phone, preparing,//! from, minutes }`.//! - `kind` is film, series or clip for a `film` row, and episode for a `film_episode`.//! - `progress` is the share watched (0–1), set only while part-watched.//! - `on_phone` is kept or keeping, from this phone's own record of what it holds (`films::file_states`).//! - `preparing` is true while the Mac converts the upload (`needs_mac`).//! - `from` is who sent it.//!//! **The rows, in order.** Each automatic row is left out when empty://! 1. `carry_on`: part-watched films and episodes, the newest place first.//! 2. `recent`: newest added.//! 3. `films`: kind film, and anything of no kind, which sits here until he moves it.//! 4. `series`.//! 5. `videos`: kind clip, a web page's video.//! 6. `on_phone`.//! 7. `getting_ready`.//! 8. `from_friends`.//! 9. Then each of his groups, `group:<id>`, in his order. An empty group still stands, so he can fill it.//!//! **The featured title** is the newest part-watched title, else the newest added.//!//! **His kind correction stays.** Nothing later writes `kind`: Find details fills only empty columns, and `kind`//! always holds a value.use std::collections::{BTreeMap, BTreeSet};use serde_json::{json, Map, Value};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::tables::groups;usesuper::films::{EPISODE_TABLE, FILM_TABLE, SEASON_TABLE};usesuper::songs::{holds_table, rows_where, text_of, Row};usecrate::handle::CottonHandle;usecrate::methods::MethodError;usecrate::shell::client::ClientController;pubconst METHODS: [&str; 14] = ["cinemas.unlock", "cinemas.lock", "cinemas.home", "cinemas.row", "cinemas.season", "cinemas.search", "cinemas.kind", "cinemas.groups", "cinemas.groupsOrder", "groups.order", "cinemas.title", "cinemas.toEpisode", "cinemas.hide", "cinemas.hidden"];/// What a film row carries over when it becomes an episode: every column the two tables share (the file and all/// about it, where he stopped, its subtitles, who sent it), except the film's own catalogue ids and where its/// details were filled from, which named a film, not an episode. Its title becomes the episode's own title.const CARRIED: [&str; 32] = ["status", "file", "watched_on", "rating", "minutes", "synopsis", "chapters", "subtitles", "subtitle_work", "subtitle_note", "oshash","subtitle_choice", "subtitle_offset", "subtitle_given", "subtitle_given_language", "original", "original_bytes", "original_sha256","video_range", "sdr_variant", "position", "position_at", "needs_mac", "source_file", "sha256", "height", "bitrate", "on_phone","sent_by", "sent_by_number", "sent_at", "send_id",];/// The posters a home row carries; the row opened reads the rest.const ROW_ITEMS: usize = 20;/// A page of a row opened.const PAGE: usize = 60;/// The kinds a film row may be corrected to.const KINDS: [&str; 3] = ["film", "series", "clip"];const FILM_COLUMNS: &str = "id, title, year, kind, poster, backdrop, minutes, position, position_at, added_on, needs_mac, file, sent_by, created_at, director, uploader, status";const EPISODE_COLUMNS: &str = "id, title, number, season, series, still, minutes, position, position_at, needs_mac, file, sent_by, created_at, status";pubfn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {let client = handle.client();match method {"cinemas.home" => {let answer = home(&client)?;// FIRST FILL: the pictures this screen draws first, their thumbnails fetched before any other (CONTRACT-2),// on the network the shell says (`network`, `constrained`), as prepare decides.ifsuper::media_sweep::first_allowed(&client, request["network"].as_str(), request["constrained"].as_bool()) {super::media_sweep::first(&client, &account_of(&client), first_pictures(&answer)); }Ok(answer) }"cinemas.row" => row(&client, request),"cinemas.season" => season(&client, request),"cinemas.search" => search(&client, request),"cinemas.kind" => kind(&client, request),"cinemas.groups" => his_groups(&client, request),"cinemas.hide" => hide(&client, request),"cinemas.hidden" => hidden_place(&client, request),"cinemas.unlock" => unlock(&client, request),"cinemas.lock" => lock(&client),"cinemas.groupsOrder" | "groups.order" => groups_order(&client, request),"cinemas.title" => title(&client, request),"cinemas.toEpisode" => to_episode(&client, request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a cinemas method"))), }}fn say(line: &str, fills: &[(&str, &str)]) -> String { cotton_core::rules::shell_lines::LineSet::shipped("cinemas").and_then(|lines| lines.say(&format!("home.{line}"), fills)).unwrap_or_default()}fn bad(why: implInto<String>) -> MethodError {MethodError::new("bad_request", why)}fn unreadable(why: String) -> MethodError {MethodError::new("unreadable", why)}/// One title, as the core reads it once for every row.#[derive(Debug, Clone)]structTitle { table: &'static str, id: String, title: String, year: Option<String>, kind: String, poster: Option<String>, backdrop: Option<String>, caption: Option<String>, minutes: Option<f64>, position: Option<f64>, position_at: String, added: String, preparing: bool, file: String, from: Option<String>,/// Whose drawn picture it wears: a film its own id, an episode its series' (so it matches the series' poster). art_key: String,/// When the row was made (`created_at`): breaks a tie within an added day. made: String,/// Marked watched (its status), for a row's Not watched chip. watched: bool,/// Who made it, for Search's people and channels: a film's director, a video's channel (its uploader). director: Option<String>, uploader: Option<String>,}fn words(row: &Row, key: &str) -> Option<String> {Some(text_of(row, key)).map(|text| text.trim().to_string()).filter(|text| !text.is_empty())}fn number(row: &Row, key: &str) -> Option<f64> { row.get(key).and_then(|value| value.as_f64().or_else(|| value.as_str().and_then(|text| text.trim().parse().ok()))).filter(|n| n.is_finite())}fn truthy(row: &Row, key: &str) -> bool { matches!(row.get(key), Some(Value::Bool(true))) || matches!(row.get(key), Some(Value::Number(n)) if n.as_f64() == Some(1.0))}implTitle {fn film(row: &Row) -> Title {let kind = words(row, "kind").filter(|kind| KINDS.contains(&kind.as_str())).unwrap_or_else(|| "film".to_string());Title { table: FILM_TABLE, id: text_of(row, "id"), title: words(row, "title").unwrap_or_default(), year: words(row, "year"), kind, poster: words(row, "poster"), backdrop: words(row, "backdrop"), caption: None, minutes: number(row, "minutes"), position: number(row, "position"), position_at: text_of(row, "position_at"), added: words(row, "added_on").unwrap_or_else(|| text_of(row, "created_at")), made: text_of(row, "created_at"), preparing: truthy(row, "needs_mac"), file: text_of(row, "file"), from: words(row, "sent_by"), art_key: text_of(row, "id"), watched: text_of(row, "status") == "watched", director: words(row, "director"), uploader: words(row, "uploader"), } }/// An episode, its season's number and its series read off its season (`season_number` and `series_title` are/// worked out on a read, never stored): `seasons` maps a season's id to its number and its series' id, `series`/// a series' id to its title and poster.fn episode(row: &Row, seasons: &BTreeMap<String, (Option<f64>, String)>, series: &BTreeMap<String, (String, Option<String>)>) -> Title {let (season_number, series_id) = seasons.get(&text_of(row, "season")).cloned().unwrap_or((None, text_of(row, "series")));let (series_title, series_poster) = series.get(&series_id).cloned().map(|(title, poster)| (Some(title).filter(|t| !t.is_empty()), poster)).unwrap_or((None, None));let (season, episode) = (season_number.or_else(|| number(row, "season_number")), number(row, "number"));let mark = match (season, episode) { (Some(s), Some(e)) => Some(say("episode_caption", &[("season", &format!("{s:.0}")), ("episode", &format!("{e:.0}"))])), _ => None, };let own = words(row, "title");let caption = match (mark, own.clone()) { (Some(mark), Some(own)) => Some(format!("{mark} · {own}")), (mark, own) => mark.or(own), };Title { table: EPISODE_TABLE, id: text_of(row, "id"), title: series_title.or_else(|| words(row, "series_title")).or(own).unwrap_or_default(), year: None, kind: "episode".to_string(), poster: series_poster.or_else(|| words(row, "still")), backdrop: words(row, "still"), caption, minutes: number(row, "minutes"), position: number(row, "position"), position_at: text_of(row, "position_at"), added: text_of(row, "created_at"), made: text_of(row, "created_at"), preparing: truthy(row, "needs_mac"), file: text_of(row, "file"), from: words(row, "sent_by"), art_key: if series_id.is_empty() { text_of(row, "id") } else { series_id }, watched: text_of(row, "status") == "watched", director: None, uploader: None, } }/// The share watched while part-watched: a place past the first minute and short of the end.fn progress(&self) -> Option<f64> {let (at, minutes) = (self.position?, self.minutes?);let length = minutes * 60.0; (length > 0.0 && at > 0.0).then(|| (at / length).clamp(0.0, 1.0)).filter(|share| *share > 0.0 && *share < 0.97) }fn item(&self, states: &BTreeMap<String, String>) -> Value {let on_phone = states.get(self.file.trim()).cloned(); json!({"table": self.table, "id": self.id, "title": self.title, "year": self.year, "kind": self.kind,"poster": self.poster, "backdrop": self.backdrop, "caption": self.caption,"progress": self.progress().map(|p| (p * 1000.0).round() / 1000.0),"on_phone": on_phone, "preparing": self.preparing, "from": self.from,"minutes": self.minutes.map(|m| m.round()),"art": art(&self.art_key), }) }}/// The drawn picture for a title with none, or while its picture loads or fails (cinemas-3.html, every `.po`): two/// colours and one of nine shapes, the same on both phones and every time, chosen from the title's id. The phones/// draw it as CONTRACT-2 "The drawn picture" says (a 165° gradient from `a` at 15% to `b` at 130%, the shape in `b`,/// the foot's inner shadow and hairline, and on a poster the name).const ART_COLOURS: [(&str, &str); 22] = [ ("#14302e", "#d99a4e"), ("#3b1342", "#f27b5c"), ("#0e1c28", "#7f9f7a"), ("#0a0e28", "#6a8be0"), ("#2b1a12", "#d8b47c"), ("#0c2828", "#46b0a8"), ("#0f1f2e", "#95bfd8"), ("#1a0c05", "#ff9d40"), ("#05202a", "#33b4cc"), ("#0f2230", "#cfe0ea"), ("#101a14", "#9bb58a"), ("#130a20", "#a764ff"), ("#151515", "#a7a29c"), ("#18201a", "#b9d29a"), ("#1a1a1f", "#8d8fa6"), ("#1c1c1c", "#5d6b5d"), ("#1d0f2b", "#f0a35a"), ("#1e1a10", "#e3c46c"), ("#201608", "#c9a14a"), ("#2a0a1a", "#d94f8f"), ("#2a1405", "#e88c3c"), ("#3a0e0e", "#e8c547"),];const ART_SHAPES: [&str; 9] = ["sun", "hills", "stripe", "ring", "rain", "horizon", "kite", "lines", "arch"];fn art(key: &str) -> Value {// FNV-1a: small, stable, the same on every platform the core runs on.let hash = key.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));let (a, b) = ART_COLOURS[(hash % ART_COLOURS.len() as u64) as usize];let shape = ART_SHAPES[((hash >> 32) % ART_SHAPES.len() as u64) as usize]; json!({ "a": a, "b": b, "shape": shape })}/// Every season's number and its series' id, by the season's id.fn seasons_of(ctx: &Ctx<'_>) -> Result<BTreeMap<String, (Option<f64>, String)>, String> {if !holds_table(ctx, SEASON_TABLE)? {returnOk(BTreeMap::new()); }Ok(rows_where(ctx, SEASON_TABLE, "id, number, film", "1 = 1", &[])?.iter().map(|row| (text_of(row, "id"), (number(row, "number"), text_of(row, "film")))).collect())}/// Every film, series, video and episode, read once.structLibrary { films: Vec<Title>, episodes: Vec<Title>, groups: Vec<(String, String, Vec<String>)>,/// Inside Hidden: the hidden categories the Bin holds (still hiding their titles), listed there with Restore. binned: BTreeSet<String>,}/// THE predicate (HIDE FROM SCREEN, owner 27 Nov 2026; `cotton_tools::…::tables::hidden`): every Cinemas reader, every/// shared reader of his films, and the summaries ask it. A hidden film category hides its titles live or binned.pub(crate) use cotton_tools::mcp::handlers::tables::hidden::{hiding, Hiding};/// The ids of his hidden film categories, live or binned ([`hiding`]).pub(crate) fn hidden_groups(ctx: &Ctx<'_>) -> Result<BTreeSet<String>, String> {Ok(hiding(ctx)?.groups)}/// Every row hidden from the screen ([`hiding`]).pub(crate) fn hidden_titles(ctx: &Ctx<'_>) -> Result<BTreeSet<String>, String> {Ok(hiding(ctx)?.titles)}/// The lists this copy holds with no version read for them (HIDDEN 6; review 5). Harmless now: a change of one reads/// that row from the object first and goes held to its version (`ObjectTransport::object_row`). Read-only, for a/// look at a copy; the same query runs on a copy's file:////// `SELECT g.id FROM cotton_groups g LEFT JOIN _seal s ON s.tbl = 'record_group' AND s.row_id = g.id WHERE coalesce(s.version, 0) <= 0`pub(crate) const LISTS_WITHOUT_VERSION: &str ="SELECT g.id AS id FROM cotton_groups g LEFT JOIN _seal s ON s.tbl = 'record_group' AND s.row_id = g.id WHERE coalesce(s.version, 0) <= 0";/// How many lists this copy holds with no version read ([`LISTS_WITHOUT_VERSION`]); none before any seal state.pub(crate) fn lists_without_version(client: &ClientController) -> Result<usize, String> { client.with_writer(|replica| {if replica.driver.get("SELECT 1 AS here FROM sqlite_master WHERE name = '_seal'", &[]).map_err(|e| e.to_string())?.is_none() {returnOk(0); }Ok(replica.driver.all(LISTS_WITHOUT_VERSION, &[]).map_err(|e| e.to_string())?.len()) })}/// Every title hidden, read on its own.pub(crate) fn hidden_titles_of(client: &ClientController) -> Result<BTreeSet<String>, MethodError> {letmut out = BTreeSet::new(); client .read_rows("cinemas.hidden", &mut |ctx| { out = hidden_titles(ctx)?;Ok(Value::Null) }) .map_err(unreadable)?;Ok(out)}/// HIDDEN's unlock, held by the core (review of a8580dbc38, A5; re-review item 2): the shell asks `cinemas.unlock`/// only once the phone's own lock has passed (or says the phone has none, `no_lock`). It is this account's alone (its/// copy's folder and its credential: signed out, or another account, holds none; the core's sign-out shuts it too),/// lasts UNLOCK_LIFE from the unlock (no read renews it: a shell left refreshing in the background keeps nothing/// open; the shell asks the phone's lock again), and/// `cinemas.lock` (Hidden left, the app to the background) shuts it. No caller's word opens it: `hidden: true`/// without it is refused.static UNLOCK: std::sync::Mutex<BTreeMap<String, (std::time::Instant, bool)>> = std::sync::Mutex::new(BTreeMap::new());const UNLOCK_LIFE: std::time::Duration = std::time::Duration::from_secs(2 * 60);/// Whose unlock: this copy's folder and the credential it is signed in with (a hash; the credential is not kept).fn account_of(client: &ClientController) -> String {use std::hash::{Hashas _, Hasheras _};letmut hash = std::collections::hash_map::DefaultHasher::new(); client.object_door().map(|door| door.credential.clone()).unwrap_or_default().hash(&mut hash); format!("{}|{:x}", client.layout().client_dir().display(), hash.finish())}/// Whether Hidden is open now for this account (and whether it opened with no screen lock); `renew` when he opened/// something inside.fn unlocked(client: &ClientController, renew: bool) -> Option<bool> {let account = account_of(client);letmut held = UNLOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);// An account signed out, or another one, leaves nothing open. held.retain(|_, (at, _)| at.elapsed() < UNLOCK_LIFE);let (at, no_lock) = held.get_mut(&account)?;if renew { *at = std::time::Instant::now(); }Some(*no_lock)}/// Refused unless Hidden is open; `renew` as [`unlocked`].pub(crate) fn inside_hidden(client: &ClientController, renew: bool) -> Result<(), MethodError> { unlocked(client, renew).map(|_| ()).ok_or_else(|| MethodError::new("locked", said("hidden_locked", &[])))}/// `cinemas.unlock { no_lock? }`: Hidden opens for this account, after the phone's lock passed.fn unlock(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let no_lock = request.get("no_lock") == Some(&Value::Bool(true)); UNLOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(account_of(client), (std::time::Instant::now(), no_lock));Ok(json!({ "unlocked": true }))}/// A test's clock: this account's unlock made `by` older.#[cfg(test)]pub(crate) fn age_unlock(client: &ClientController, by: std::time::Duration) {ifletSome((at, _)) = UNLOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get_mut(&account_of(client)) { *at -= by; }}/// Hidden shut for this account: `cinemas.lock`, and the core's own sign-out.pub(crate) fn lock_account(client: &ClientController) { UNLOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&account_of(client));}/// `cinemas.lock {}`: Hidden shuts for this account.fn lock(client: &ClientController) -> Result<Value, MethodError> { UNLOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&account_of(client));Ok(json!({ "unlocked": false }))}/// Undo of a Hide (re-review item 1): the undo `cinemas.hide` hands back works once, for UNDO_LIFE, outside Hidden/// (Home's "… is hidden" toast is not inside it). Keyed by account and category; the token is only that undo's.static UNDOS: std::sync::Mutex<Vec<(String, String, String, std::time::Instant)>> = std::sync::Mutex::new(Vec::new());const UNDO_LIFE: std::time::Duration = std::time::Duration::from_secs(60);fn undo_token(client: &ClientController, group: &str) -> String {use std::hash::{Hashas _, Hasheras _};letmut hash = std::collections::hash_map::DefaultHasher::new(); (group, std::time::SystemTime::now(), std::process::id(), std::thread::current().id()).hash(&mut hash);let token = format!("{:016x}", hash.finish());letmut undos = UNDOS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); undos.retain(|(.., at)| at.elapsed() < UNDO_LIFE); undos.push((account_of(client), group.to_string(), token.clone(), std::time::Instant::now())); token}/// Whether `token` is a live undo of hiding `group`, spent if so.fn spend_undo(client: &ClientController, group: &str, token: &str) -> bool {let account = account_of(client);letmut undos = UNDOS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); undos.retain(|(.., at)| at.elapsed() < UNDO_LIFE);match undos.iter().position(|(a, g, t, _)| *a == account && g == group && t == token) {Some(at) => { undos.remove(at);true }None => false, }}implLibrary {/// The open library: every title and category outside Hidden (HIDDEN, CONTRACT-2.md).fn read(client: &ClientController) -> Result<Library, MethodError> {Library::read_in(client, false) }/// The library a call asks for: the hidden place's when it says `hidden: true` (the shell says so only inside/// Hidden, once the phone's lock has passed), else the open one.pub(crate) fn read_for(client: &ClientController, request: &Value) -> Result<Library, MethodError> {let inside = request.get("hidden") == Some(&Value::Bool(true));if inside { inside_hidden(client, false)?; }Library::read_in(client, inside) }/// Every title, open and hidden: for what plays now (the remote), never for a list.pub(crate) fn read_all(client: &ClientController) -> Result<Library, MethodError> {letmut all = Library::read_in(client, false)?;let shut = Library::read_in(client, true)?; all.films.extend(shut.films); all.episodes.extend(shut.episodes); all.groups.extend(shut.groups);Ok(all) }/// HIDDEN (owner, 26 Nov 2026): a title in ANY hidden category is hidden, and so is every episode of a series/// that is. Open (`hidden` false) holds every other title and the open categories; hidden holds the hidden titles/// and the hidden categories alone. Every Cinemas answer is made from one of the two, so none says a hidden title/// or a hidden category's name outside Hidden.fn read_in(client: &ClientController, hidden: bool) -> Result<Library, MethodError> {letmut out = Library { films: Vec::new(), episodes: Vec::new(), groups: Vec::new(), binned: BTreeSet::new() }; client .read_rows("cinemas.home", &mut |ctx| { out = Library::of(ctx, hidden)?;Ok(Value::Null) }) .map_err(unreadable)?;Ok(out) }fn of(ctx: &mutCtx<'_>, hidden: bool) -> Result<Library, String> {// A copy the Cinemas kit has not reached yet holds no film tables: it has no titles, which is the truth.if !holds_table(ctx, FILM_TABLE)? {returnOk(Library { films: Vec::new(), episodes: Vec::new(), groups: Vec::new(), binned: BTreeSet::new() }); }let films: Vec<Title> = rows_where(ctx, FILM_TABLE, FILM_COLUMNS, "1 = 1", &[])?.iter().map(Title::film).collect();let series: BTreeMap<String, (String, Option<String>)> = films.iter().map(|film| (film.id.clone(), (film.title.clone(), film.poster.clone()))).collect();let seasons = seasons_of(ctx)?;let episodes = if holds_table(ctx, EPISODE_TABLE)? { rows_where(ctx, EPISODE_TABLE, EPISODE_COLUMNS, "1 = 1", &[])?.iter().map(|row| Title::episode(row, &seasons, &series)).collect() } else { Vec::new() };let order = groups::list_order(ctx, FILM_TABLE).map_err(|failure| failure.to_string())?;// The one predicate, read once for the whole library.letHiding { groups: hidden_ids, titles: shut, .. } = hiding(ctx)?;let group_hidden = |_: &Ctx<'_>, id: &str| hidden_ids.contains(id);letmut his: Vec<(usize, String, String, Vec<String>, bool)> = groups::live_groups(ctx.read.driver(), Some(ctx.workspace_id))? .into_iter() .filter(|(_, data)| data.get("table").and_then(Value::as_str) == Some(FILM_TABLE) && data.get("where").is_none()) .map(|(id, data)| {let at = order.iter().position(|o| *o == id).unwrap_or(usize::MAX);let shut = group_hidden(ctx, &id); (at, id, groups::name_of(&data).to_string(), groups::members_of(&data), shut) }) .collect(); his.sort_by_key(|(at, ..)| *at);// An episode is hidden by itself or by its series (its art key is its series' id).let is_hidden = |title: &Title| shut.contains(&title.id) || (title.table == EPISODE_TABLE && shut.contains(&title.art_key));let films = films.into_iter().filter(|t| is_hidden(t) == hidden).collect();let episodes = episodes.into_iter().filter(|t| is_hidden(t) == hidden).collect();letmut groups: Vec<(String, String, Vec<String>)> = his.into_iter().filter(|g| g.4 == hidden).map(|(_, id, name, members, _)| (id, name, members)).collect();// Inside Hidden, a hidden category the Bin holds is listed too, after the live ones: it still hides its titles,// so this is where he finds them, restores it, or shows it again (core 3, M1).letmut binned = BTreeSet::new();if hidden {let not_live: Vec<String> = hidden_ids.iter().filter(|id| !groups.iter().any(|(gid, ..)| gid == *id)).cloned().collect();// THE Bin's gate (`hidden::bin_shows`, CORE 5 L4): this is the Bin inside Hidden reading a binned category.let gate = Hiding { groups: hidden_ids.clone(), ..Hiding::default() };let shown = |id: &str| cotton_tools::mcp::handlers::tables::hidden::in_hidden_bin(|| cotton_tools::mcp::handlers::tables::hidden::bin_shows(&gate, Some(id), &Map::new()));for id in not_live.iter().filter(|id| shown(id)) {ifletSome((data, Some(_))) = groups::group_of(ctx.read.driver(), id)? { groups.push((id.clone(), groups::name_of(&data).to_string(), groups::members_of(&data))); binned.insert(id.clone()); } } }Ok(Library { films, episodes, groups, binned }) }fn by_id(&self) -> BTreeMap<&str, &Title> {self.films.iter().chain(self.episodes.iter()).map(|title| (title.id.as_str(), title)).collect() }/// Every row's id, words and titles, in the home's order.fn rows(&self) -> Vec<(String, String, Option<String>, Vec<&Title>)> {fn newest<'a>(mut list: Vec<&'a Title>, key: fn(&Title) -> &str) -> Vec<&'a Title> {// A real library comes in a few big imports, most of it on one added day: within a day the row made// last comes first, not the alphabet (Cinemas lead, his library on build 19). list.sort_by(|a, b| key(b).cmp(key(a)).then_with(|| b.made.cmp(&a.made)).then_with(|| a.title.cmp(&b.title))); list }fn by_title(mut list: Vec<&Title>) -> Vec<&Title> { list.sort_by_key(|title| title.title.to_lowercase()); list }let shown: Vec<&Title> = self.films.iter().collect();let all: Vec<&Title> = self.films.iter().chain(self.episodes.iter()).collect();let carry_on = newest(all.iter().copied().filter(|title| title.progress().is_some() && title.kind != "series").collect(), |t| t.position_at.as_str());let recent = newest(shown.iter().copied().filter(|title| !title.added.is_empty()).collect(), |t| t.added.as_str());letmut rows = vec![ ("carry_on".to_string(), say("carry_on", &[]), None, carry_on), ("recent".to_string(), say("recent", &[]), None, recent), ("films".to_string(), say("films", &[]), None, by_title(shown.iter().copied().filter(|title| title.kind == "film").collect())), ("series".to_string(), say("series", &[]), None, by_title(shown.iter().copied().filter(|title| title.kind == "series").collect())), ("videos".to_string(), say("videos", &[]), None, newest(shown.iter().copied().filter(|title| title.kind == "clip").collect(), |t| t.added.as_str())), ("getting_ready".to_string(), say("getting_ready", &[]), None, by_title(all.iter().copied().filter(|title| title.preparing).collect())), ("from_friends".to_string(), say("from_friends", &[]), None, newest(all.iter().copied().filter(|title| title.from.is_some()).collect(), |t| t.added.as_str())), ]; rows.retain(|(_, _, _, titles)| !titles.is_empty());let by_id = self.by_id();for (id, name, members) in &self.groups {let titles: Vec<&Title> = members.iter().filter_map(|member| by_id.get(member.as_str()).copied()).collect(); rows.push((format!("group:{id}"), name.clone(), Some(id.clone()), titles)); } rows }}/// The phone's kept files' row, placed after the kinds: worked out here because it reads this phone's own record.fn with_on_phone<'a>(mut rows: Vec<(String, String, Option<String>, Vec<&'a Title>)>, library: &'a Library, states: &BTreeMap<String, String>) -> Vec<(String, String, Option<String>, Vec<&'a Title>)> {letmut kept: Vec<&Title> = library.films.iter().chain(library.episodes.iter()).filter(|title| states.contains_key(title.file.trim())).collect();if kept.is_empty() {return rows; } kept.sort_by_key(|title| title.title.to_lowercase());let at = rows.iter().position(|(id, ..)| id == "getting_ready" || id == "from_friends" || id.starts_with("group:")).unwrap_or(rows.len()); rows.insert(at, ("on_phone".to_string(), say("on_phone", &[]), None, kept)); rows}fn home(client: &std::sync::Arc<ClientController>) -> Result<Value, MethodError> {let library = Library::read(client)?;let states = super::films::file_states(client)?;if library.films.is_empty() && library.episodes.is_empty() && library.groups.is_empty() {returnOk(json!({ "featured": null, "rows": [], "empty": { "title": say("empty_title", &[]), "line": say("empty_line", &[]), "add": say("add", &[]) }, "received": super::cinemas_shared::received(client) })); }let rows = with_on_phone(library.rows(), &library, &states);// The featured title plays: the newest part-watched one, else the newest added that is not still on the Mac,// one with a picture first (a real library holds many without; Cinemas lead, build 19).fn pick<'a>(titles: &[&'a Title]) -> Option<&'a Title> {let playable: Vec<&Title> = titles.iter().copied().filter(|title| !title.preparing).collect(); playable.iter().copied().find(|title| title.backdrop.is_some() || title.poster.is_some()).or_else(|| playable.first().copied()).or_else(|| titles.first().copied()) }let featured = rows .iter() .find(|(id, ..)| id == "carry_on") .and_then(|(_, _, _, titles)| pick(titles).map(|title| (true, title))) .or_else(|| rows.iter().find(|(id, ..)| id == "recent").and_then(|(_, _, _, titles)| pick(titles).map(|title| (false, title)))) .map(|(carrying_on, title)| featured(title, carrying_on, &states));let answered: Vec<Value> = rows .iter() .map(|(id, words, group, titles)| { json!({ "id": id, "title": words, "group": group, "count": titles.len(),"items": titles.iter().take(ROW_ITEMS).map(|title| title.item(&states)).collect::<Vec<_>>(),"more": titles.len() > ROW_ITEMS }) }) .collect();Ok(json!({ "featured": featured, "rows": answered, "empty": null, "received": super::cinemas_shared::received(client) }))}/// Home's first pictures in Home's own order (CONTRACT-2, FIRST FILL): the featured title's backdrop (else its/// poster), then each row's items' posters (else backdrops), the rows as Home stands them (Carry on, Recently added,/// then the rest); at most `media_sweep::FIRST_KEYS`.pub(crate) fn first_pictures(home: &Value) -> Vec<String> {let art = |item: &Value, first: &str, then: &str| item[first].as_str().or_else(|| item[then].as_str()).map(str::to_string);letmut keys: Vec<String> = Vec::new(); keys.extend(art(&home["featured"]["item"], "backdrop", "poster"));for row in home["rows"].as_array().into_iter().flatten() { keys.extend(row["items"].as_array().into_iter().flatten().filter_map(|item| art(item, "poster", "backdrop"))); }super::media_sweep::first_chosen(keys)}fn clock(seconds: f64) -> String {let total = seconds.max(0.0).round() as u64;// As the phones' own clock writes a place: 4:05, and 1:12:04 past the hour (StreamShapesTest).let (h, m, s) = (total / 3600, (total % 3600) / 60, total % 60);if h > 0 { format!("{h}:{m:02}:{s:02}") } else { format!("{m}:{s:02}") }}fn featured(title: &Title, carrying_on: bool, states: &BTreeMap<String, String>) -> Value {let line = match (carrying_on, title.position, title.minutes) { (true, Some(at), Some(minutes)) => say("featured_progress", &[("at", &clock(at)), ("length", &clock(minutes * 60.0))]), _ if title.preparing => say("preparing", &[]), _ => title.caption.clone().or_else(|| title.year.clone()).unwrap_or_default(), };let play = if carrying_on { say("resume", &[]) } else { say("play", &[]) };// Nothing to say is null, never an empty line the phone would still draw.let line = Some(line).filter(|line| !line.trim().is_empty()); json!({ "item": title.item(states), "line": line, "play": play, "tv": say("tv", &[]), "playable": !title.preparing })}const CHIPS: [&str; 5] = ["all", "unwatched", "on_phone", "az", "newest"];fn row(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let id = request.get("id").and_then(Value::as_str).filter(|id| !id.trim().is_empty()).ok_or_else(|| bad("cinemas.row names its row: id"))?;// Where the page starts: `next` from the last page, as text (both phones keep it as text) or as a number.let after = request.get("after").and_then(|after| after.as_u64().or_else(|| after.as_str().and_then(|text| text.trim().parse().ok()))).unwrap_or(0) as usize;let library = Library::read_for(client, request)?;let states = super::films::file_states(client)?;let rows = with_on_phone(library.rows(), &library, &states);letSome((_, words, group, titles)) = rows.into_iter().find(|(row, ..)| row == id) else {returnOk(json!({ "id": id, "title": "", "items": [], "next": null })); };// The row's chips (cinemas-3.html 2): All, Not watched, On this phone, A–Z, Newest; one is on.let filter = request.get("filter").and_then(Value::as_str).filter(|f| CHIPS.contains(f)).unwrap_or("all");letmut titles: Vec<&Title> = match filter {"unwatched" => titles.into_iter().filter(|title| !title.watched).collect(),"on_phone" => titles.into_iter().filter(|title| states.contains_key(title.file.trim())).collect(), _ => titles, };match filter {"az" => titles.sort_by_key(|title| title.title.to_lowercase()),"newest" => titles.sort_by(|a, b| b.added.cmp(&a.added).then_with(|| b.made.cmp(&a.made))), _ => {} }let chips: Vec<Value> = CHIPS.iter().map(|chip| json!({ "id": chip, "label": say(&format!("chip_{chip}"), &[]), "on": *chip == filter })).collect();let page: Vec<Value> = titles.iter().skip(after).take(PAGE).map(|title| title.item(&states)).collect();let next = (after + PAGE < titles.len()).then(|| (after + PAGE).to_string());Ok(json!({ "id": id, "title": words, "group": group, "count": titles.len(), "chips": chips, "filter": filter, "items": page, "next": next }))}fn season(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let id = request.get("id").and_then(Value::as_str).filter(|id| !id.trim().is_empty()).ok_or_else(|| bad("cinemas.season names the season: id"))?.to_string();// A hidden series' season opens only inside Hidden (re-review item 3).letmut series_hidden = false; client .read_rows("cinemas.season", &mut |ctx| {let args = [rusqlite::types::Value::Text(id.clone())];ifletSome(season) = rows_where(ctx, SEASON_TABLE, "film", "id = ?", &args)?.into_iter().next() { series_hidden = hidden_titles(ctx)?.contains(&text_of(&season, "film")); }Ok(Value::Null) }) .map_err(unreadable)?;if series_hidden && inside_hidden(client, false).is_err() {returnErr(MethodError::new("not_found", say("no_title", &[]))); }let states = super::films::file_states(client)?;letmut answer = Value::Null; client .read_rows("cinemas.season", &mut |ctx| {let args = [rusqlite::types::Value::Text(id.clone())];letSome(season) = rows_where(ctx, SEASON_TABLE, "id, number, title, film", "id = ?", &args)?.into_iter().next() else {returnOk(Value::Null); };let series_id = text_of(&season, "film");let series: BTreeMap<String, (String, Option<String>)> = rows_where(ctx, FILM_TABLE, "id, title, poster", "id = ?", &[rusqlite::types::Value::Text(series_id.clone())])? .iter() .map(|row| (text_of(row, "id"), (text_of(row, "title"), words(row, "poster")))) .collect();let seasons: BTreeMap<String, (Option<f64>, String)> = [(id.clone(), (number(&season, "number"), series_id))].into_iter().collect();letmut episodes: Vec<(f64, Value)> = rows_where(ctx, EPISODE_TABLE, &format!("{EPISODE_COLUMNS}, synopsis"), "season = ?", &args)? .iter() .map(|row| {let title = Title::episode(row, &seasons, &series);letmut item = title.item(&states); item["number"] = json!(number(row, "number")); item["episode_title"] = json!(words(row, "title"));// What the episode's row says: "3. Its title", "Episode 3", or "Episode" for one with neither (the// phones fell back to the series' name and "0."; his library on build 19). item["label"] = json!(match (number(row, "number"), words(row, "title")) { (Some(n), Some(own)) => say("episode_numbered", &[("n", &format!("{n:.0}")), ("title", &own)]), (None, Some(own)) => own, (Some(n), None) => say("episode_n", &[("n", &format!("{n:.0}"))]), (None, None) => say("episode_untitled", &[]), }); item["synopsis"] = json!(words(row, "synopsis")); item["still"] = json!(words(row, "still"));// The row's honest state in words (cinemas-3.html 4): watched, or what is left of a part-watched// one; on this phone and getting ready are the item's own marks. item["state_line"] = match (text_of(row, "status").as_str(), title.progress(), title.position, title.minutes) { ("watched", _, _, _) => json!(say("episode_watched", &[])), (_, Some(_), Some(at), Some(minutes)) => json!(say("episode_left", &[("left", &more::minutes_said((minutes * 60.0 - at).max(0.0) / 60.0))])), _ => Value::Null, }; (number(row, "number").unwrap_or(f64::MAX), item) }) .collect(); episodes.sort_by(|a, b| a.0.total_cmp(&b.0)); answer = json!({"season": { "id": id, "number": number(&season, "number"), "title": words(&season, "title"), "series": text_of(&season, "film") },"episodes": episodes.into_iter().map(|(_, item)| item).collect::<Vec<_>>(), });Ok(Value::Null) }) .map_err(unreadable)?;if answer.is_null() {returnErr(MethodError::new("not_found", say("no_title", &[]))); }Ok(answer)}/// Letters folded for search: lower case, accents and punctuation aside.fn folded(text: &str) -> String { text.chars().filter(|c| c.is_alphanumeric() || c.is_whitespace()).flat_map(char::to_lowercase).collect::<String>().split_whitespace().collect::<Vec<_>>().join(" ")}fn search(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let q = folded(request.get("q").and_then(Value::as_str).unwrap_or_default());if q.is_empty() {returnOk(json!({ "items": [], "top_line": null, "people": [], "groups": [] })); }// Inside Hidden (`hidden: true`) the hidden titles and categories alone; outside, never one of them.let library = Library::read_for(client, request)?;let states = super::films::file_states(client)?;// A title starting with what was typed comes first, then a word of it, then anywhere in it; episodes after.let rank = |title: &Title| -> Option<u8> {let by = [title.director.as_deref(), title.uploader.as_deref()].into_iter().flatten().collect::<Vec<_>>().join(" ");let haystack = folded(&format!("{} {} {by}", title.title, title.caption.clone().unwrap_or_default()));let name = folded(&title.title);if name.starts_with(&q) {Some(0) } elseif haystack.split(' ').any(|word| word.starts_with(&q)) {Some(1) } elseif haystack.contains(&q) || title.year.as_deref() == Some(q.as_str()) {Some(2) } else {None } };letmut found: Vec<(u8, u8, &Title)> = library .films .iter() .filter_map(|title| rank(title).map(|r| (r, 0, title))) .chain(library.episodes.iter().filter_map(|title| rank(title).map(|r| (r, 1, title)))) .collect(); found.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)).then_with(|| a.2.title.to_lowercase().cmp(&b.2.title.to_lowercase())));let groups: Vec<Value> = library.groups.iter().filter(|(_, name, _)| folded(name).contains(&q)).map(|(id, name, _)| json!({ "id": id, "name": name })).collect();// People (a film's director) and channels (a video's uploader) whose name holds what was typed, each with the// titles of theirs here, most first.letmut people: BTreeMap<(String, &'static str), (String, Vec<String>)> = BTreeMap::new();for title in &library.films {for (name, kind) in [(title.director.as_deref(), "person"), (title.uploader.as_deref(), "channel")] {letSome(name) = name.filter(|name| folded(name).contains(&q)) else { continue }; people.entry((folded(name), kind)).or_insert_with(|| (name.to_string(), Vec::new())).1.push(title.id.clone()); } }letmut people: Vec<(String, &'static str, Vec<String>)> = people.into_iter().map(|((_, kind), (name, ids))| (name, kind, ids)).collect(); people.sort_by(|a, b| b.2.len().cmp(&a.2.len()).then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase())));let people: Vec<Value> = people .into_iter() .map(|(name, kind, ids)| json!({ "name": name, "kind": kind, "ids": ids, "line": say(if ids.len() == 1 { "search_by_one" } else { "search_by_other" }, &[("n", &ids.len().to_string())]) })) .collect();// The top result's line: what it is, its year, and what is left of it when part-watched ("Film · 2021 · 1 h 12 m left").let top_line = found.first().map(|(_, _, title)| {let what = if title.table == EPISODE_TABLE { "episode" } else { title.kind.as_str() };letmut parts = vec![say(&format!("top_{what}"), &[])];ifletSome(year) = title.year.as_deref().filter(|year| !year.is_empty()) { parts.push(year.to_string()); }iflet (Some(at), Some(minutes)) = (title.position.filter(|at| *at > 0.0), title.minutes) { parts.push(say("top_left", &[("left", &more::minutes_said((minutes * 60.0 - at).max(0.0) / 60.0))])); } parts.join(" · ") });Ok(json!({ "items": found.into_iter().take(100).map(|(_, _, title)| title.item(&states)).collect::<Vec<_>>(), "top_line": top_line, "people": people, "groups": groups }))}fn kind(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let id = request.get("id").and_then(Value::as_str).filter(|id| !id.trim().is_empty()).ok_or_else(|| bad("cinemas.kind names the title: id"))?;let to = request.get("to").and_then(Value::as_str).filter(|to| KINDS.contains(to)).ok_or_else(|| bad("cinemas.kind takes to: film, series or clip"))?;super::records::call(client, "records.update", &json!({ "table": FILM_TABLE, "id": id, "patch": { "kind": to } }))?;Ok(json!({ "id": id, "kind": to, "said": say(&format!("kind_{to}"), &[]) }))}fn his_groups(client: &ClientController, request: &Value) -> Result<Value, MethodError> {// Outside Hidden the open categories alone; inside (`hidden: true`) the hidden ones too, each said so, for the// picker there (HIDDEN, CONTRACT-2.md). A hidden category's name never leaves Hidden.let inside = request.get("hidden") == Some(&Value::Bool(true));if inside { inside_hidden(client, false)?; }let open = Library::read(client)?;let shut = if inside { Some(Library::read_in(client, true)?) } else { None };letmut groups: Vec<Value> = Vec::new();for (library, hidden) in std::iter::once((&open, false)).chain(shut.iter().map(|l| (l, true))) {let live: BTreeSet<&str> = library.by_id().keys().copied().collect();// Inside Hidden a title in a hidden category is counted there; an open category counts its open titles.for (id, name, members) in &library.groups {let count = members.iter().filter(|m| live.contains(m.as_str()) || (hidden && open.by_id().contains_key(m.as_str()))).count(); groups.push(json!({ "id": id, "name": name, "count": count, "hidden": hidden })); } }if inside {// Inside Hidden, the hidden categories come first: they are what that place is for. groups.sort_by_key(|g| g["hidden"] != Value::Bool(true)); }Ok(json!({ "groups": groups }))}/// The Cinemas words the phones draw (`stream.*`), when the core answers them.pub(crate) fn said(line: &str, fills: &[(&str, &str)]) -> String { cotton_core::rules::shell_lines::LineSet::shipped("cinemas").and_then(|lines| lines.say(&format!("stream.{line}"), fills)).unwrap_or_default()}/// `cinemas.hide { id, hidden }`: a category of his films hidden, or no longer (HIDDEN, CONTRACT-2.md): its flag on/// `record_group`, synced, so it is hidden on every phone. A kind is not a category, and a list of another table's/// rows is not his to hide here.fn hide(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let id = request.get("id").and_then(Value::as_str).filter(|id| !id.trim().is_empty()).ok_or_else(|| bad("cinemas.hide names the category: id"))?;let hidden = request.get("hidden").and_then(Value::as_bool).ok_or_else(|| bad("cinemas.hide takes hidden: true or false"))?;// Hiding is done anywhere; Stop hiding only inside Hidden, open, or once by the undo a Hide handed back.if !hidden {let undo = request.get("undo").and_then(Value::as_str).unwrap_or_default();if !(spend_undo(client, id, undo)) { inside_hidden(client, false)?; } }let open = Library::read(client)?;let shut = Library::read_in(client, true)?;let in_open = open.groups.iter().find(|(gid, ..)| gid == id).map(|(_, name, _)| name.clone());let in_shut = shut.groups.iter().find(|(gid, ..)| gid == id).map(|(_, name, _)| name.clone());let missing = || MethodError::new("not_found", "no category of his films has that id");// Re-review 3, finding 1: a Hide names only an open category (a stale Home on another phone offering Hide on one// already hidden is not found, and hands back no undo); Stop hiding names only a hidden one. Inside Hidden, asking// for the state it already has changes nothing and hands back no undo.let name = match (hidden, in_open, in_shut) { (true, Some(name), _) | (false, _, Some(name)) => name, (true, None, Some(name)) | (false, Some(name), None) if inside_hidden(client, false).is_ok() => {returnOk(json!({ "id": id, "hidden": hidden, "line": Value::Null, "undo": Value::Null, "unchanged": true, "name": name })); } _ => returnErr(missing()), };// Written as the lists' own acts write a list (`groups::order_lists`): no tool draws record_group for records.update.let id_owned = id.to_string(); client .write_rows("cinemas.hide", &mut |ctx| {letmut patch = serde_json::Map::new(); patch.insert("hidden".into(), Value::Bool(hidden)); cotton_tools::mcp::handlers::common::update_row(ctx, groups::GROUPS, &id_owned, patch).map_err(|failure| failure.to_string())?; ctx.commit().map_err(|failure| failure.to_string())?;Ok(Value::Null) }) .map_err(|why| MethodError::new("refused", why))?;let line = if hidden { said("hidden_done", &[("group", &name)]) } else { said("shown_done", &[("group", &name)]) };letmut args = json!({ "id": id, "hidden": !hidden });if hidden { args["undo"] = json!(undo_token(client, id)); }Ok(json!({ "id": id, "hidden": hidden, "line": line, "undo": { "method": "cinemas.hide", "args": args } }))}/// `cinemas.hidden {}`: the hidden place, a small home of his hidden titles (HIDDEN, CONTRACT-2.md): Carry on, then/// each hidden category in his order. Open once the shell's `cinemas.unlock` (after the phone's lock passed); one/// opened with `no_lock` says so. Locked, it answers no row and no name.fn hidden_place(client: &ClientController, request: &Value) -> Result<Value, MethodError> {// Open only by the core's unlock (`cinemas.unlock`), never by the caller's word.let _ = request;let state = unlocked(client, false);let no_lock = state == Some(true);let unlocked = state.is_some();letmut answer = json!({ "title": said("hidden_place", &[]), "locked": !unlocked, "rows": [], "search_hint": said("hidden_search_hint", &[]) });if no_lock { answer["no_lock"] = json!(said("hidden_no_lock", &[])); answer["set_lock"] = json!(said("hidden_set_lock", &[])); }if !unlocked { answer["unlock"] = json!(said("hidden_unlock", &[]));returnOk(answer); }let library = Library::read_in(client, true)?;let states = super::films::file_states(client)?;let rows: Vec<Value> = library .rows() .into_iter() .filter(|(id, ..)| id == "carry_on" || id.starts_with("group:")) .map(|(id, words, group, titles)| {let words = if id == "carry_on" { said("hidden_carry_on", &[]) } else { words };letmut row = json!({ "id": id, "title": words, "group": group, "count": titles.len(), "hidden": true,"items": titles.iter().take(ROW_ITEMS).map(|title| title.item(&states)).collect::<Vec<_>>(),"more": titles.len() > ROW_ITEMS });// A hidden category the Bin holds: said so, with Restore (cinemas.restore) beside Show this category.ifletSome(gid) = group.as_ref().filter(|gid| library.binned.contains(*gid)) { row["binned"] = json!(said("hidden_in_bin", &[])); row["restore"] = json!({ "label": said("hidden_restore", &[]), "method": "cinemas.restore", "args": { "id": gid } }); } row }) .collect();letmut rows = rows;// CORE 4, M2: the Bin inside Hidden, its hidden titles alone, counted from the rows it lists; the row opens it// (`cinemas.bin { hidden: true }`), where each title has Restore and Delete forever. Left out while it is empty.let bin = more::bin(client, &json!({ "hidden": true }))?;let binned = bin["count"].as_u64().unwrap_or(0);if binned > 0 { rows.push(json!({ "id": "bin", "title": say("bin_title", &[]), "count": binned, "hidden": true,"act": { "method": "cinemas.bin", "request": { "hidden": true } } })); }if rows.is_empty() { answer["empty"] = json!(said("hidden_empty", &[])); } answer["rows"] = json!(rows);Ok(answer)}fn groups_order(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let order: Vec<String> = request .get("order") .and_then(Value::as_array) .ok_or_else(|| bad("cinemas.groupsOrder takes order: the groups' ids in their new order"))? .iter() .map(|id| id.as_str().map(str::to_string).ok_or_else(|| bad("each of order is a group's id"))) .collect::<Result<_, _>>()?;// The whole order is kept, hidden categories in their places; the answer names the open ones alone, and the// hidden ones too only inside Hidden (HIDE FROM SCREEN 3).let inside = request.get("hidden") == Some(&Value::Bool(true));if inside { inside_hidden(client, false)?; }let written = client .write_rows("cinemas.groupsOrder", &mut |ctx| {let shut = if inside { BTreeSet::new() } else { hidden_groups(ctx)? };// Outside Hidden the order sent names the open categories alone: each hidden one keeps its place, the open// ones fill the other places in the order sent (any open one not sent after them, as it stood).let order: Vec<String> = if shut.is_empty() { order.clone() } else {let current = groups::list_order(ctx, FILM_TABLE).map_err(|failure| failure.to_string())?;let sent: Vec<String> = order.iter().filter(|id| !shut.contains(*id)).cloned().collect();letmut fill = sent.iter().cloned().chain(current.iter().filter(|id| !shut.contains(*id) && !sent.contains(id)).cloned());letmut full: Vec<String> = current.iter().map(|id| if shut.contains(id) { Some(id.clone()) } else { fill.next() }).collect::<Option<Vec<_>>>().unwrap_or_default(); full.extend(fill); full };let ids = groups::order_lists(ctx, FILM_TABLE, &order).map_err(|failure| failure.to_string())?;let ids: Vec<String> = ids.into_iter().filter(|id| !shut.contains(id)).collect();Ok(json!({ "groups": ids })) }) .map_err(|why| MethodError::new("refused", why))?;Ok(crate::authoring::own_answer(written))}/// A title's acts, in the order its page lists them: keep it on this phone (or remove it, once it is here; never while/// the Mac is still getting it ready, or with no file), add it to a group, say what it is (a film row only), mark it/// watched or unwatched, and the Bin. Each label is the core's (`home.act_*`).fn acts_of(title: &Title, states: &BTreeMap<String, String>, watched: bool) -> Vec<Value> {// `short`: the act's words under its mark in the page's row of four (cinemas-3.html, 3), where the long ones// would wrap; an act drawn in a list reads `label`.let act = |id: &str, line: &str| {let short = say(&format!("{line}_short"), &[]);let short = if short.is_empty() || short.contains("_short") { say(line, &[]) } else { short }; json!({ "id": id, "label": say(line, &[]), "short": short }) };letmut acts = Vec::new();let has_file = !title.file.trim().is_empty();match states.get(title.file.trim()) {Some(_) => acts.push(act("remove_download", "act_remove_download")),Noneif !title.preparing && has_file => acts.push(act("keep", "act_keep")),None => {} } acts.push(act("group", "act_group"));// Send (send.offer / send.make) and Subtitles (Find, Make, Give: the kit's subtitle commands), a film's or an// episode's with a file: the row's other two.if has_file { acts.push(act("send", "act_send")); acts.push(act("subtitles", "act_subtitles")); }if title.table == FILM_TABLE { acts.push(act("kind", "act_kind")); } acts.push(if watched { act("mark_unwatched", "act_unwatched") } else { act("mark_watched", "act_watched") }); acts.push(act("bin", "act_bin")); acts}fn title(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let table = request.get("table").and_then(Value::as_str).filter(|t| *t == FILM_TABLE || *t == EPISODE_TABLE).ok_or_else(|| bad("cinemas.title names film or film_episode: table"))?;let id = request.get("id").and_then(Value::as_str).filter(|id| !id.trim().is_empty()).ok_or_else(|| bad("cinemas.title names the title: id"))?.to_string();// A hidden title's page answers only inside Hidden (`hidden: true`); outside it is not there.let inside = request.get("hidden") == Some(&Value::Bool(true));letmut library = Library::read_for(client, request)?;if inside {// Inside Hidden its page ticks the open categories it is in as well as the hidden ones.let open = Library::read(client)?; library.groups.extend(open.groups); }let states = super::films::file_states(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", &[])))?;letmut extra = Map::new();let wanted = id.clone(); client .read_rows("cinemas.title", &mut |ctx| {let args = [rusqlite::types::Value::Text(wanted.clone())];let columns = if table == FILM_TABLE { "synopsis, source_url, uploader, subtitle_work, subtitle_note, height, video_range, language, status, subtitles, subtitle_choice" } else { "synopsis, subtitle_work, subtitle_note, height, video_range, status, subtitles, subtitle_choice" };ifletSome(row) = rows_where(ctx, table, columns, "id = ?", &args)?.into_iter().next() {for (key, value) in row { extra.insert(key, value); } }if table == FILM_TABLE {let seasons: Vec<Value> = rows_where(ctx, SEASON_TABLE, "id, number, title, episodes, watched", "film = ?", &args)? .iter()// A season is always named: its own title, else "Season 2", else "Other episodes" (an importer's// season with no number drew "Season 0"; his library on build 19). .map(|row| {let named = words(row, "title").unwrap_or_else(|| match number(row, "number") {Some(n) => say("season_n", &[("n", &format!("{n:.0}"))]),None => say("season_other", &[]), }); json!({ "id": text_of(row, "id"), "number": number(row, "number"), "title": named, "episodes": number(row, "episodes"), "watched": number(row, "watched") }) }) .collect();if !seasons.is_empty() {letmut seasons = seasons;// Specials (season 0) after the seasons, as a library names them (his importer's "Season 00").let order = |season: &Value| season["number"].as_f64().map_or(f64::MAX, |n| if n == 0.0 { f64::MAX - 1.0 } else { n }); seasons.sort_by(|a, b| order(a).total_cmp(&order(b))); extra.insert("_seasons".into(), Value::Array(seasons)); }// A series plays the episode shell.player deals (the one in progress, else the first unwatched), and// its Play says which.let episodes = super::film_player::episodes_of(ctx, &wanted)?;ifletSome(next) = super::film_player::resume_episode(&episodes) {let (season, episode) = (next.season.to_string(), next.number.to_string());let length = next.minutes.unwrap_or(0.0) * 60.0;let play = match next.position.filter(|at| !next.watched && *at > 0.0 && (length <= 0.0 || at / length < 0.97)) {Some(at) => json!({ "label": say("resume_episode", &[("season", &season), ("episode", &episode), ("at", &clock(at))]), "from_start": say("from_start", &[]) }),None => json!({ "label": say("play_episode", &[("season", &season), ("episode", &episode)]), "from_start": null }), }; extra.insert("_series_play".into(), play); } }Ok(Value::Null) }) .map_err(unreadable)?;let carrying_on = found.progress().is_some();let play = match (extra.remove("_series_play"), carrying_on, found.position) { (Some(series), _, _) => series, (None, true, Some(at)) => json!({ "label": say("resume_at", &[("at", &clock(at))]), "from_start": say("from_start", &[]) }), _ => json!({ "label": say("play", &[]), "from_start": null }), };let in_groups: Vec<Value> = library.groups.iter().map(|(gid, name, members)| json!({ "id": gid, "name": name, "in": members.contains(&id) })).collect();let text = |key: &str| extra.get(key).and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()).map(str::to_string);letmut facts: Vec<String> = Vec::new();ifletSome(year) = &found.year { facts.push(year.clone()) }ifletSome(minutes) = found.minutes.filter(|m| *m > 0.0) {let total = minutes.round() as u64; facts.push(if total >= 60 { say("length_hours", &[("h", &(total / 60).to_string()), ("m", &(total % 60).to_string())]) } else { say("length_minutes", &[("m", &total.to_string())]) }); }if extra.get("height").and_then(Value::as_f64).is_some_and(|h| h >= 2000.0) { facts.push("4K".to_string()) }if text("video_range").is_some_and(|range| range != "SDR") { facts.push("HDR".to_string()) }let source = text("source_url").map(|url| json!({ "url": url, "by": text("uploader") }));letmut acts = acts_of(found, &states, text("status").as_deref() == Some("watched"));if source.is_some() {// A web video's page is the second act of its row (cinemas-3.html 5). acts.insert(1.min(acts.len()), json!({ "id": "open_page", "label": say("act_open_page", &[]), "short": say("act_open_page", &[]) })); }// The page's row of four and More (cinemas-3.html 3 and 5): keeping, the page, a group, sending and subtitles// stand in the row; what it is, watched and the Bin wait under More. A row act may carry a second line: the// file's size under Keep, the subtitle track under Subtitles.let kept_size = more::kept_size(client, found.file.trim())?;let subtitle_line = more::subtitle_line(&extra);for act in acts.iter_mut() {let id = act["id"].as_str().unwrap_or_default().to_string();let row = matches!(id.as_str(), "keep" | "remove_download" | "open_page" | "group" | "send" | "subtitles"); act["place"] = json!(if row { "row" } else { "more" }); act["second"] = match id.as_str() {"keep" => kept_size.clone().map(Value::from).unwrap_or(Value::Null),"subtitles" => subtitle_line.clone().map(Value::from).unwrap_or(Value::Null), _ => Value::Null, }; }// "28 min watched · 1h 53m left" under a part-watched title's bar.let watched_line = match (found.progress(), found.position, found.minutes) { (Some(_), Some(at), Some(minutes)) => Some(say("watched_left", &[("watched", &more::minutes_said(at / 60.0)), ("left", &more::minutes_said((minutes * 60.0 - at).max(0.0) / 60.0))])), _ => None, };// More from its channel (cinemas-3.html 5): the same uploader's other titles here, newest first.let more_from = found.uploader.as_deref().map(|channel| {letmut theirs: Vec<&Title> = library.films.iter().filter(|other| other.id != found.id && other.uploader.as_deref().is_some_and(|by| folded(by) == folded(channel))).collect(); theirs.sort_by(|a, b| b.added.cmp(&a.added).then_with(|| b.made.cmp(&a.made))); json!({ "title": say("more_from", &[("channel", channel)]), "items": theirs.into_iter().take(PAGE).map(|t| t.item(&states)).collect::<Vec<_>>() }) }).filter(|more| more["items"].as_array().is_some_and(|items| !items.is_empty()));Ok(json!({"more_from": more_from,"watched_line": watched_line,"item": found.item(&states),"synopsis": text("synopsis"),"facts": facts,"play": play,"tv": say("tv", &[]),"playable": !found.preparing,"preparing": found.preparing.then(|| json!({ "line": say("preparing", &[]) })),"groups": in_groups,"acts": acts,"subtitles": { "work": text("subtitle_work"), "line": text("subtitle_note") },"seasons": extra.get("_seasons").cloned(),"source": source, }))}/// `cinemas.toEpisode { id, series: <id> | { new: name }, season, episode }`: a film row that is really an episode/// moves under its series. The series is his chosen one or found by name or made; the season is found or made;/// the episode carries the film's file and all about it; the film row goes to the Bin.fn to_episode(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let id = request.get("id").and_then(Value::as_str).filter(|id| !id.trim().is_empty()).ok_or_else(|| bad("cinemas.toEpisode names the film: id"))?.to_string();let whole = |key: &str| request.get(key).and_then(Value::as_f64).filter(|n| *n >= 1.0 && n.fract() == 0.0 && *n < 10_000.0).map(|n| n as u32);let season = whole("season").ok_or_else(|| bad("cinemas.toEpisode takes season: a whole number from 1"))?;let episode = whole("episode").ok_or_else(|| bad("cinemas.toEpisode takes episode: a whole number from 1"))?;enumSeries {Held(String),New(String), }let series = match request.get("series") {Some(Value::String(held)) if !held.trim().is_empty() => Series::Held(held.clone()),Some(Value::Object(new)) => match new.get("new").and_then(Value::as_str).map(str::trim).filter(|name| !name.is_empty()) {Some(name) => Series::New(name.to_string()),None => returnErr(bad("cinemas.toEpisode's new series is named: series { new: name }")), }, _ => returnErr(bad("cinemas.toEpisode takes series: a series' id, or { new: name }")), };let written = client .write_rows("cinemas.toEpisode", &mut |ctx| {let args = [rusqlite::types::Value::Text(id.clone())];let columns = format!("id, title, kind, added_on, {}", CARRIED.join(", "));let film = rows_where(ctx, FILM_TABLE, &columns, "id = ?", &args)?.into_iter().next().ok_or_else(|| say("no_title", &[]))?;if text_of(&film, "kind") == "series" {returnErr("a series cannot become an episode".to_string()); }let series_id = match &series {Series::Held(held) => {let found = rows_where(ctx, FILM_TABLE, "id, kind", "id = ?", &[rusqlite::types::Value::Text(held.clone())])?;match found.first() {Some(row) if text_of(row, "kind") == "series" => held.clone(), _ => returnErr("that series is no longer here".to_string()), } }Series::New(name) => {let today = words(&film, "added_on").unwrap_or_else(|| { chrono::DateTime::from_timestamp_millis(cotton_tools::mcp::handlers::common::now_ms(ctx)).unwrap_or_default().format("%Y-%m-%d").to_string() });super::film_intake::series_of(ctx, name, &today, &mut BTreeMap::new())? } };if series_id == id {returnErr("a film cannot become an episode of itself".to_string()); }let season_id = super::film_intake::season_of(ctx, &series_id, season, &mut BTreeMap::new())?;letmut data = Map::new(); data.insert("season".into(), json!(season_id)); data.insert("series".into(), json!(series_id)); data.insert("number".into(), json!(episode)); data.insert("title".into(), json!(words(&film, "title").unwrap_or_else(|| format!("{episode}"))));for key in CARRIED {// An episode's status is only watching or watched: a film's "want to watch" or "stopped" is left off.let fits = |value: &Value| key != "status" || matches!(value.as_str(), Some("watching" | "watched"));ifletSome(value) = film.get(key).filter(|value| !value.is_null() && fits(value)) {// A yes-or-no column reads back from the file as 0 or 1, and is written as false or true.let value = match (key, value.as_i64()) { ("needs_mac" | "sdr_variant", Some(n)) => Value::Bool(n != 0), _ => value.clone(), }; data.insert(key.to_string(), value); } }let made = super::songs::made(ctx, EPISODE_TABLE, data)?;// The files are the episode's now. The film row lets go of them before it goes to the Bin: the object// drops a deleted row's film folder when no other row of ITS table names it (apps/business/src/engine.ts// dropPlayedMedia), and the episode is in another table, so a binned film still naming the folder would// take the episode's stream, upload and original with it.letmut let_go = Map::new();for key in ["file", "source_file", "original", "subtitle_given"] {if film.get(key).is_some_and(|value| !value.is_null()) { let_go.insert(key.to_string(), Value::Null); } }super::songs::patched(ctx, FILM_TABLE, &id, let_go)?;// The film row ends for good, never in the Bin: the episode is that film now, and a Put back from the Bin// brought a second film of the same name with no file (Android builder's walk, 26 Nov 2026). cotton_tools::mcp::handlers::tables::erase_record(ctx, &id, "moved").map_err(|failure| failure.to_string())?;Ok(json!({ "table": EPISODE_TABLE, "id": made, "series": series_id, "season": season_id })) }) .map_err(|why| MethodError::new("refused", why))?;Ok(crate::authoring::own_answer(written))}/// The pages past Home and a title: Subtitles, On this phone, still being prepared, the remote.#[path = "cinemas_more.rs"]pubmod more;#[cfg(test)]#[path = "cinemas_home_tests.rs"]mod tests;