Cotton code
248 lines · 11.2 KB · RustRaw
//! Cinemas' Mark watched and Mark unwatched (Cinemas definition, 4 Nov 2026,//! section 5), and what the player (`shell.player`, `shell_player_kinds`)//! reads of a film's series: its episodes in order, the one a series plays,//! an episode's marquee caption, and the stamp a finish writes.//!//! - `films.mark { table, id, watched }`: Mark watched and Mark unwatched.//!//! Every time is this phone's clock in its own zone; a watched day is that//! zone's day.use serde_json::{json, Map, Value};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{now_iso, now_ms, today_in};use super::songs::{patched, rows_where, text_of, Row};use crate::methods::MethodError;use crate::shell::client::ClientController;pub const METHODS: [&str; 1] = ["films.mark"];pub const FILM_TABLE: &str = "film";pub const SEASON_TABLE: &str = "film_season";pub const EPISODE_TABLE: &str = "film_episode";pub const WATCH_TABLE: &str = "watch";/// Past this share of its length, a play finished the film.pub const FINISHED_SHARE: f64 = 0.9;fn bad(why: &str) -> MethodError {    MethodError::new("bad_request", why.to_string())}/// A line of the cinemas set, filled.pub(crate) fn line(name: &str, fills: &[(&str, &str)]) -> Result<String, MethodError> {    cotton_core::rules::shell_lines::LineSet::shipped("cinemas")        .and_then(|lines| lines.say(name, fills))        .ok_or_else(|| MethodError::new("unreadable", format!("the cinemas set says no line {name}")))}pub fn call(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "films.mark" => mark(client, request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a film player method"))),    }}/// The fields of a request, none unknown.fn fields<'a>(request: &'a Value, allowed: &[&str]) -> Result<&'a Map<String, Value>, MethodError> {    let fields = request.as_object().ok_or_else(|| bad("a film player method takes an object"))?;    if let Some(unknown) = fields.keys().find(|key| !allowed.contains(&key.as_str())) {        return Err(bad(&format!("a film player method has no field {unknown}")));    }    Ok(fields)}/// The film or episode a request names.fn named(fields: &Map<String, Value>) -> Result<(&'static str, String), MethodError> {    let table = match fields.get("table").and_then(Value::as_str) {        Some(FILM_TABLE) => FILM_TABLE,        Some(EPISODE_TABLE) => EPISODE_TABLE,        _ => return Err(bad("this names a film or an episode")),    };    let id = fields.get("id").and_then(Value::as_str).map(str::trim).filter(|id| !id.is_empty()).ok_or_else(|| bad("this names the record's id"))?;    Ok((table, id.to_string()))}pub(crate) fn zone(client: &ClientController) -> Result<String, MethodError> {    client.time_zone().map(str::to_string).ok_or_else(|| bad("this phone named no time zone, so a watched day cannot be said"))}pub(crate) fn written(client: &ClientController, label: &str, body: &mut dyn FnMut(&mut Ctx<'_>) -> Result<Value, String>) -> Result<Value, MethodError> {    let answer = client.write_rows(label, body).map_err(|reason| MethodError::new("unwritable", reason))?;    Ok(crate::authoring::own_answer(answer))}/// A patch written only where it changes the row: a pause at the same/// second, or a second episode marked in the same instant, writes nothing.pub(crate) fn changed(ctx: &mut Ctx<'_>, table: &str, id: &str, mut patch: Map<String, Value>) -> Result<(), String> {    let columns = patch.keys().cloned().collect::<Vec<_>>().join(", ");    let held = row(ctx, table, &columns, id)?;    patch.retain(|key, value| {        let now = held.get(key).unwrap_or(&Value::Null);        match (now, &*value) {            (Value::Number(a), Value::Number(b)) => a.as_f64() != b.as_f64(),            // A bool is stored as 0 or 1.            (Value::Number(a), Value::Bool(b)) => a.as_i64() != Some(i64::from(*b)),            (a, b) => a != b,        }    });    patched(ctx, table, id, patch)}/// One row by id, or the refusal.pub(crate) fn row(ctx: &Ctx<'_>, table: &str, columns: &str, id: &str) -> Result<Row, String> {    rows_where(ctx, table, columns, "id = ?", &[rusqlite::types::Value::Text(id.to_string())])?        .into_iter()        .next()        .ok_or_else(|| format!("this database holds no {table} {id}"))}/// One episode of a series, in the series' order.#[derive(Debug, Clone)]pub(crate) struct Episode {    pub(crate) id: String,    pub(crate) season: u32,    pub(crate) number: u32,    pub(crate) title: String,    pub(crate) file: String,    pub(crate) minutes: Option<f64>,    pub(crate) still: String,    pub(crate) position: Option<f64>,    pub(crate) position_at: String,    pub(crate) watched: bool,    /// Waiting for the Mac to make a copy that plays (`needs_mac`).    pub(crate) converting: bool,}/// A series' episodes, by season number then episode number.pub(crate) fn episodes_of(ctx: &Ctx<'_>, series: &str) -> Result<Vec<Episode>, String> {    let seasons: std::collections::BTreeMap<String, u32> = rows_where(ctx, SEASON_TABLE, "id, number", "film = ?", &[rusqlite::types::Value::Text(series.to_string())])?        .iter()        .map(|season| (text_of(season, "id"), season.get("number").and_then(Value::as_f64).unwrap_or(0.0) as u32))        .collect();    let mut episodes = Vec::new();    for (season_id, season) in &seasons {        for row in rows_where(ctx, EPISODE_TABLE, "id, number, title, file, minutes, still, position, position_at, status, needs_mac", "season = ?", &[rusqlite::types::Value::Text(season_id.clone())])? {            episodes.push(Episode {                id: text_of(&row, "id"),                season: *season,                number: row.get("number").and_then(Value::as_f64).unwrap_or(0.0) as u32,                title: text_of(&row, "title"),                file: text_of(&row, "file"),                minutes: row.get("minutes").and_then(Value::as_f64).filter(|minutes| *minutes > 0.0),                still: text_of(&row, "still"),                position: row.get("position").and_then(Value::as_f64),                position_at: text_of(&row, "position_at"),                watched: text_of(&row, "status") == "watched",                converting: matches!(row.get("needs_mac"), Some(Value::Bool(true))) || row.get("needs_mac").and_then(Value::as_i64) == Some(1),            });        }    }    // Specials (season 0) after the last season: a series starts at season 1 and plays on through its seasons.    episodes.sort_by_key(|episode| (episode.season == 0, episode.season, episode.number));    Ok(episodes)}/// The episode a series plays: the one in progress (the latest resume point/// not watched), else the first not watched that has a file to play (one still/// on the Mac is passed over; his library on build 19), else the first not/// watched, else its first.pub(crate) fn resume_episode(episodes: &[Episode]) -> Option<&Episode> {    episodes        .iter()        .filter(|episode| !episode.watched && !episode.position_at.is_empty())        .max_by(|a, b| a.position_at.cmp(&b.position_at))        .or_else(|| episodes.iter().find(|episode| !episode.watched && !episode.file.trim().is_empty()))        .or_else(|| episodes.iter().find(|episode| !episode.watched))        .or_else(|| episodes.first())}/// The series an episode belongs to: its own link, else its season's film.pub(crate) fn series_of(ctx: &Ctx<'_>, episode: &Row) -> Result<String, String> {    let series = text_of(episode, "series");    if !series.is_empty() {        return Ok(series);    }    let season = row(ctx, SEASON_TABLE, "film", &text_of(episode, "season"))?;    Ok(text_of(&season, "film"))}/// An episode's marquee words: "S1 E5 · Its title", or the mark alone.pub(crate) fn caption_of(episode: &Episode) -> Result<String, String> {    let mark = cotton_core::rules::shell_lines::LineSet::shipped("cards")        .and_then(|cards| cards.say("field.episode_mark", &[("said", &episode.season.to_string()), ("number", &episode.number.to_string())]))        .ok_or("the cards set says no episode mark")?;    if episode.title.is_empty() {        return Ok(mark);    }    line("player.caption", &[("mark", &mark), ("title", &episode.title)]).map_err(|failure| failure.message)}// ── Mark watched ────────────────────────────────────────────────────────────fn mark(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let fields = fields(request, &["table", "id", "watched"])?;    let (table, id) = named(fields)?;    let watched = fields.get("watched").and_then(Value::as_bool).ok_or_else(|| bad("watched is true or false"))?;    let zone = zone(client)?;    written(client, "films.mark", &mut |ctx| {        let title = text_of(&row(ctx, table, "title", &id)?, "title");        marked(ctx, table, &id, watched, &zone)?;        let said = line(if watched { "watch.marked" } else { "watch.unmarked" }, &[("name", &title)]).map_err(|failure| failure.message)?;        Ok(json!({ "table": table, "id": id, "watched": watched, "said": said }))    })}/// A film or an episode watched (the day and the time stamped, the resume/// point cleared) or unwatched. A watched episode stamps its series' last/// watch, and the series' last episode watched finishes the series.pub(crate) fn marked(ctx: &mut Ctx<'_>, table: &str, id: &str, watched: bool, zone: &str) -> Result<(), String> {    let now = now_iso(ctx);    let today = today_in(zone, now_ms(ctx)).map_err(|failure| failure.to_string())?;    let mut patch = Map::new();    patch.insert("position".into(), Value::Null);    patch.insert("position_at".into(), Value::Null);    match (table, watched) {        (FILM_TABLE, true) => {            patch.insert("status".into(), json!("watched"));            patch.insert("watched_on".into(), json!(today));            patch.insert("last_watched_at".into(), json!(now));        }        (FILM_TABLE, false) => {            patch.insert("status".into(), json!("want_to_watch"));            patch.insert("watched_on".into(), Value::Null);        }        (_, true) => {            patch.insert("status".into(), json!("watched"));            patch.insert("watched_on".into(), json!(today));        }        (_, false) => {            patch.insert("status".into(), Value::Null);            patch.insert("watched_on".into(), Value::Null);        }    }    changed(ctx, table, id, patch)?;    if table == EPISODE_TABLE && watched {        let held = row(ctx, EPISODE_TABLE, "id, series, season", id)?;        let series = series_of(ctx, &held)?;        let episodes = episodes_of(ctx, &series)?;        let mut patch = Map::new();        patch.insert("last_watched_at".into(), json!(now));        if episodes.iter().all(|episode| episode.watched) {            patch.insert("status".into(), json!("watched"));            patch.insert("watched_on".into(), json!(today));            patch.insert("position_at".into(), Value::Null);        } else {            patch.insert("position_at".into(), json!(now));        }        changed(ctx, FILM_TABLE, &series, patch)?;    }    Ok(())}#[cfg(test)]#[path = "film_player_tests.rs"]mod tests;