//! Films into Cotton Cinemas from this phone (Cinemas definition, 4 Nov 2026, //! section 6): the share sheet, Plus › Add files and Plus › Add a folder all //! end here, as Music's doors end in `music.capture`. //! //! - `films.capture { films: [{ path, sourcePath, minutes?, video?, audio?, //! height?, bitrate?, title?, year?, posterPath?, locked?, typedTitle?, //! typedYear?, beside?, seriesBeside?, chapters? }], onlyFilms? }` //! → `{ films: [{ sourcePath, outcome, id?, table?, series?, key?, //! subtitles?, nfoUnread?, title, line }], said }` //! (`series`: an episode's series, where a folder lands). //! Each file is what the phone read of it (AVFoundation, off the main //! thread): its length, its codecs, its picture's height, its tags' title //! and year, a frame or its artwork as `posterPath`, and whether its seller //! locked it. Its path says the rest (`cotton_core::films::from_path`): //! `Series/Season 02/S02E05 - Title.mkv` makes the series, the season and //! the episode; `Film (2019).mkv` a film. //! //! `outcome`: //! - `added`: a new film or episode. An MP4 or a MOV the phone plays as it //! is goes up whole (`films//whole.`, its `file`); anything else //! goes up as it came (`films//source.`, its `source_file`) with //! `needs_mac`, and the Mac's importer makes its stream. Its poster stands //! at once either way. //! - `here`: the same bytes are a film already (by `sha256`). //! - `better`: the same title and year (or the same episode of a series) was //! here in a worse file: this file takes its place, and the line says the //! other can go. `worse`: a better file is here already; this one is not //! kept. //! - `refused`: no video, locked by its seller (never unlocked), or over the //! 20 GB a film may be. `not_film`: with `onlyFilms` (Cotton's own drain), a //! video under twenty minutes in a camera's container, which Photos keeps. //! //! What lies beside a file (open standards, 7 Nov 2026; the rules are //! `cotton_core::films::sidecars`, which the film importer mirrors for the //! Mac's `pnpm film:import`): `beside` is the file's folder and, for an //! episode, `seriesBeside` the series' folder (above `Season NN`), each //! `{ siblings, nfos, files }`: every file name in it, the text of each `.nfo` //! by name, and a staged copy of each subtitle and picture by name. The core //! reads no file system for these: it names the sidecars from `siblings` and //! takes their text or copy from the other two, refusing the capture when a //! named one was not handed. Then, on an `added` or a `better` row: //! - the NFO (`.nfo`, else `movie.nfo`; an episode's own; a series' //! `tvshow.nfo`) fills only empty columns, ids first, said in `filled_from` //! as `nfo`; one that is no NFO is named in `nfoUnread` and not read; //! - the title is the one the person typed (`typedTitle`, `typedYear`), else //! the NFO's, else the file's tags, else its name (the Mac's rule); //! - the poster and the fanart beside a film are its `poster` and `backdrop` //! where the row has none (the poster before `posterPath`'s frame); a //! series' are the series row's; //! - each subtitle is kept as media in the film's own folder beside its file, //! `films//.[.forced][.sdh][.n].` (named so //! the same rules read it back), queued up and pinned here, its key in //! `subtitles`. The player plays a whole file as it is and takes subtitles //! only from an HLS master's renditions, so these wait in the folder for //! the Mac to make them renditions; //! - `chapters` (`[{ start_ms, title }]`, read by the caller from the file's //! own marks; no ffprobe here) are the row's `chapters` when two or more. //! //! A file brought in here is on this phone: it is kept, its ledger row //! pinned, and it uploads through the drain in parts. use std::collections::BTreeMap; use std::path::PathBuf; use serde::Deserialize; use serde_json::{json, Map, Value}; use cotton_client::layout::Layout; use cotton_client::media::store::put_media_file; use cotton_core::films::sidecars::{chapters_text, read_nfo, series_sidecars, sidecars, Chapter, Nfo, Sidecars, Subtitle, FORCED_WORDS, LANGUAGES, SDH_WORDS}; use cotton_core::films::{better, extension, from_path, is_film, is_video, plays_whole, same_key, FilmPath, Quality}; use cotton_core::media::keys::{film_content_type, film_source_key, film_whole_key}; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::handlers::common::{now_iso, now_ms, today_in}; use super::film_player::line; use super::songs::{made, patched, put, queue, rows_where, text_of, Row}; use crate::handle::CottonHandle; use crate::methods::MethodError; use crate::phone::io_trouble::io_refusal; use crate::shell::client::ClientController; pub const METHODS: [&str; 2] = ["films.capture", "films.picked"]; const FILM_TABLE: &str = "film"; const SEASON_TABLE: &str = "film_season"; const EPISODE_TABLE: &str = "film_episode"; /// The most one film may be (the object's own cap, `MediaKind::Film`). pub const FILM_MAX_BYTES: u64 = 20 * 1024 * 1024 * 1024; /// The most files one capture takes: a folder is walked in turns. pub const MOST_IN_ONE: usize = 200; /// One file of a capture, as the phone read it. #[derive(Debug, Clone, Default, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct FilmIn { /// Where the bytes are now: a staged copy the phone owns. pub path: PathBuf, /// The path it came in as (`Series/Season 02/S02E05 - Title.mkv` from a /// folder, the file's own name from the share sheet). pub source_path: String, #[serde(default)] pub minutes: Option, /// The video's and the audio's codecs, as four-character codes. #[serde(default)] pub video: Option, #[serde(default)] pub audio: Option, #[serde(default)] pub height: Option, #[serde(default)] pub bitrate: Option, /// The file's own tags. #[serde(default)] pub title: Option, #[serde(default)] pub year: Option, /// A frame of the film, or its embedded artwork. #[serde(default)] pub poster_path: Option, /// The seller's lock (FairPlay): such a file is refused, never opened. #[serde(default)] pub locked: bool, /// A title and a year the person typed: they beat the NFO's, the tags' /// and the name's. #[serde(default)] pub typed_title: Option, #[serde(default)] pub typed_year: Option, /// The file's own folder, as the phone read it. #[serde(default)] pub beside: Option, /// An episode's series' folder (above `Season NN`). #[serde(default)] pub series_beside: Option, /// The file's own chapter marks. #[serde(default)] pub chapters: Option>, } /// One folder beside a file: what lies there, read by the phone. #[derive(Debug, Clone, Default, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct Folder { /// Every file's name in the folder. pub siblings: Vec, /// Each `.nfo`'s text, by its name. #[serde(default)] pub nfos: BTreeMap, /// A staged copy of each subtitle and picture, by its name. #[serde(default)] pub files: BTreeMap, } /// What the rules found beside a file, read. #[derive(Debug, Default)] struct Beside { nfo: Option, /// An NFO the rules named that is no NFO: named, not read. unread: Vec, subtitles: Vec<(Subtitle, PathBuf)>, poster: Option, backdrop: Option, } /// The sidecars `found` names in `folder`, their text and copies taken from /// what the phone handed; one it did not hand refuses the capture. fn read_folder(folder: &Folder, found: Sidecars, whose: &str) -> Result { let path = |name: &str| folder.files.get(name).cloned().ok_or_else(|| format!("{name} lies beside {whose}: hand its staged copy in files")); let mut out = Beside::default(); if let Some(name) = &found.nfo { let text = folder.nfos.get(name).ok_or_else(|| format!("{name} lies beside {whose}: hand its text in nfos"))?; match read_nfo(text) { Some(nfo) => out.nfo = Some(nfo), None => out.unread.push(name.clone()), } } for subtitle in found.subtitles { let at = path(&subtitle.file)?; out.subtitles.push((subtitle, at)); } out.poster = found.poster.as_deref().map(path).transpose()?; out.backdrop = found.backdrop.as_deref().map(path).transpose()?; Ok(out) } /// What lies beside a file and, for an episode, beside its series. fn beside_of(film: &FilmIn, episode: bool) -> Result<(Beside, Option), String> { let own = match &film.beside { Some(folder) => read_folder(folder, sidecars(&film.source_path, &folder.siblings, episode), &film.source_path)?, None => Beside::default(), }; let series = match (&film.series_beside, episode) { (Some(folder), true) => Some(read_folder(folder, series_sidecars(&folder.siblings), &format!("the series of {}", film.source_path))?), (Some(_), false) => return Err(format!("{} is no episode, so it has no series folder", film.source_path)), (None, _) => None, }; Ok((own, series)) } fn is_episode(source_path: &str) -> bool { matches!(from_path(source_path), Some(FilmPath::Episode { .. })) } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct CaptureIn { films: Vec, #[serde(default)] only_films: bool, } fn bad(why: &str) -> MethodError { MethodError::new("bad_request", why.to_string()) } pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result { match method { "films.capture" => capture(&handle.client(), request), "films.picked" => picked(request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a films intake method"))), } } /// `films.picked { paths }` → `{ films: [{ path, series }], stage: [path] }`: /// of every file under a picked folder (by its path in it), which are films /// (`is_video`), each episode's series' folder (`series_folder`, handed as its /// `seriesBeside`), and which other files a capture will ask for by name — the /// NFOs, subtitles and pictures `sidecars` and `series_sidecars` name — so a /// phone stages those and no others. fn picked(request: &Value) -> Result { let paths: Vec = request .get("paths") .and_then(Value::as_array) .ok_or_else(|| bad("films.picked takes { paths: [path] }"))? .iter() .map(|path| path.as_str().map(str::to_string).ok_or_else(|| bad("films.picked takes { paths: [path] }"))) .collect::>()?; let folder_of = |path: &str| path.rsplit_once('/').map_or(String::new(), |(folder, _)| folder.to_string()); let mut names: BTreeMap> = BTreeMap::new(); for path in &paths { names.entry(folder_of(path)).or_default().push(path.rsplit('/').next().unwrap_or(path).to_string()); } let mut stage: std::collections::BTreeSet = std::collections::BTreeSet::new(); let mut take = |folder: &str, found: Sidecars| { let at = |name: &str| if folder.is_empty() { name.to_string() } else { format!("{folder}/{name}") }; found.nfo.iter().chain(found.poster.iter()).chain(found.backdrop.iter()).for_each(|name| { stage.insert(at(name)); }); found.subtitles.iter().for_each(|subtitle| { stage.insert(at(&subtitle.file)); }); }; let mut films = Vec::new(); for path in &paths { if !extension(path).is_some_and(|ext| is_video(&ext)) { continue; } let folder = folder_of(path); take(&folder, sidecars(path, &names[&folder], is_episode(path))); let series = cotton_core::films::series_folder(path); if let Some(above) = &series { take(above, series_sidecars(names.get(above).map_or(&[][..], Vec::as_slice))); } films.push(json!({ "path": path, "series": series })); } Ok(json!({ "films": films, "stage": stage.into_iter().collect::>() })) } fn capture(client: &ClientController, request: &Value) -> Result { let asked: CaptureIn = serde_json::from_value(request.clone()).map_err(|error| bad(&format!("films.capture takes {{ films: [{{ path, sourcePath, … }}], onlyFilms? }}: {error}")))?; if asked.films.is_empty() || asked.films.len() > MOST_IN_ONE { return Err(bad(&format!("films.capture takes from 1 to {MOST_IN_ONE} files at a time"))); } for film in &asked.films { beside_of(film, is_episode(&film.source_path)).map_err(|why| bad(&why))?; } let zone = client.time_zone().map(str::to_string).ok_or_else(|| bad("this phone named no time zone, so a film's day added cannot be said"))?; let layout = client.layout().clone(); let answer = client .write_rows("films.capture", &mut |ctx| write_films(ctx, &layout, &asked.films, asked.only_films, &zone)) .map_err(|reason| MethodError::new("capture_refused", reason))?; let answer = crate::authoring::own_answer(answer); // Brought in here, so on this phone: kept, its ledger row pinned — a film // already here by its bytes too, where its whole file is those bytes. let kept: Vec = answer["films"] .as_array() .into_iter() .flatten() .filter(|film| matches!(film["outcome"].as_str(), Some("added" | "better" | "here"))) .filter_map(|film| film["key"].as_str().map(str::to_string)) .collect(); if !kept.is_empty() { 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))?; super::films::mark_kept(client, &kept)?; } // Each subtitle kept beside its film is on this phone too: pinned, never // counted as a film of its own. let subtitles: Vec = answer["films"] .as_array() .into_iter() .flatten() .flat_map(|film| film["subtitles"].as_array().cloned().unwrap_or_default()) .filter_map(|key| key.as_str().map(str::to_string)) .collect(); if !subtitles.is_empty() { let now = super::songs::iso_now(client)?; client .with_writer(|f| { for key in &subtitles { 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))?; } Ok(answer) } /// What a capture's file is, once its tags and its path are read. enum Made { /// `named`: the title and the year the NFO gives, left for its patch to /// fill and say so. Film { title: String, year: Option, nfo_title: bool, nfo_year: bool }, Episode { series: String, season: u32, episode: u32, title: Option, nfo_title: bool }, } /// Everything a capture writes, in one write. pub fn write_films(ctx: &mut Ctx<'_>, layout: &Layout, films: &[FilmIn], only_films: bool, zone: &str) -> Result { let workspace_id = ctx.workspace_id.to_string(); let database = ctx.file.id().to_string(); let now = now_iso(ctx); let today = today_in(zone, now_ms(ctx)).map_err(|failure| failure.to_string())?; let say = |name: &str, fills: &[(&str, &str)]| line(name, fills).map_err(|failure| failure.message); let mut answers = Vec::new(); // Series and seasons made in this capture, so a folder's episodes share them. let mut series_made: BTreeMap = BTreeMap::new(); let mut seasons_made: BTreeMap<(String, u32), String> = BTreeMap::new(); let mut episodes_by_series: BTreeMap = BTreeMap::new(); let mut series_dressed: std::collections::BTreeSet = std::collections::BTreeSet::new(); for film in films { let name = film.source_path.rsplit('/').next().unwrap_or(&film.source_path).to_string(); let refuse = |line_name: &str| -> Result { Ok(json!({"sourcePath": film.source_path, "outcome": "refused", "title": name, "line": say(line_name, &[("name", &name)])?})) }; let Some(ext) = extension(&film.source_path).filter(|ext| is_video(ext)) else { answers.push(refuse("intake.refused")?); continue; }; if film.locked { answers.push(refuse("intake.locked")?); continue; } let size = std::fs::metadata(&film.path).map_err(|error| io_refusal("the film could not be read", &film.path, &error))?.len(); if size > FILM_MAX_BYTES { answers.push(refuse("intake.too_big")?); continue; } if only_films && !is_film(&ext, film.minutes) { answers.push(json!({"sourcePath": film.source_path, "outcome": "not_film", "title": name})); continue; } let parsed = from_path(&film.source_path); let (beside, series_beside) = beside_of(film, matches!(parsed, Some(FilmPath::Episode { .. })))?; // The title the person typed, else the NFO's, else the tags', else // the path's (the Mac's rule, a1481ff57). let typed = words(&film.typed_title); let nfo_title = beside.nfo.as_ref().and_then(|nfo| words(&nfo.title)).filter(|_| typed.is_none()); let typed_year = words(&film.typed_year); let nfo_year = beside.nfo.as_ref().and_then(|nfo| words(&nfo.year)).filter(|_| typed_year.is_none()); let year_of = |path_year: Option| typed_year.clone().or(nfo_year.clone()).or(words(&film.year)).or(path_year); let title_of = |path_title: Option| typed.clone().or(nfo_title.clone()).or(words(&film.title)).or(path_title); let what = match parsed { Some(FilmPath::Episode { series, season, episode, title }) => Made::Episode { series, season, episode, title: title_of(title), nfo_title: nfo_title.is_some() }, Some(FilmPath::Film { title, year }) => Made::Film { title: title_of(Some(title)).expect("the path named it"), year: year_of(year), nfo_title: nfo_title.is_some(), nfo_year: nfo_year.is_some() }, None => match title_of(None) { Some(title) => Made::Film { title, year: year_of(None), nfo_title: nfo_title.is_some(), nfo_year: nfo_year.is_some() }, None => { answers.push(refuse("intake.refused")?); continue; } }, }; // 1. The bytes, into this device's store. let stored = put_media_file(layout, &workspace_id, &film.path, &ext) .map_err(|error| io_refusal("the film could not be copied into this device's store", &film.path, &error))?; // 2. The same bytes are a film already: already here. let sha = rusqlite::types::Value::Text(stored.sha256.clone()); let held = rows_where(ctx, FILM_TABLE, "id, title, file, NULL AS series, 'film' AS held_in", "sha256 = ?", std::slice::from_ref(&sha))? .into_iter() .chain(rows_where(ctx, EPISODE_TABLE, "id, title, file, series, 'film_episode' AS held_in", "sha256 = ?", &[sha])?) .next(); if let Some(row) = held { let title = text_of(&row, "title"); let series = Some(text_of(&row, "series")).filter(|series| !series.is_empty()); let mut answer = json!({"sourcePath": film.source_path, "outcome": "here", "id": text_of(&row, "id"), "table": text_of(&row, "held_in"), "series": series, "title": title, "line": say("intake.here", &[("title", &title)])?}); // Its whole file is these very bytes, now on this phone: it is kept // here (a reinstall, or a phone that only streamed it), and the // object already holds them, so nothing goes up again. let file = text_of(&row, "file"); if super::films::whole(&file) { kept_here(ctx, &workspace_id, &file, &stored, film_content_type(&ext).ok_or("a film extension carries its type")?, &now)?; answer["key"] = json!(file); } answers.push(answer); continue; } let whole = plays_whole(&ext, film.video.as_deref(), film.audio.as_deref()); let quality = Quality { height: film.height, bitrate: film.bitrate }; // 3. The film or the episode it is, found by title and year or by its // place in its series; a held one in a worse file takes this one. // An episode's answer names its series: a folder lands there. let (table, twin, title, series_id) = match &what { Made::Film { title, year, .. } => { let key = same_key(title, year.as_deref()); let twin = rows_where(ctx, FILM_TABLE, "id, title, year, height, bitrate, file, source_file", "kind = 'film' AND lower(trim(title)) = ?", &[rusqlite::types::Value::Text(title.trim().to_lowercase())])? .into_iter() .find(|row| same_key(&text_of(row, "title"), Some(&text_of(row, "year")).filter(|year| !year.is_empty()).map(String::as_str)) == key); (FILM_TABLE, twin, title.clone(), None) } Made::Episode { series, season, episode, title, .. } => { let series_id = series_of(ctx, series, &today, &mut series_made)?; if let Some(dress) = series_beside.as_ref().filter(|_| series_dressed.insert(series_id.clone())) { dress_series(ctx, layout, &workspace_id, &series_id, dress, &now)?; } let season_id = season_of(ctx, &series_id, *season, &mut seasons_made)?; let twin = rows_where(ctx, EPISODE_TABLE, "id, title, height, bitrate, file, source_file", "season = ? AND number = ?", &[rusqlite::types::Value::Text(season_id.clone()), rusqlite::types::Value::Integer(i64::from(*episode))])?.into_iter().next(); *episodes_by_series.entry(series.clone()).or_default() += 1; let title = match title { Some(title) => title.clone(), None => say("intake.episode_named", &[("series", series), ("season", &season.to_string()), ("number", &episode.to_string())])?, }; (EPISODE_TABLE, twin, title, Some(series_id)) } }; let content_type = film_content_type(&ext).ok_or("a film's extension carries its type")?; if let Some(row) = twin.filter(|row| !text_of(row, "file").is_empty() || !text_of(row, "source_file").is_empty()) { let id = text_of(&row, "id"); let held = Quality { height: number(&row, "height"), bitrate: number(&row, "bitrate") }; if !better(quality, held) { answers.push(json!({"sourcePath": film.source_path, "outcome": "worse", "id": id, "table": table, "series": series_id, "title": title, "line": say("intake.worse", &[("title", &title)])?})); continue; } // A fresh folder, so the better file never lands on the held one's key. let folder = format!("{id}-{}", &stored.sha256[..12]); let key = if whole { film_whole_key(&database, &folder, &ext) } else { film_source_key(&database, &folder, &ext) }; let replaced = if text_of(&row, "file").is_empty() { text_of(&row, "source_file") } else { text_of(&row, "file") }; let mut patch = file_patch(&key, whole, &stored.sha256, film); // What lies beside the better file: the NFO and the pictures fill // only what the row holds nothing in; its chapters are this file's. let held_row = rows_where(ctx, table, "*", "id = ?", &[rusqlite::types::Value::Text(id.clone())])?.into_iter().next().unwrap_or_default(); if table == FILM_TABLE { if blank(&held_row, "poster") { put(&mut patch, "poster", keep(ctx, layout, &workspace_id, beside.poster.as_deref(), &now, "a film's poster")?.map(Value::from)); } if blank(&held_row, "backdrop") { put(&mut patch, "backdrop", keep(ctx, layout, &workspace_id, beside.backdrop.as_deref(), &now, "a film's backdrop")?.map(Value::from)); } } put(&mut patch, "chapters", film.chapters.as_deref().and_then(chapters_text).map(Value::from)); if let Some(nfo) = &beside.nfo { let filled = nfo_patch(nfo, table, &held_row); patch.extend(filled); } patched(ctx, table, &id, patch)?; queue(ctx, &workspace_id, &key, &stored, content_type, &now)?; let subtitles = keep_subtitles(ctx, layout, &workspace_id, &database, &folder, whole, &beside.subtitles, &now)?; let mut answer = json!({"sourcePath": film.source_path, "outcome": "better", "id": id, "table": table, "series": series_id, "key": key, "replaced": replaced, "title": title, "line": say("intake.better", &[("title", &title)])?}); said_beside(&mut answer, &subtitles, &beside, series_beside.as_ref()); answers.push(answer); continue; } // 4. A new film or episode: the row, its poster, then its file's key. // The poster beside a film before the frame the phone cut; an episode // takes no folder art, so its still is the frame. let poster = keep(ctx, layout, &workspace_id, beside.poster.as_deref().or(film.poster_path.as_deref()), &now, "a film's poster")?; let chapters = film.chapters.as_deref().and_then(chapters_text); let id = match &what { Made::Film { title, year, nfo_title, nfo_year } => { let mut data = Map::new(); // A title or a year the NFO gives is its patch's, said so. if !nfo_title { data.insert("title".into(), json!(title)); } if !nfo_year { put(&mut data, "year", year.clone().map(Value::from)); } data.insert("kind".into(), json!("film")); data.insert("status".into(), json!("want_to_watch")); data.insert("added_on".into(), json!(today)); put(&mut data, "minutes", film.minutes.map(|minutes| json!(minutes.round()))); put(&mut data, "poster", poster.map(Value::from)); put(&mut data, "backdrop", keep(ctx, layout, &workspace_id, beside.backdrop.as_deref(), &now, "a film's backdrop")?.map(Value::from)); put(&mut data, "chapters", chapters.map(Value::from)); if let Some(nfo) = &beside.nfo { let filled = nfo_patch(nfo, FILM_TABLE, &data); data.extend(filled); } made(ctx, FILM_TABLE, data)? } Made::Episode { season, episode, title, nfo_title, .. } => { let series_id = series_id.clone().ok_or("the series was found above")?; let season_id = seasons_made.get(&(series_id.clone(), *season)).cloned().ok_or("the season was found above")?; let mut data = Map::new(); data.insert("season".into(), json!(season_id)); data.insert("series".into(), json!(series_id)); data.insert("number".into(), json!(episode)); match title { Some(_) if *nfo_title => {} Some(title) => { data.insert("title".into(), json!(title)); } None => { data.insert("title".into(), json!(episode_title(*episode)?)); } } put(&mut data, "minutes", film.minutes.map(|minutes| json!(minutes.round()))); put(&mut data, "still", poster.map(Value::from)); put(&mut data, "chapters", chapters.map(Value::from)); if let Some(nfo) = &beside.nfo { let filled = nfo_patch(nfo, EPISODE_TABLE, &data); data.extend(filled); } made(ctx, EPISODE_TABLE, data)? } }; let key = if whole { film_whole_key(&database, &id, &ext) } else { film_source_key(&database, &id, &ext) }; patched(ctx, table, &id, file_patch(&key, whole, &stored.sha256, film))?; queue(ctx, &workspace_id, &key, &stored, content_type, &now)?; let subtitles = keep_subtitles(ctx, layout, &workspace_id, &database, &id, whole, &beside.subtitles, &now)?; let line_name = if whole { "intake.added" } else { "intake.converting" }; let mut answer = json!({"sourcePath": film.source_path, "outcome": "added", "id": id, "key": key, "table": table, "series": series_id, "needsMac": !whole, "title": title, "line": say(line_name, &[("title", &title)])?}); said_beside(&mut answer, &subtitles, &beside, series_beside.as_ref()); answers.push(answer); } let films_added = answers.iter().filter(|answer| answer["outcome"] == "added" && answer["table"] == FILM_TABLE).count(); let said = match (answers.as_slice(), episodes_by_series.len()) { ([one], _) => one["line"].clone(), (_, 1) if films_added == 0 => { let (series, count) = episodes_by_series.iter().next().expect("one series"); // Every one of them waiting for the Mac says so once, never a sentence per episode (android-finish, 25 Nov 2026). let converting = answers.iter().filter(|answer| answer["outcome"] == "added").all(|answer| answer["needsMac"] == true); let line = if converting { "intake.episodes_converting" } else { "intake.episodes_added" }; Value::from(say(line, &[("series", series), ("count", &count.to_string())])?) } _ => { let added = answers.iter().filter(|answer| answer["outcome"] == "added").count(); if added > 0 { Value::from(say("intake.added_many", &[("count", &added.to_string())])?) } else { answers.first().map(|answer| answer["line"].clone()).unwrap_or(Value::Null) } } }; Ok(json!({ "films": answers, "said": said })) } /// Bytes this phone now holds of a file the object already has: its ledger /// row says where they are, synced, so they are kept here and never queued up. fn kept_here(ctx: &mut Ctx<'_>, workspace_id: &str, key: &str, stored: &cotton_client::media::store::StoredMediaFile, content_type: &str, now: &str) -> Result<(), String> { cotton_store::media_ledger::enqueue_media( ctx.db(), &cotton_store::media_ledger::MediaEnqueueInput { key: key.to_string(), workspace_id: workspace_id.to_string(), sha256: stored.sha256.clone(), content_type: content_type.to_string(), size_bytes: i64::try_from(stored.size_bytes).unwrap_or(i64::MAX), local_path: Some(stored.path.to_string_lossy().to_string()), state: Some("synced".to_string()), after: None, after_row_id: None, tier: Some(cotton_store::media_holdings::Tier::Original), captured_here: true, now: now.to_string(), }, ) .map(|_| ()) .map_err(|error| error.to_string()) } /// What a film's or an episode's file says on its row: the stream it plays /// (a whole file) or the upload the Mac converts, and the file's facts. fn file_patch(key: &str, whole: bool, sha256: &str, film: &FilmIn) -> Map { let mut patch = Map::new(); if whole { patch.insert("file".into(), json!(key)); patch.insert("source_file".into(), Value::Null); patch.insert("needs_mac".into(), json!(false)); } else { patch.insert("source_file".into(), json!(key)); patch.insert("needs_mac".into(), json!(true)); } patch.insert("sha256".into(), json!(sha256)); put(&mut patch, "height", film.height.map(Value::from)); put(&mut patch, "bitrate", film.bitrate.map(Value::from)); patch } /// The patch an NFO makes on a row of `table` (`nfo_patch`): a film's, a /// series' and an episode's fills are all said in `filled_from`. fn nfo_patch(nfo: &Nfo, table: &str, row: &Map) -> Map { cotton_core::films::sidecars::nfo_patch(nfo, table, row) } /// A language as a subtitle's dotted word the rules read back as that /// language: a tag that is also a mark (Hindi's `hi`, the hearing-impaired /// mark) is written as its three-letter code. fn language_word(language: &str) -> String { let mark = SDH_WORDS.contains(&language) || FORCED_WORDS.contains(&language); LANGUAGES.iter().find(|(from, to)| mark && *to == language && from.len() == 3).map_or_else(|| language.to_string(), |(from, _)| from.to_string()) } /// A picture beside a film kept as a picture key, or nothing. fn keep(ctx: &mut Ctx<'_>, layout: &Layout, workspace_id: &str, path: Option<&std::path::Path>, now: &str, what: &str) -> Result, String> { path.map(|path| super::media::keep_picture(ctx, layout, workspace_id, path, now, what)).transpose() } fn blank(row: &Row, key: &str) -> bool { row.get(key).and_then(Value::as_str).is_none_or(|text| text.trim().is_empty()) } /// A series' own folder on its row: its `tvshow.nfo` fills only empty /// columns, its poster and fanart only an empty poster and backdrop. fn dress_series(ctx: &mut Ctx<'_>, layout: &Layout, workspace_id: &str, series_id: &str, beside: &Beside, now: &str) -> Result<(), String> { let row = rows_where(ctx, FILM_TABLE, "*", "id = ?", &[rusqlite::types::Value::Text(series_id.to_string())])?.into_iter().next().ok_or("the series was found above")?; let mut patch = Map::new(); if blank(&row, "poster") { put(&mut patch, "poster", keep(ctx, layout, workspace_id, beside.poster.as_deref(), now, "a series' poster")?.map(Value::from)); } if blank(&row, "backdrop") { put(&mut patch, "backdrop", keep(ctx, layout, workspace_id, beside.backdrop.as_deref(), now, "a series' backdrop")?.map(Value::from)); } if let Some(nfo) = &beside.nfo { patch.extend(nfo_patch(nfo, FILM_TABLE, &row)); } patched(ctx, FILM_TABLE, series_id, patch) } /// `/films//.[.forced][.sdh][.n].`: /// a subtitle beside its film's file in the film's own folder, named so the /// sidecar rules read it back beside `whole.` or `source.`. fn subtitle_key(database: &str, folder: &str, whole: bool, subtitle: &Subtitle, taken: &mut std::collections::BTreeSet) -> Option<(String, String)> { let ext = subtitle.file.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase())?; let stem = if whole { "whole" } else { "source" }; let mut words = language_word(&subtitle.language); if subtitle.forced { words.push_str(".forced"); } if subtitle.sdh { words.push_str(".sdh"); } let mut name = format!("{stem}.{words}.{ext}"); let mut n = 1; while !taken.insert(name.clone()) { n += 1; name = format!("{stem}.{words}.{n}.{ext}"); } Some((format!("{database}/films/{folder}/{name}"), ext)) } /// Each subtitle beside a film, into this device's store and queued up in the /// film's own folder. Answers their keys, in the rules' order. #[allow(clippy::too_many_arguments)] fn keep_subtitles(ctx: &mut Ctx<'_>, layout: &Layout, workspace_id: &str, database: &str, folder: &str, whole: bool, subtitles: &[(Subtitle, PathBuf)], now: &str) -> Result, String> { let mut taken = std::collections::BTreeSet::new(); let mut keys = Vec::new(); for (subtitle, path) in subtitles { let (key, ext) = subtitle_key(database, folder, whole, subtitle, &mut taken).ok_or_else(|| format!("{} names no extension", subtitle.file))?; let stored = put_media_file(layout, workspace_id, path, &ext).map_err(|error| io_refusal("a subtitle could not be copied into this device's store", path, &error))?; // WebVTT is a film folder's own type; SubRip and ASS go up as bytes. let content_type = if ext == "vtt" { "text/vtt" } else { "application/octet-stream" }; queue(ctx, workspace_id, &key, &stored, content_type, now)?; keys.push(key); } Ok(keys) } /// What a film's answer says of what lay beside it: the subtitles kept and /// any NFO that was no NFO. fn said_beside(answer: &mut Value, subtitles: &[String], beside: &Beside, series: Option<&Beside>) { if !subtitles.is_empty() { answer["subtitles"] = json!(subtitles); } let unread: Vec<&String> = beside.unread.iter().chain(series.into_iter().flat_map(|series| series.unread.iter())).collect(); if !unread.is_empty() { answer["nfoUnread"] = json!(unread); } } /// An episode with no title of its own is named by its number. fn episode_title(episode: u32) -> Result { line("intake.episode_title", &[("number", &episode.to_string())]).map_err(|failure| failure.message) } fn words(text: &Option) -> Option { text.as_deref().map(str::trim).filter(|text| !text.is_empty()).map(str::to_string) } fn number(row: &Row, key: &str) -> Option { row.get(key).and_then(Value::as_f64).map(|n| n as u32) } /// The series named `title`, found by its folded title or made. pub(crate) fn series_of(ctx: &mut Ctx<'_>, title: &str, today: &str, made_here: &mut BTreeMap) -> Result { if let Some(id) = made_here.get(title) { return Ok(id.clone()); } let id = match rows_where(ctx, FILM_TABLE, "id", "kind = 'series' AND lower(trim(title)) = ?", &[rusqlite::types::Value::Text(title.trim().to_lowercase())])?.into_iter().next() { Some(row) => text_of(&row, "id"), None => { let mut data = Map::new(); data.insert("title".into(), json!(title)); data.insert("kind".into(), json!("series")); data.insert("status".into(), json!("want_to_watch")); data.insert("added_on".into(), json!(today)); made(ctx, FILM_TABLE, data)? } }; made_here.insert(title.to_string(), id.clone()); Ok(id) } /// A series' season `number`, found or made. pub(crate) fn season_of(ctx: &mut Ctx<'_>, series: &str, number: u32, made_here: &mut BTreeMap<(String, u32), String>) -> Result { let wanted = (series.to_string(), number); if let Some(id) = made_here.get(&wanted) { return Ok(id.clone()); } let held = rows_where(ctx, SEASON_TABLE, "id", "film = ? AND number = ?", &[rusqlite::types::Value::Text(series.to_string()), rusqlite::types::Value::Integer(i64::from(number))])?; let id = match held.into_iter().next() { Some(row) => text_of(&row, "id"), None => { let mut data = Map::new(); data.insert("film".into(), json!(series)); data.insert("number".into(), json!(number)); data.insert("title".into(), json!(line("intake.season_title", &[("number", &number.to_string())]).map_err(|failure| failure.message)?)); made(ctx, SEASON_TABLE, data)? } }; made_here.insert(wanted, id.clone()); Ok(id) } #[cfg(test)] #[path = "film_intake_tests.rs"] mod tests;