//! Cotton Cinemas' intake rules, one place for every door (Cinemas //! definition, 4 Nov 2026, section 6): what a film file's path says (a film //! and its year, or a series' episode), which files are films at all, which //! the phone may send whole and which wait for the Mac, and which of two //! files of one film is kept. //! //! Pure: no file is read here. The phone hands what AVFoundation read of a //! file, the Mac verb what ffprobe read (the film importer mirrors //! [`from_path`], and both are tested against //! `tests/fixtures/film_names.json`). //! //! - A path is read right to left: `Series Name/Season 02/S02E05 - Title.mkv` //! is an episode, `Film (2019).mkv` or `Film.2019.1080p.BluRay.mkv` a film. //! A sample or an extras folder is nothing. //! - A file arriving in Cotton is a film when it runs twenty minutes or more //! or is an MKV or an AVI ([`is_film`]); in Cotton Cinemas every video is. //! - An MP4 or a MOV holding H.264 or HEVC with AAC plays on the phone as it //! is, so it goes up whole ([`plays_whole`]); anything else needs the Mac. //! - The same title and year twice keeps the better file ([`better`]): the //! taller picture, then the higher bitrate. use serde::{Deserialize, Serialize}; pub mod sidecars; /// The extensions a film file comes in. pub const VIDEO_EXTENSIONS: [&str; 12] = ["mp4", "m4v", "mov", "mkv", "avi", "webm", "ts", "m2ts", "wmv", "mpg", "mpeg", "flv"]; /// The containers the phone plays as they are, sent up whole. pub const WHOLE_EXTENSIONS: [&str; 3] = ["mp4", "m4v", "mov"]; /// A video shorter than this is a clip, not a film, when it arrives in /// Cotton (Photos keeps it). pub const FILM_MINUTES: f64 = 20.0; /// Folders whose files are never films of the library: a release's samples /// and extras. const SKIPPED_FOLDERS: [&str; 8] = ["sample", "samples", "extras", "featurettes", "trailers", "behind the scenes", "deleted scenes", "subs"]; /// Words a release name carries after its title and year, where the title /// ends when no year says so. const RELEASE_WORDS: [&str; 26] = [ "480p", "576p", "720p", "1080p", "1080i", "2160p", "4k", "uhd", "bluray", "blu-ray", "brrip", "bdrip", "dvdrip", "webrip", "web-dl", "webdl", "hdtv", "x264", "x265", "h264", "h265", "hevc", "hdr", "remux", "proper", "repack", ]; /// What a film file's path says. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum FilmPath { Film { title: String, #[serde(default, skip_serializing_if = "Option::is_none")] year: Option, }, Episode { series: String, season: u32, episode: u32, #[serde(default, skip_serializing_if = "Option::is_none")] title: Option, }, } /// The lower-cased extension of a path's file, if it has one. pub fn extension(path: &str) -> Option { let file = path.rsplit('/').next()?; let at = file.rfind('.').filter(|at| *at > 0)?; Some(file[at + 1..].to_ascii_lowercase()) } /// Whether a file of this extension is a video a film can be. pub fn is_video(ext: &str) -> bool { VIDEO_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()) } /// In Cotton, whether a video that came in is a film (not a clip for /// Photos): twenty minutes or more, or a container no camera writes. A /// length nobody could read is no film unless the container says so. pub fn is_film(ext: &str, minutes: Option) -> bool { let ext = ext.to_ascii_lowercase(); matches!(ext.as_str(), "mkv" | "avi") || minutes.is_some_and(|minutes| minutes >= FILM_MINUTES) } /// Whether the phone plays this file as it is: an MP4 or a MOV whose video /// is H.264 or HEVC and whose audio, if any, is AAC. Codecs are named as /// AVFoundation's four-character codes, ffprobe's names or Android's media /// types (`video/avc`, `audio/mp4a-latm`), any way. pub fn plays_whole(ext: &str, video: Option<&str>, audio: Option<&str>) -> bool { if !WHOLE_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()) { return false; } let video_ok = video.is_some_and(|codec| matches!(codec.trim().to_ascii_lowercase().as_str(), "avc1" | "avc3" | "h264" | "hvc1" | "hev1" | "hevc" | "h265" | "video/avc" | "video/hevc")); let audio_ok = audio.is_none_or(|codec| matches!(codec.trim().to_ascii_lowercase().as_str(), "aac" | "mp4a" | "aac " | "audio/mp4a-latm")); video_ok && audio_ok } /// What one file is, to choose between two of the same film. #[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Quality { /// The picture's height in pixels. pub height: Option, /// Kilobits a second, the whole file's. pub bitrate: Option, } /// Whether `a` is the better file of one film than `b`: the taller picture, /// then the higher bitrate; a tie keeps the one already held. pub fn better(a: Quality, b: Quality) -> bool { match (a.height.unwrap_or(0), b.height.unwrap_or(0)) { (x, y) if x != y => x > y, _ => a.bitrate.unwrap_or(0) > b.bitrate.unwrap_or(0), } } /// A film's key for "the same title and year": folded title, then the year. pub fn same_key(title: &str, year: Option<&str>) -> String { let folded: String = title.chars().filter(|c| c.is_alphanumeric() || c.is_whitespace()).collect::().to_lowercase(); let folded = folded.split_whitespace().collect::>().join(" "); format!("{folded}\u{1f}{}", year.unwrap_or("")) } /// What a path says of its film, read from the file's name and the folders /// above it. `None` for a file that is no video, or one in a sample or an /// extras folder. pub fn from_path(path: &str) -> Option { let parts: Vec<&str> = path.split('/').map(str::trim).filter(|part| !part.is_empty()).collect(); let file = *parts.last()?; let ext = extension(file)?; if !is_video(&ext) { return None; } let folders = &parts[..parts.len() - 1]; if folders.iter().any(|folder| SKIPPED_FOLDERS.contains(&spaced(folder).to_lowercase().as_str())) { return None; } let stem = spaced(&file[..file.len() - ext.len() - 1]); if stem.split_whitespace().any(|word| word.eq_ignore_ascii_case("sample")) { return None; } let season_folder = folders.last().and_then(|folder| season_of(folder)); if let Some((before, season, episode, after)) = episode_mark(&stem) { let series = match season_folder { Some(_) if folders.len() >= 2 => Some(title_of(&spaced(folders[folders.len() - 2])).0), _ => None, } .or_else(|| Some(title_of(before).0).filter(|series| !series.is_empty())) .or_else(|| folders.last().filter(|_| season_folder.is_none()).map(|folder| title_of(&spaced(folder)).0))?; return Some(FilmPath::Episode { series, season, episode, title: episode_title(after) }); } // `05 - Title.mkv` inside a season's folder. if let (Some(season), true) = (season_folder, folders.len() >= 2) { let digits: String = stem.chars().take_while(char::is_ascii_digit).collect(); if let Ok(episode) = digits.parse::() { let series = title_of(&spaced(folders[folders.len() - 2])).0; return Some(FilmPath::Episode { series, season, episode, title: episode_title(&stem[digits.len()..]) }); } } let (title, year) = title_of(&stem); (!title.is_empty()).then_some(FilmPath::Film { title, year }) } /// The series' folder of the episode at `path` (`Series/Season 02/S02E05.mkv` /// → `Series`): the one above its season's folder, where `tvshow.nfo` and the /// series' poster lie; none for a film, or an episode in no season's folder. /// A phone hands that folder's sidecars beside the file (`seriesBeside`). pub fn series_folder(path: &str) -> Option { let parts: Vec<&str> = path.split('/').map(str::trim).filter(|part| !part.is_empty()).collect(); let folders = parts.get(..parts.len().checked_sub(1)?)?; if folders.len() < 2 || season_of(folders[folders.len() - 1]).is_none() { return None } matches!(from_path(path), Some(FilmPath::Episode { .. })).then(|| folders[..folders.len() - 1].join("/")) } /// Dots and underscores between words read as spaces ("Night.Ferry.2019", /// "Dust Signals.2011"); a dot a space follows is the title's own ("Mr. /// Robot"). fn spaced(name: &str) -> String { let chars: Vec = name.trim().chars().collect(); let out: String = chars .iter() .enumerate() .map(|(at, c)| match c { '_' => ' ', '.' if chars.get(at + 1) != Some(&' ') => ' ', c => *c, }) .collect(); out.split_whitespace().collect::>().join(" ") } /// A season's folder: `Season 2`, `Season 02`, `Series 2`, `S02`. fn season_of(folder: &str) -> Option { let lower = spaced(folder).to_lowercase(); let rest = lower .strip_prefix("season") .or_else(|| lower.strip_prefix("series")) .or_else(|| lower.strip_prefix('s').filter(|rest| rest.chars().all(|c| c.is_ascii_digit())))?; rest.trim().parse().ok() } /// `S02E05` or `2x05` in a name: what stands before it, the season, the /// episode, what follows. fn episode_mark(stem: &str) -> Option<(&str, u32, u32, &str)> { let pattern = regex::Regex::new(r"(?i)\bs(\d{1,2})\s?e(\d{1,3})\b|\b(\d{1,2})x(\d{2,3})\b").expect("the episode mark"); let found = pattern.captures(stem)?; let whole = found.get(0)?; let (season, episode) = match (found.get(1), found.get(2)) { (Some(season), Some(episode)) => (season.as_str(), episode.as_str()), _ => (found.get(3)?.as_str(), found.get(4)?.as_str()), }; Some((&stem[..whole.start()], season.parse().ok()?, episode.parse().ok()?, &stem[whole.end()..])) } /// An episode's own title after its mark, release words cut. fn episode_title(after: &str) -> Option { let after = after.trim().trim_start_matches(['-', '–', '—', ':', '.']).trim(); Some(title_of(after).0).filter(|title| !title.is_empty()) } /// A name's title and year: `Title (2019)`, `Title [2019]`, or `Title 2019 /// 1080p …`, where the title ends at the year or at the first release word. fn title_of(name: &str) -> (String, Option) { let words: Vec<&str> = name.split_whitespace().collect(); let mut title = Vec::new(); let mut year = None; for (at, word) in words.iter().enumerate() { let bare = word.trim_matches(|c: char| matches!(c, '(' | ')' | '[' | ']')); let is_year = bare.len() == 4 && (bare.starts_with("19") || bare.starts_with("20")) && bare.chars().all(|c| c.is_ascii_digit()); if is_year && at > 0 { year = Some(bare.to_string()); break; } if RELEASE_WORDS.contains(&bare.to_lowercase().as_str()) || (word.starts_with('[') && at > 0) { break; } title.push(*word); } let title = title.join(" ").trim_matches(|c: char| c == '-' || c.is_whitespace()).to_string(); (title, year) } #[cfg(test)] mod tests;