//! Cinemas' Give subtitles (coordinator for the owner, 25 Nov 2026, SUBTITLE//! FILE): the phone half of the Mac's `film:subtitles --file` (c168179dd8).//! On a film's or an episode's page the person picks a `.srt` or `.vtt` from//! the phone's files; the act's file pick (`PickKind::File`) hands this//! method the path of the phone's own copy.//!//! - `films.subtitleFile { table, id, path }` → `{ key, language?, said }`,//! `table` `film` or `film_episode`. The file is checked (one of the pick's//! extensions, at most [`MOST_BYTES`], a cue line `-->` in it), kept in//! this device's store and queued up SEALED as any film file is, under//! `<database>/films/<folder>/given/sub-<first 16 hex of its sha256>.<ext>`//! beside the film's stream, and pinned here. In the same write the row//! takes `subtitle_given` (that key), `subtitle_given_language` (the//! language its name says, `sidecars::given_language`; else left empty and//! the Mac takes the first language the owner reads) and `subtitle_work`//! `file`, with a `subtitle_note` saying it waits for the Mac.//! - The Mac's `film:subtitles --queue` (GET /v1/films/subtitles/asked, ask//! `file`) opens the file once the drain has sent it, lays it as a track//! (source `sidecar`), and writes `ready` or `failed` with its line. A file//! not yet sent is waited for, never failed.//!//! A film kept whole (an MP4 or a MOV the phone sent as it plays,//! `films/<folder>/whole.<ext>`) takes the file too: its note says the Mac//! makes its stream first, and the Mac's run converts it, then lays the track//! (CINEMAS WALK, 25 Nov 2026: refusing it promised a conversion nothing made).//!//! Refused, nothing written: a row that is not a film or an episode, one with//! no stream yet, a file of another kind, one too large, and one with no cue//! in it. The same bytes given twice name the same key.use serde::Deserialize;use serde_json::{json, Map, Value};use sha2::{Digest, Sha256};use cotton_client::media::store::put_media_file;use cotton_core::definitions::{CommandPick, PickKind};use cotton_core::films::sidecars::given_language;use cotton_tools::mcp::handlers::common::now_iso;usesuper::film_player::line;usesuper::songs::{patched, queue, rows_where, text_of};usecrate::handle::CottonHandle;usecrate::methods::MethodError;usecrate::phone::io_trouble::io_refusal;usecrate::shell::client::ClientController;pubconst METHODS: [&str; 1] = ["films.subtitleFile"];/// The largest subtitle file taken: a feature's SubRip is 50 to 150 KB.pubconst MOST_BYTES: u64 = 4 * 1024 * 1024;/// What the act's file pick accepts (the kit's `give_subtitles`).pubconst ACCEPT: [&str; 2] = ["srt", "vtt"];#[derive(Deserialize)]structAsked { table: String, id: String, path: String,}fn bad(why: implInto<String>) -> MethodError {MethodError::new("bad_request", why.into())}pubfn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {match method {"films.subtitleFile" => give(&handle.client(), request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a films subtitle method"))), }}fn give(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let asked: Asked = serde_json::from_value(request.clone()).map_err(|error| bad(format!("films.subtitleFile takes {{ table, id, path }}: {error}")))?;if !matches!(asked.table.as_str(), "film" | "film_episode") {returnErr(bad(line("subtitles.not_a_film", &[])?)); }let pick = CommandPick { argument: "path".into(), kind: PickKind::File, label: None, table: None, database_by: None, filter: None, choices_from: None, optional: None, min: None, default: None, max: None, labels: None, accept: Some(ACCEPT.iter().map(|ext| ext.to_string()).collect()) };let path = pick.file_value(&json!(asked.path)).map_err(bad)?;let file = std::path::PathBuf::from(&path);let unreadable = line("subtitles.unreadable", &[])?;let size = std::fs::metadata(&file).map_err(|error| bad(io_refusal(unreadable.clone(), &file, &error)))?.len();if size > MOST_BYTES {let (size, most) = ((size / (1024 * 1024)).max(1).to_string(), (MOST_BYTES / (1024 * 1024)).to_string());returnErr(bad(line("subtitles.too_large", &[("size", &size), ("most", &most)])?)); }let bytes = std::fs::read(&file).map_err(|error| bad(io_refusal(unreadable.clone(), &file, &error)))?;if !bytes.windows(3).any(|w| w == b"-->") {returnErr(bad(line("subtitles.no_cues", &[])?)); }let (no_stream, waiting, waiting_whole) = (line("subtitles.no_stream", &[])?, line("subtitles.waiting", &[])?, line("subtitles.waiting_whole", &[])?);let ext = path.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase()).unwrap_or_default();let hash = Sha256::digest(&bytes).iter().take(8).map(|b| format!("{b:02x}")).collect::<String>();let name = path.rsplit('/').next().unwrap_or(&path).to_string();let language = given_language(&name);let layout = client.layout().clone();let (table, id) = (asked.table.clone(), asked.id.clone());let answer = client .write_rows("films.subtitleFile", &mut |ctx| {let row = rows_where(ctx, &table, "*", "id = ?", &[rusqlite::types::Value::Text(id.clone())])?.into_iter().next().ok_or_else(|| format!("no {table} {id} here"))?;let stream = text_of(&row, "file");let whole = is_whole(&stream);letSome((folder, _)) = stream.rsplit_once('/').filter(|_| (stream.ends_with(".m3u8") || whole) && stream.contains("/films/")) else {returnErr(no_stream.clone()); };let key = format!("{folder}/given/sub-{hash}.{ext}");let workspace_id = ctx.workspace_id.to_string();let now = now_iso(ctx);let stored = put_media_file(&layout, &workspace_id, &file, &ext).map_err(|error| io_refusal(unreadable.clone(), &file, &error))?;let content_type = if ext == "vtt" { "text/vtt" } else { "application/octet-stream" }; queue(ctx, &workspace_id, &key, &stored, content_type, &now)?;letmut patch = Map::new(); patch.insert("subtitle_given".into(), json!(key)); patch.insert("subtitle_given_language".into(), language.clone().map_or(Value::Null, Value::from)); patch.insert("subtitle_work".into(), json!("file")); patch.insert("subtitle_note".into(), json!(if whole { &waiting_whole } else { &waiting })); patched(ctx, &table, &id, patch)?;Ok(json!({ "key": key, "language": language })) }) .map_err(|reason| MethodError::new("write_refused", reason))?;letmut answer = crate::authoring::own_answer(answer);let key = answer["key"].as_str().unwrap_or_default().to_string();// Given here, so on this phone until it is sent: pinned, as a film's own sidecar is.let now = super::songs::iso_now(client)?; client .with_writer(|f| cotton_store::media_ledger::set_media_pinned(f.driver, &key, true, &now).map_err(|error| error.to_string())) .map_err(|reason| MethodError::new("unwritable", reason))?;// No words of its own: the act's receipt ("Your Mac will add your subtitles to {name}") says it, and a `said` here// was drawn after it on Android, hiding the film's name (CINEMAS WALK, 25 Nov 2026).Ok(answer)}#[cfg(test)]#[path = "film_subtitle_file_tests.rs"]mod tests;/// A film kept whole as the phone sent it: `…/films/<folder>/whole.<mp4|m4v|mov>`.fn is_whole(stream: &str) -> bool { stream.rsplit('/').next().is_some_and(|name| matches!(name.to_ascii_lowercase().as_str(), "whole.mp4" | "whole.m4v" | "whole.mov"))}