Cotton code
514 lines · 23.1 KB · RustRaw
//! Films out: the tree Kodi, Jellyfin, Plex and Infuse read, with Kodi NFOs//! beside each film and episode, and what was watched in Trakt's watched//! export shape.//!//! ```text//! Films///!   <Title (Year)>///!     <Title (Year)>.<ext>          the film as stored: a whole file, or the//!                                   source waiting for the Mac//!     <Title (Year)>.m3u8           …or its HLS master, the renditions it//!     <Title (Year)>.hls/…          names under .hls/ as stored//!     <Title (Year)>.<lang>.vtt     each subtitle rendition, as a sidecar//!     <Title (Year)>.nfo            Kodi's movie NFO//!     poster.<ext>, fanart.<ext>//!   <Series>///!     tvshow.nfo, poster.<ext>, fanart.<ext>, seasonNN-poster.<ext>//!     Season NN///!       <Series> - SNNENN - <Title>.<ext>   (and .nfo, .<lang>.vtt, -thumb.<ext>)//!   trakt-watched.json              { movies: [...], shows: [...] }//! ```//!//! An HLS film's master is the one file rewritten: its URIs gain the//! `.hls/` folder its renditions sit in. Every playlist, segment and//! subtitle below it is copied as stored. A film is watched when its status//! says so or the watch log holds a finished watch: `playcount` is its//! finished watches (one when only its status says watched), `lastplayed` its//! latest watch.use std::collections::{BTreeMap, BTreeSet};use chrono::DateTime;use serde_json::{json, Map, Value as JsonValue};use super::{by_id, component, extension, json_number, number, plain_number, pretty, text, unique, xml, Out, Result, Row};pub(super) fn write(out: &mut Out) -> Result<()> {    let films = out.rows("film");    let seasons = out.rows("film_season");    let episodes = out.rows("film_episode");    let watches = out.rows("watch");    let log = WatchLog::of(&watches);    let seasons_by_id = by_id(&seasons);    let mut ordered: Vec<&Row> = films.iter().collect();    ordered.sort_by(|a, b| {        let title = |row: &Row| text(row, "title").unwrap_or_default().to_lowercase();        title(a).cmp(&title(b)).then_with(|| text(a, "year").cmp(&text(b, "year"))).then_with(|| text(a, "id").cmp(&text(b, "id")))    });    let mut taken = BTreeSet::new();    let mut movies = Vec::new();    let mut shows = Vec::new();    let mut series_ids = BTreeSet::new();    for film in ordered {        let id = text(film, "id").unwrap_or_default();        let series = text(film, "kind") == Some("series");        let named = match (text(film, "title"), text(film, "year")) {            (Some(title), Some(year)) if !series => format!("{title} ({year})"),            (Some(title), _) => title.to_string(),            (None, _) => String::new(),        };        let folder = unique(&mut taken, &component(Some(&named), "Untitled"));        if series {            series_ids.insert(id.to_string());            let mine: Vec<&Row> = episodes.iter().filter(|e| text(e, "series") == Some(id)).collect();            if let Some(show) = write_series(out, film, &folder, &mine, &seasons, &log)? {                shows.push(show);            }        } else {            let watched = log.of_film(film);            write_film(out, film, &folder, &watched)?;            if watched.plays > 0 {                movies.push((watched.last.clone(), id.to_string(), trakt_movie(film, &watched)));            }        }    }    // Episodes whose series is gone gather under the series' title they hold.    let mut orphans: BTreeMap<String, Vec<&Row>> = BTreeMap::new();    for episode in &episodes {        if text(episode, "series").is_some_and(|series| series_ids.contains(series)) {            continue;        }        let season_series = text(episode, "season").and_then(|id| seasons_by_id.get(id)).and_then(|s| text(s, "series_title"));        let title = text(episode, "series_title").or(season_series).unwrap_or("Unknown Series");        orphans.entry(title.to_string()).or_default().push(episode);    }    for (title, mine) in orphans {        let folder = unique(&mut taken, &component(Some(&title), "Unknown Series"));        let mut series = Row::new();        series.insert("title".into(), json!(title));        if let Some(show) = write_series(out, &series, &folder, &mine, &seasons, &log)? {            shows.push(show);        }    }    movies.sort_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1)));    shows.sort_by(|a, b| a["show"]["title"].as_str().cmp(&b["show"]["title"].as_str()));    let watched = json!({ "movies": movies.into_iter().map(|(_, _, m)| m).collect::<Vec<_>>(), "shows": shows });    out.write("Films/trakt-watched.json", pretty(&watched));    Ok(())}// ── the watch log ────────────────────────────────────────────────────────/// What the watch log says of one film or episode.#[derive(Debug, Default, Clone)]struct Watched {    /// Finished watches, or one when only the status says watched.    plays: u32,    /// The latest watch's start, as stored (an RFC 3339 instant or a day).    last: Option<String>,}struct WatchLog<'a> {    by_film: BTreeMap<&'a str, Vec<&'a Row>>,    by_episode: BTreeMap<&'a str, Vec<&'a Row>>,}impl<'a> WatchLog<'a> {    fn of(watches: &'a [Row]) -> Self {        let mut log = WatchLog { by_film: BTreeMap::new(), by_episode: BTreeMap::new() };        for watch in watches {            if let Some(episode) = text(watch, "episode") {                log.by_episode.entry(episode).or_default().push(watch);            } else if let Some(film) = text(watch, "film") {                log.by_film.entry(film).or_default().push(watch);            }        }        log    }    fn said(watches: Option<&Vec<&Row>>, row: &Row) -> Watched {        let watches = watches.map(Vec::as_slice).unwrap_or_default();        let finished = watches.iter().filter(|w| matches!(w.get("finished"), Some(JsonValue::Bool(true))) || number(w, "finished") == Some(1.0)).count() as u32;        let status = text(row, "status") == Some("watched");        let last = watches.iter().filter_map(|w| text(w, "started_at")).max_by_key(|at| trakt_time(at)).map(str::to_string).or_else(|| text(row, "watched_on").map(str::to_string));        let plays = if finished == 0 && status { 1 } else { finished };        Watched { plays, last: if plays > 0 || !watches.is_empty() { last } else { None } }    }    fn of_film(&self, film: &Row) -> Watched {        Self::said(text(film, "id").and_then(|id| self.by_film.get(id)), film)    }    fn of_episode(&self, episode: &Row) -> Watched {        Self::said(text(episode, "id").and_then(|id| self.by_episode.get(id)), episode)    }}/// Kodi's `lastplayed`: `YYYY-MM-DD HH:MM:SS` in UTC.fn kodi_time(value: &str) -> Option<String> {    if let Ok(instant) = DateTime::parse_from_rfc3339(value) {        return Some(instant.naive_utc().format("%Y-%m-%d %H:%M:%S").to_string());    }    let day = value.get(..10)?;    chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d").ok().map(|d| format!("{d} 00:00:00"))}/// Trakt's `last_watched_at`: RFC 3339 in UTC with milliseconds.fn trakt_time(value: &str) -> Option<String> {    if let Ok(instant) = DateTime::parse_from_rfc3339(value) {        return Some(instant.naive_utc().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string());    }    let day = value.get(..10)?;    chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d").ok().map(|d| format!("{d}T00:00:00.000Z"))}// ── one film ─────────────────────────────────────────────────────────────fn write_film(out: &mut Out, film: &Row, folder: &str, watched: &Watched) -> Result<()> {    let base = format!("Films/{folder}");    write_video(out, film, &base, folder)?;    out.write(&format!("{base}/{folder}.nfo"), movie_nfo(film, watched));    for (column, name) in [("poster", "poster"), ("backdrop", "fanart")] {        if let Some(media) = text(film, column) {            out.copy(media, &format!("{base}/{name}.{}", extension(media).unwrap_or_else(|| "jpg".into())));        }    }    Ok(())}/// A film's or an episode's video at `<base>/<stem>.<ext>`: its whole file,/// its HLS master and renditions with each subtitle as a sidecar, or the/// source waiting for the Mac. Nothing when it holds none.fn write_video(out: &mut Out, row: &Row, base: &str, stem: &str) -> Result<()> {    let Some(key) = text(row, "file").or_else(|| text(row, "source_file")) else { return Ok(()) };    let ext = extension(key).unwrap_or_else(|| "bin".into());    if ext != "m3u8" {        out.copy(key, &format!("{base}/{stem}.{ext}"));        return Ok(());    }    let Some(master) = out.read(key) else { return Ok(()) };    let folder = key.rsplit_once('/').map(|(dir, _)| dir).unwrap_or_default();    let hls = format!("{stem}.hls");    let mut copied = BTreeSet::new();    for uri in uris(&master) {        copy_rendition(out, folder, &uri, &format!("{base}/{hls}"), &mut copied)?;    }    out.write(&format!("{base}/{stem}.m3u8"), rewritten(&master, &hls));    // Each subtitle rendition beside the video, as Kodi and Jellyfin find one.    let mut names = BTreeSet::new();    for media in master.lines().filter(|l| l.starts_with("#EXT-X-MEDIA:") && attribute(l, "TYPE").as_deref() == Some("SUBTITLES")) {        let Some(playlist) = attribute(media, "URI") else { continue };        let Some(vtt) = joined(folder, &playlist).and_then(|p| out.read(&p)).and_then(|text| {            let dir = playlist.rsplit_once('/').map(|(d, _)| d.to_string()).unwrap_or_default();            uris(&text).into_iter().next().and_then(|segment| joined(folder, &if dir.is_empty() { segment } else { format!("{dir}/{segment}") }))        }) else {            continue;        };        let language = attribute(media, "LANGUAGE").filter(|l| !l.is_empty() && l != "und").unwrap_or_else(|| "und".into());        let forced = if attribute(media, "FORCED").as_deref() == Some("YES") { ".forced" } else { "" };        let name = unique(&mut names, &format!("{stem}.{language}{forced}"));        out.copy(&vtt, &format!("{base}/{name}.vtt"));    }    Ok(())}/// A playlist's URIs: every line that is not a tag, and every `URI="…"` a tag/// names.fn uris(playlist: &str) -> Vec<String> {    let mut found = Vec::new();    for line in playlist.lines().map(str::trim).filter(|l| !l.is_empty()) {        if line.starts_with('#') {            if let Some(uri) = attribute(line, "URI") {                found.push(uri);            }        } else {            found.push(line.to_string());        }    }    found}/// One attribute of an HLS tag line, unquoted.fn attribute(line: &str, name: &str) -> Option<String> {    let body = line.split_once(':')?.1;    let mut rest = body;    while !rest.is_empty() {        let (key, after) = rest.split_once('=')?;        let (value, next) = if let Some(quoted) = after.strip_prefix('"') {            let end = quoted.find('"')?;            (&quoted[..end], quoted[end + 1..].trim_start_matches(','))        } else {            after.split_once(',').unwrap_or((after, ""))        };        if key.trim() == name {            return Some(value.to_string());        }        rest = next;    }    None}/// A relative URI against a folder key, `None` when it climbs out of it or is/// absolute: a film's renditions are its own folder's.fn joined(folder: &str, uri: &str) -> Option<String> {    if uri.contains("://") || uri.starts_with('/') || uri.split('/').any(|part| part == ".." || part.is_empty()) {        return None;    }    Some(format!("{folder}/{uri}"))}/// One rendition (a media playlist and what it names, or a file) copied under/// `dest`, at its path relative to the master.fn copy_rendition(out: &mut Out, folder: &str, uri: &str, dest: &str, copied: &mut BTreeSet<String>) -> Result<()> {    let Some(key) = joined(folder, uri) else { return Ok(()) };    if !copied.insert(key.clone()) {        return Ok(());    }    if extension(uri).as_deref() != Some("m3u8") {        out.copy(&key, &format!("{dest}/{uri}"));        return Ok(());    }    let Some(text) = out.read(&key) else { return Ok(()) };    out.copy(&key, &format!("{dest}/{uri}"));    let dir = uri.rsplit_once('/').map(|(d, _)| d.to_string()).unwrap_or_default();    for inner in uris(&text) {        let at = if dir.is_empty() { inner } else { format!("{dir}/{inner}") };        copy_rendition(out, folder, &at, dest, copied)?;    }    Ok(())}/// The master with every relative URI under `hls/`.fn rewritten(master: &str, hls: &str) -> String {    let mut out = String::with_capacity(master.len() + 64);    for line in master.split_inclusive('\n') {        let (body, end) = line.strip_suffix('\n').map(|b| (b, "\n")).unwrap_or((line, ""));        let trimmed = body.trim();        if trimmed.is_empty() {            out.push_str(body);        } else if trimmed.starts_with('#') {            match attribute(trimmed, "URI") {                Some(uri) if joined("", &uri).is_some() => out.push_str(&body.replacen(&format!("URI=\"{uri}\""), &format!("URI=\"{hls}/{uri}\""), 1)),                _ => out.push_str(body),            }        } else if joined("", trimmed).is_some() {            out.push_str(&format!("{hls}/{trimmed}"));        } else {            out.push_str(body);        }        out.push_str(end);    }    out}// ── the NFOs ─────────────────────────────────────────────────────────────const NFO_HEAD: &str = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";fn tag(body: &mut String, name: &str, value: Option<&str>) {    if let Some(value) = value {        body.push_str(&format!("  <{name}>{}</{name}>\n", xml(value)));    }}/// Each of a list column's names (`Drama, Mystery`).fn each(row: &Row, column: &str) -> Vec<String> {    text(row, column).map(|v| v.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string).collect()).unwrap_or_default()}/// The ids a row holds as `uniqueid`s, the first one default.fn unique_ids(body: &mut String, row: &Row, kinds: &[&str]) {    let mut first = true;    for kind in kinds {        if let Some(value) = text(row, &format!("{kind}_id")) {            let default = if first { " default=\"true\"" } else { "" };            body.push_str(&format!("  <uniqueid type=\"{kind}\"{default}>{}</uniqueid>\n", xml(value)));            first = false;        }    }}fn watched_tags(body: &mut String, watched: &Watched) {    body.push_str(&format!("  <playcount>{}</playcount>\n", watched.plays));    tag(body, "lastplayed", watched.last.as_deref().and_then(kodi_time).as_deref());    body.push_str(&format!("  <watched>{}</watched>\n", watched.plays > 0));}/// Kodi's `userrating` (0 to 10) from Cotton's rating of 5.fn user_rating(body: &mut String, row: &Row) {    if let Some(rating) = number(row, "rating").filter(|r| *r > 0.0) {        tag(body, "userrating", Some(&plain_number((rating * 2.0).round())));    }}fn movie_nfo(film: &Row, watched: &Watched) -> String {    let mut body = format!("{NFO_HEAD}<movie>\n");    tag(&mut body, "title", text(film, "title"));    tag(&mut body, "originaltitle", text(film, "original_title"));    tag(&mut body, "year", text(film, "year"));    tag(&mut body, "plot", text(film, "synopsis"));    tag(&mut body, "runtime", number(film, "minutes").map(plain_number).as_deref());    tag(&mut body, "mpaa", text(film, "certificate"));    user_rating(&mut body, film);    unique_ids(&mut body, film, &["tmdb", "imdb", "tvdb"]);    for genre in each(film, "genres") {        tag(&mut body, "genre", Some(&genre));    }    for country in each(film, "country") {        tag(&mut body, "country", Some(&country));    }    for director in each(film, "director") {        tag(&mut body, "director", Some(&director));    }    watched_tags(&mut body, watched);    for actor in each(film, "cast") {        body.push_str(&format!("  <actor>\n    <name>{}</name>\n  </actor>\n", xml(&actor)));    }    body.push_str("</movie>\n");    body}fn tvshow_nfo(series: &Row) -> String {    let mut body = format!("{NFO_HEAD}<tvshow>\n");    tag(&mut body, "title", text(series, "title"));    tag(&mut body, "originaltitle", text(series, "original_title"));    tag(&mut body, "year", text(series, "year"));    tag(&mut body, "plot", text(series, "synopsis"));    tag(&mut body, "mpaa", text(series, "certificate"));    user_rating(&mut body, series);    unique_ids(&mut body, series, &["tvdb", "tmdb", "imdb"]);    for genre in each(series, "genres") {        tag(&mut body, "genre", Some(&genre));    }    for actor in each(series, "cast") {        body.push_str(&format!("  <actor>\n    <name>{}</name>\n  </actor>\n", xml(&actor)));    }    body.push_str("</tvshow>\n");    body}fn episode_nfo(episode: &Row, season: u32, number_: u32, watched: &Watched) -> String {    let mut body = format!("{NFO_HEAD}<episodedetails>\n");    tag(&mut body, "title", text(episode, "title"));    tag(&mut body, "season", Some(&season.to_string()));    tag(&mut body, "episode", Some(&number_.to_string()));    tag(&mut body, "plot", text(episode, "synopsis"));    tag(&mut body, "runtime", number(episode, "minutes").map(plain_number).as_deref());    tag(&mut body, "aired", text(episode, "aired"));    user_rating(&mut body, episode);    unique_ids(&mut body, episode, &["tvdb", "tmdb"]);    watched_tags(&mut body, watched);    body.push_str("</episodedetails>\n");    body}// ── one series ───────────────────────────────────────────────────────────/// A series' folder: its NFO and art, each season's poster, each episode in/// its season's folder. Answers its Trakt show when an episode was watched.fn write_series(out: &mut Out, series: &Row, folder: &str, episodes: &[&Row], seasons: &[Row], log: &WatchLog) -> Result<Option<JsonValue>> {    let base = format!("Films/{folder}");    out.write(&format!("{base}/tvshow.nfo"), tvshow_nfo(series));    for (column, name) in [("poster", "poster"), ("backdrop", "fanart")] {        if let Some(media) = text(series, column) {            out.copy(media, &format!("{base}/{name}.{}", extension(media).unwrap_or_else(|| "jpg".into())));        }    }    let seasons_by_id = by_id(seasons);    let series_id = text(series, "id");    let mut season_rows: Vec<&Row> = seasons.iter().filter(|s| series_id.is_some() && text(s, "film") == series_id).collect();    season_rows.sort_by(|a, b| number(a, "number").unwrap_or(f64::MAX).total_cmp(&number(b, "number").unwrap_or(f64::MAX)));    for season in season_rows {        if let (Some(media), Some(n)) = (text(season, "poster"), number(season, "number")) {            out.copy(media, &format!("{base}/season{:02}-poster.{}", n as u32, extension(media).unwrap_or_else(|| "jpg".into())));        }    }    let season_of = |episode: &Row| -> u32 {        text(episode, "season")            .and_then(|id| seasons_by_id.get(id))            .and_then(|s| number(s, "number"))            .or_else(|| number(episode, "season_number"))            .filter(|n| *n >= 0.0)            .map(|n| n as u32)            .unwrap_or(1)    };    let mut ordered: Vec<(u32, u32, &Row)> = episodes.iter().map(|e| (season_of(e), number(e, "number").filter(|n| *n >= 0.0).map(|n| n as u32).unwrap_or(0), *e)).collect();    ordered.sort_by(|a, b| (a.0, a.1, text(a.2, "id")).cmp(&(b.0, b.1, text(b.2, "id"))));    let series_name = folder.to_string();    let series_title = text(series, "title").map(str::to_string).unwrap_or_else(|| series_name.clone());    let mut names = BTreeSet::new();    let mut trakt_seasons: BTreeMap<u32, Vec<JsonValue>> = BTreeMap::new();    let mut plays = 0;    let mut last: Option<String> = None;    for (season, n, episode) in ordered {        let title = text(episode, "title").map(|t| format!(" - {t}")).unwrap_or_default();        let stem = unique(&mut names, &component(Some(&format!("{series_title} - S{season:02}E{n:02}{title}")), "Episode"));        let at = format!("{base}/Season {season:02}");        let watched = log.of_episode(episode);        write_video(out, episode, &at, &stem)?;        out.write(&format!("{at}/{stem}.nfo"), episode_nfo(episode, season, n, &watched));        if let Some(media) = text(episode, "still") {            out.copy(media, &format!("{at}/{stem}-thumb.{}", extension(media).unwrap_or_else(|| "jpg".into())));        }        if watched.plays > 0 {            plays += watched.plays;            if watched.last.as_deref().and_then(trakt_time) > last.as_deref().and_then(trakt_time) {                last = watched.last.clone();            }            let mut entry = Map::new();            entry.insert("number".into(), json!(n));            entry.insert("plays".into(), json!(watched.plays));            if let Some(at) = watched.last.as_deref().and_then(trakt_time) {                entry.insert("last_watched_at".into(), json!(at));            }            trakt_seasons.entry(season).or_default().push(JsonValue::Object(entry));        }    }    if plays == 0 {        return Ok(None);    }    let mut show = Map::new();    show.insert("plays".into(), json!(plays));    if let Some(at) = last.as_deref().and_then(trakt_time) {        show.insert("last_watched_at".into(), json!(at));    }    show.insert("show".into(), trakt_item(series, &series_title, &["tvdb", "imdb", "tmdb"]));    show.insert("seasons".into(), JsonValue::Array(trakt_seasons.into_iter().map(|(number, episodes)| json!({ "number": number, "episodes": episodes })).collect()));    Ok(Some(JsonValue::Object(show)))}// ── Trakt ────────────────────────────────────────────────────────────────/// A Trakt movie or show: its title, its year as a number, the ids it holds/// (TMDB and TheTVDB as numbers, IMDb as text).fn trakt_item(row: &Row, title: &str, kinds: &[&str]) -> JsonValue {    let mut ids = Map::new();    for kind in kinds {        if let Some(value) = text(row, &format!("{kind}_id")) {            let id = match (*kind, value.parse::<f64>()) {                ("imdb", _) | (_, Err(_)) => json!(value),                (_, Ok(n)) => json_number(n),            };            ids.insert((*kind).into(), id);        }    }    let mut item = Map::new();    item.insert("title".into(), json!(title));    if let Some(year) = text(row, "year").and_then(|y| y.parse::<f64>().ok()) {        item.insert("year".into(), json_number(year));    }    item.insert("ids".into(), JsonValue::Object(ids));    JsonValue::Object(item)}fn trakt_movie(film: &Row, watched: &Watched) -> JsonValue {    let mut movie = Map::new();    movie.insert("plays".into(), json!(watched.plays));    if let Some(at) = watched.last.as_deref().and_then(trakt_time) {        movie.insert("last_watched_at".into(), json!(at));    }    movie.insert("movie".into(), trakt_item(film, text(film, "title").unwrap_or("Untitled"), &["imdb", "tmdb", "tvdb"]));    JsonValue::Object(movie)}