Cotton code
483 lines · 21.7 KB · RustRaw
//! The files every other player writes beside a film (open standards, 7 Nov//! 2026): a Kodi or Jellyfin NFO, external subtitles, a poster and a//! fanart. One rule list for every door: the phone's Add a folder reads a//! folder by these, and the Mac's `pnpm film:import` by the film//! importer's NFO reader, which mirrors this file; both answer//! `tests/fixtures/film_sidecars.json` alike (its `lists` too), so a rule//! changed here is changed there, never one alone.//!//! - Beside `Night Ferry (2019).mkv`: `Night Ferry (2019).nfo`, else//!   `movie.nfo`; an episode's own `<episode>.nfo` only; a series'//!   `tvshow.nfo` in its folder (above `Season NN`).//! - Subtitles `<name>.<lang>.srt|vtt|ass|ssa` (and a bare `<name>.srt`,//!   language unknown); `forced` and `sdh`/`cc`/`hi` among the dotted words//!   say so.//! - The poster `<name>-poster.jpg|png`, else `poster.jpg|png`, else//!   `folder.jpg|png`; the backdrop `<name>-fanart.jpg|png`, else//!   `fanart.jpg|png`. An episode takes no folder art: it is its series'.//! - The NFO (Kodi's shape: `movie`, `tvshow` or `episodedetails`; or a//!   file holding only an IMDb or a TMDB address) fills only EMPTY columns,//!   ids first, each fill said in `filled_from` as `nfo`: a column the person//!   edited is never overwritten, and an id the NFO gives makes Find details//!   look up by id, never by title.//!//! Pure: no file is read here; the caller hands names and text.use quick_xml::events::Event;use quick_xml::Reader;use serde::{Deserialize, Serialize};use serde_json::{json, Map, Value};/// A film's own NFO when its folder holds one film.pub const FILM_NFO: &str = "movie.nfo";/// A series' NFO, in the series' folder.pub const SERIES_NFO: &str = "tvshow.nfo";/// The extensions an external subtitle comes in.pub const SUBTITLE_EXTENSIONS: [&str; 4] = ["srt", "vtt", "ass", "ssa"];/// The extensions a poster or a fanart comes in.pub const ART_EXTENSIONS: [&str; 2] = ["jpg", "png"];/// A folder's poster, by name without extension, in the order looked for.pub const POSTER_NAMES: [&str; 2] = ["poster", "folder"];/// A folder's backdrop, by name without extension.pub const BACKDROP_NAMES: [&str; 1] = ["fanart"];/// The words among a subtitle's dotted words that mark it forced.pub const FORCED_WORDS: [&str; 1] = ["forced"];/// The words that mark it for the deaf and hard of hearing.pub const SDH_WORDS: [&str; 3] = ["sdh", "cc", "hi"];/// The id kinds an NFO's `uniqueid` gives that a film row holds.pub const ID_KINDS: [&str; 3] = ["tmdb", "imdb", "tvdb"];/// What `filled_from` says of a fill an NFO made.pub const FROM_NFO: &str = "nfo";/// ISO 639-2 (what MKV and many subtitle names say) to the BCP 47 tag HLS/// wants, for the languages a film comes in most (the Mac's/// film importer's `LANGUAGES`).pub const LANGUAGES: [(&str, &str); 67] = [    ("eng", "en"), ("hin", "hi"), ("tam", "ta"), ("tel", "te"), ("mal", "ml"), ("kan", "kn"), ("ben", "bn"), ("mar", "mr"), ("urd", "ur"), ("pan", "pa"), ("guj", "gu"),    ("fre", "fr"), ("fra", "fr"), ("ger", "de"), ("deu", "de"), ("spa", "es"), ("ita", "it"), ("por", "pt"), ("rus", "ru"), ("jpn", "ja"), ("kor", "ko"), ("chi", "zh"), ("zho", "zh"),    ("ara", "ar"), ("dut", "nl"), ("nld", "nl"), ("swe", "sv"), ("nor", "no"), ("nob", "nb"), ("dan", "da"), ("fin", "fi"), ("pol", "pl"), ("tur", "tr"), ("gre", "el"), ("ell", "el"),    ("heb", "he"), ("tha", "th"), ("vie", "vi"), ("ind", "id"), ("may", "ms"), ("msa", "ms"), ("ukr", "uk"), ("cze", "cs"), ("ces", "cs"), ("hun", "hu"), ("rum", "ro"), ("ron", "ro"),    ("per", "fa"), ("fas", "fa"), ("ice", "is"), ("isl", "is"), ("bul", "bg"), ("hrv", "hr"), ("srp", "sr"), ("slo", "sk"), ("slk", "sk"), ("slv", "sl"), ("est", "et"), ("lav", "lv"), ("lit", "lt"),    ("english", "en"), ("hindi", "hi"), ("french", "fr"), ("german", "de"), ("spanish", "es"), ("italian", "it"), ("tamil", "ta"),];/// The lists as the shared fixture holds them (`lists`): the drift check of/// the two sides.pub fn lists() -> Value {    json!({        "film_nfo": FILM_NFO,        "series_nfo": SERIES_NFO,        "subtitle_extensions": SUBTITLE_EXTENSIONS,        "art_extensions": ART_EXTENSIONS,        "poster_names": POSTER_NAMES,        "backdrop_names": BACKDROP_NAMES,        "forced_words": FORCED_WORDS,        "sdh_words": SDH_WORDS,        "id_kinds": ID_KINDS,        "languages": LANGUAGES.iter().map(|(from, to)| (from.to_string(), Value::from(*to))).collect::<Map<String, Value>>(),    })}/// One external subtitle beside a film.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Subtitle {    /// The file's name in the folder.    pub file: String,    /// Its BCP 47 language, `und` when its name says none.    pub language: String,    #[serde(default, skip_serializing_if = "std::ops::Not::not")]    pub forced: bool,    #[serde(default, skip_serializing_if = "std::ops::Not::not")]    pub sdh: bool,}/// What lies beside one film or episode, by file name in its folder.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct Sidecars {    #[serde(default, skip_serializing_if = "Option::is_none")]    pub nfo: Option<String>,    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub subtitles: Vec<Subtitle>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub poster: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub backdrop: Option<String>,}/// One chapter of a film, as a row's `chapters` holds them (a JSON list):/// where it starts and what it is called. The Mac reads them from ffprobe/// (the film importer's `chaptersOf`); the phone takes them from the caller,/// which read the file's own chapter marks. One shape for both.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Chapter {    #[serde(alias = "startMs")]    pub start_ms: u64,    pub title: String,}/// A row's `chapters` text: the list as JSON, `None` for fewer than two (a/// film of one chapter has none worth naming, as the Mac says).pub fn chapters_text(chapters: &[Chapter]) -> Option<String> {    (chapters.len() > 1).then(|| serde_json::to_string(chapters).expect("chapters are plain"))}/// A file name's stem and its lower-cased extension.fn split_ext(name: &str) -> Option<(&str, String)> {    let at = name.rfind('.').filter(|at| *at > 0)?;    Some((&name[..at], name[at + 1..].to_ascii_lowercase()))}/// The sibling whose name is one of `wanted` (stem and extension, any case),/// in `wanted`'s order.fn first_named(siblings: &[String], wanted: &[String]) -> Option<String> {    wanted.iter().find_map(|want| siblings.iter().find(|name| name.eq_ignore_ascii_case(want)).cloned())}fn art(stems: &[String]) -> Vec<String> {    stems.iter().flat_map(|stem| ART_EXTENSIONS.iter().map(move |ext| format!("{stem}.{ext}"))).collect()}/// A dotted word of a subtitle's name as a language: an ISO 639-2 code or an/// English name made BCP 47, a BCP 47 tag kept; `None` for any other word.pub fn language_of(word: &str) -> Option<String> {    let lower = word.trim().to_ascii_lowercase();    if let Some((_, tag)) = LANGUAGES.iter().find(|(from, _)| *from == lower) {        return Some(tag.to_string());    }    let mut parts = lower.split('-');    let head = parts.next()?;    let head_ok = (2..=3).contains(&head.len()) && head.chars().all(|c| c.is_ascii_lowercase());    let rest_ok = parts.all(|part| (2..=8).contains(&part.len()) && part.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()));    (head_ok && rest_ok && !matches!(head, "und" | "unk" | "mis" | "zxx")).then_some(lower)}/// The language a lone subtitle file's name says, for one the person gave/// (Cinemas' Give subtitles): the dotted words just before its extension,/// marks (`forced`, `sdh`) passed over, read as a language only when the/// rules know it by name or by its tag (`Film.en.srt`, `Film.eng.forced.srt`,/// `Film.pt-br.vtt`). A word of the title (`The.Matrix.srt`) is no language.pub fn given_language(name: &str) -> Option<String> {    let name = name.rsplit('/').next().unwrap_or(name);    let (stem, _) = split_ext(name)?;    for word in stem.rsplit('.').take(3) {        let lower = word.trim().to_ascii_lowercase();        if FORCED_WORDS.contains(&lower.as_str()) || SDH_WORDS.contains(&lower.as_str()) {            continue;        }        if let Some((_, tag)) = LANGUAGES.iter().find(|(from, _)| *from == lower) {            return Some(tag.to_string());        }        let head = lower.split('-').next().unwrap_or_default();        return (LANGUAGES.iter().any(|(_, tag)| *tag == head) && language_of(&lower).is_some()).then_some(lower);    }    None}/// A subtitle's language and marks from the dotted words between the film's/// name and the extension.fn subtitle_of(file: &str, words: &str) -> Subtitle {    let mut subtitle = Subtitle { file: file.to_string(), language: "und".into(), forced: false, sdh: false };    let mut named = false;    for word in words.split('.').map(str::trim).filter(|word| !word.is_empty()) {        let lower = word.to_ascii_lowercase();        if FORCED_WORDS.contains(&lower.as_str()) {            subtitle.forced = true;        } else if SDH_WORDS.contains(&lower.as_str()) {            subtitle.sdh = true;        } else if !named {            if let Some(language) = language_of(word) {                subtitle.language = language;                named = true;            }        }    }    subtitle}/// What lies beside the video `video` (its name, or its path: only the last/// part is read) among `siblings`, the names of the other files in its/// folder. An episode (`episode` true) takes its own NFO only and no folder/// art. Subtitles are in name order.pub fn sidecars(video: &str, siblings: &[String], episode: bool) -> Sidecars {    let name = video.rsplit('/').next().unwrap_or(video);    let Some((stem, _)) = split_ext(name) else { return Sidecars::default() };    let mut nfos = vec![format!("{stem}.nfo")];    if !episode {        nfos.push(FILM_NFO.into());    }    let nfo = first_named(siblings, &nfos);    let prefix = format!("{}.", stem.to_lowercase());    let mut subtitles: Vec<Subtitle> = siblings        .iter()        .filter_map(|sibling| {            let (sub_stem, ext) = split_ext(sibling)?;            if !SUBTITLE_EXTENSIONS.contains(&ext.as_str()) {                return None;            }            let lower = sub_stem.to_lowercase();            if lower == stem.to_lowercase() {                return Some(subtitle_of(sibling, ""));            }            lower.starts_with(&prefix).then(|| subtitle_of(sibling, &sub_stem[prefix.len()..]))        })        .collect();    subtitles.sort_by(|a, b| a.file.cmp(&b.file));    let own = |kind: &str| art(&[format!("{stem}-{kind}")]);    let (poster, backdrop) = if episode {        (None, None)    } else {        let folder_posters: Vec<String> = POSTER_NAMES.iter().map(|n| n.to_string()).collect();        let folder_backdrops: Vec<String> = BACKDROP_NAMES.iter().map(|n| n.to_string()).collect();        (            first_named(siblings, &[own("poster"), art(&folder_posters)].concat()),            first_named(siblings, &[own("fanart"), art(&folder_backdrops)].concat()),        )    };    Sidecars { nfo, subtitles, poster, backdrop }}/// What lies in a series' folder for the series itself: `tvshow.nfo`, its/// poster and its fanart.pub fn series_sidecars(siblings: &[String]) -> Sidecars {    let posters: Vec<String> = POSTER_NAMES.iter().map(|n| n.to_string()).collect();    let backdrops: Vec<String> = BACKDROP_NAMES.iter().map(|n| n.to_string()).collect();    Sidecars {        nfo: first_named(siblings, &[SERIES_NFO.to_string()]),        subtitles: Vec::new(),        poster: first_named(siblings, &art(&posters)),        backdrop: first_named(siblings, &art(&backdrops)),    }}/// One id an NFO gives.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct NfoId {    pub kind: String,    pub value: String,}/// What an NFO says, the parts a film row holds.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct Nfo {    /// `movie`, `tvshow`, `episodedetails`, or `url` for a file holding only    /// an address.    pub kind: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub title: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub original_title: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub year: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub plot: Option<String>,    /// Minutes.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub runtime: Option<u32>,    /// The `default` one first, then in the file's order; one of each kind.    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub ids: Vec<NfoId>,    /// YYYY-MM-DD: an episode's `aired`, a film's `premiered`.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub aired: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub season: Option<u32>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub episode: Option<u32>,}impl Nfo {    /// The id of one kind, if the NFO gives it.    pub fn id(&self, kind: &str) -> Option<&str> {        self.ids.iter().find(|id| id.kind == kind).map(|id| id.value.as_str())    }}const ROOTS: [&str; 3] = ["movie", "tvshow", "episodedetails"];fn date_of(text: &str) -> Option<String> {    let text = text.trim();    let ok = text.len() >= 10 && text.as_bytes()[4] == b'-' && text.as_bytes()[7] == b'-' && text[..10].chars().enumerate().all(|(at, c)| at == 4 || at == 7 || c.is_ascii_digit());    ok.then(|| text[..10].to_string())}fn year_of(text: &str) -> Option<String> {    let text = text.trim();    (text.len() >= 4 && text[..4].chars().all(|c| c.is_ascii_digit()) && (text.starts_with("19") || text.starts_with("20"))).then(|| text[..4].to_string())}fn leading_number(text: &str) -> Option<u32> {    let digits: String = text.trim().chars().take_while(char::is_ascii_digit).collect();    digits.parse().ok()}/// An id's value as a row holds it: IMDb's `tt…`, the others digits.fn id_value(kind: &str, value: &str) -> Option<String> {    let value = value.trim();    let ok = match kind {        "imdb" => value.len() > 2 && value.starts_with("tt") && value[2..].chars().all(|c| c.is_ascii_digit()),        _ => !value.is_empty() && value.chars().all(|c| c.is_ascii_digit()),    };    ok.then(|| value.to_string())}/// An NFO that is only an address (Kodi takes one): an IMDb title or a TMDB/// film or series.fn url_nfo(text: &str) -> Option<Nfo> {    let imdb = regex::Regex::new(r"imdb\.com/title/(tt\d+)").expect("the IMDb address");    let tmdb = regex::Regex::new(r"themoviedb\.org/(?:movie|tv)/(\d+)").expect("the TMDB address");    let mut ids = Vec::new();    if let Some(found) = tmdb.captures(text) {        ids.push(NfoId { kind: "tmdb".into(), value: found[1].to_string() });    }    if let Some(found) = imdb.captures(text) {        ids.push(NfoId { kind: "imdb".into(), value: found[1].to_string() });    }    (!ids.is_empty()).then(|| Nfo { kind: "url".into(), ids, ..Nfo::default() })}/// What an NFO's text says: Kodi's XML (the first `movie`, `tvshow` or/// `episodedetails`, its own children only, never an actor's or a set's), or/// a file holding only an IMDb or TMDB address. `None` for neither.pub fn read_nfo(text: &str) -> Option<Nfo> {    let text = text.trim_start_matches('\u{feff}');    let mut reader = Reader::from_str(text);    let mut nfo: Option<Nfo> = None;    // (uniqueid kind, default?) of the uniqueid being read.    let mut unique: Option<(String, bool)> = None;    let mut ids: Vec<(String, String, bool)> = Vec::new();    let mut depth = 0usize;    let mut field: Option<String> = None;    let mut said = String::new();    let mut fields: Vec<(String, String)> = Vec::new();    loop {        match reader.read_event() {            Ok(Event::Start(start)) => {                let name = String::from_utf8_lossy(start.local_name().as_ref()).to_ascii_lowercase();                depth += 1;                if nfo.is_none() && depth == 1 {                    if !ROOTS.contains(&name.as_str()) {                        break;                    }                    nfo = Some(Nfo { kind: name, ..Nfo::default() });                } else if nfo.is_some() && depth == 2 {                    said.clear();                    if name == "uniqueid" {                        let attr = |key: &[u8]| {                            start.attributes().flatten().find(|a| a.key.local_name().as_ref().eq_ignore_ascii_case(key)).and_then(|a| cotton_rules::xml_text::attribute_value(&a).map(|v| v.trim().to_ascii_lowercase()))                        };                        unique = Some((attr(b"type").unwrap_or_default(), attr(b"default").as_deref() == Some("true")));                    }                    field = Some(name);                }            }            Ok(Event::Text(text)) if depth == 2 && field.is_some() => {                if let Ok(text) = text.decode() {                    said.push_str(&text);                }            }            Ok(Event::GeneralRef(reference)) if depth == 2 && field.is_some() => said.push_str(&cotton_rules::xml_text::reference_text(&reference)),            Ok(Event::CData(text)) if depth == 2 && field.is_some() => said.push_str(&String::from_utf8_lossy(&text)),            Ok(Event::End(_)) => {                if depth == 2 {                    if let Some(name) = field.take() {                        let value = said.trim().to_string();                        if name == "uniqueid" {                            let (kind, default) = unique.take().unwrap_or_default();                            let kind = if kind.is_empty() && value.starts_with("tt") { "imdb".to_string() } else { kind };                            ids.push((kind, value, default));                        } else if !value.is_empty() {                            fields.push((name, value));                        }                    }                }                depth = depth.saturating_sub(1);                if depth == 0 && nfo.is_some() {                    break;                }            }            Ok(Event::Eof) | Err(_) => break,            _ => {}        }    }    let Some(mut nfo) = nfo else { return url_nfo(text) };    let first = |key: &str| fields.iter().find(|(name, _)| name == key).map(|(_, value)| value.clone());    nfo.title = first("title");    nfo.original_title = first("originaltitle");    nfo.plot = first("plot").or_else(|| first("outline"));    nfo.runtime = first("runtime").and_then(|r| leading_number(&r)).filter(|r| *r > 0);    nfo.aired = first("aired").or_else(|| first("premiered")).and_then(|d| date_of(&d));    nfo.year = first("year").and_then(|y| year_of(&y)).or_else(|| nfo.aired.as_deref().and_then(year_of));    nfo.season = first("season").and_then(|s| leading_number(&s));    nfo.episode = first("episode").and_then(|e| leading_number(&e));    // An old NFO's `<id>tt…</id>` is its IMDb id.    if let Some(old) = first("id").filter(|id| id.starts_with("tt")) {        ids.push(("imdb".into(), old, false));    }    let mut ordered: Vec<&(String, String, bool)> = ids.iter().filter(|(_, _, default)| *default).collect();    ordered.extend(ids.iter().filter(|(_, _, default)| !*default));    for (kind, value, _) in ordered {        if !ID_KINDS.contains(&kind.as_str()) || nfo.ids.iter().any(|id| &id.kind == kind) {            continue;        }        if let Some(value) = id_value(kind, value) {            nfo.ids.push(NfoId { kind: kind.clone(), value });        }    }    Some(nfo)}/// What an NFO gives a row of `table` (`film` or `film_episode`), in its/// columns, ids first; empty ones left out. An original title the same as/// the title says nothing.pub fn nfo_columns(nfo: &Nfo, table: &str) -> Map<String, Value> {    let mut out = Map::new();    let mut put = |key: &str, value: Option<Value>| {        if let Some(value) = value {            out.insert(key.to_string(), value);        }    };    let id = |kind: &str| nfo.id(kind).map(Value::from);    put("tmdb_id", id("tmdb"));    if table == "film" {        put("imdb_id", id("imdb"));    }    put("tvdb_id", id("tvdb"));    put("title", nfo.title.clone().map(Value::from));    put("synopsis", nfo.plot.clone().map(Value::from));    put("minutes", nfo.runtime.map(Value::from));    if table == "film" {        put("original_title", nfo.original_title.clone().filter(|o| Some(o) != nfo.title.as_ref()).map(Value::from));        put("year", nfo.year.clone().map(Value::from));    } else {        put("aired", nfo.aired.clone().map(Value::from));    }    out}fn blank(value: Option<&Value>) -> bool {    match value {        None | Some(Value::Null) => true,        Some(Value::String(text)) => text.trim().is_empty(),        _ => false,    }}/// The patch an NFO makes on a row as it stands (`row`, its data): only its/// empty columns, each said in `filled_from` as `nfo` beside what it said/// already. Empty when the NFO fills nothing.pub fn nfo_patch(nfo: &Nfo, table: &str, row: &Map<String, Value>) -> Map<String, Value> {    let mut patch: Map<String, Value> = nfo_columns(nfo, table).into_iter().filter(|(key, _)| blank(row.get(key))).collect();    if patch.is_empty() {        return patch;    }    let mut from: Map<String, Value> = row.get("filled_from").and_then(Value::as_str).and_then(|text| serde_json::from_str(text).ok()).unwrap_or_default();    for key in patch.keys() {        from.insert(key.clone(), Value::from(FROM_NFO));    }    patch.insert("filled_from".into(), Value::from(Value::Object(from).to_string()));    patch}#[cfg(test)]#[path = "sidecars_tests.rs"]mod tests;