Files
arr/crates/arr-subs/src/model.rs
T

307 lines
10 KiB
Rust

//! The domain types a subtitle provider deals in.
//!
//! Everything here is a fact about a candidate or about the file it is wanted
//! for. None of it decides anything: which candidate wins is ranking, and
//! ranking is pure and lives in `arr-core` (#185).
use std::{fmt, path::PathBuf};
use arr_core::{Language, Source};
/// The name a provider answers to in candidate rows, settings and the UI.
///
/// A string rather than an enum: providers arrive one issue at a time and the
/// set is a deployment fact, not a domain rule. Ranking never looks at it.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ProviderId(String);
impl ProviderId {
/// Name a provider.
#[must_use]
pub fn new(name: impl Into<String>) -> Self {
Self(name.into())
}
/// The name as written.
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for ProviderId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
/// A provider's own handle for one candidate, opaque to everything else.
///
/// Each provider decides what this spells — a numeric file id, a URL, a
/// composite key. It is only ever handed back to the provider that issued it.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct CandidateId(String);
impl CandidateId {
/// Wrap a provider's handle.
#[must_use]
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
/// The handle as written.
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for CandidateId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
/// Which title a media file belongs to, in the terms providers search by.
///
/// TMDB ids rather than titles: a provider that matches on a title string
/// matches the wrong film often enough to matter, and every title arr knows
/// carries a TMDB id already (DESIGN.md §4).
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum MediaRef {
/// A film.
Movie {
/// TMDB's id for the film.
tmdb_id: u64,
},
/// One episode of a series.
Episode {
/// TMDB's id for the series, not for the episode.
tmdb_id: u64,
/// Season number as TMDB numbers it.
season: u16,
/// Episode number within the season.
episode: u16,
},
}
/// The file subtitles are wanted for.
///
/// The path and size are here because `moviehash` — the signal that wins
/// ranking outright (DESIGN.md §15) — is computed from the bytes of the file
/// and is quoted alongside its length. Computing it is the searching
/// provider's job, not this type's: only OpenSubtitles.com accepts one.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MediaFile {
/// Where the video sits on disk.
pub path: PathBuf,
/// Its length in bytes.
pub size: u64,
/// The release name it was imported under, when one is known. Providers
/// that index by release name search on it, and ranking scores an exact
/// match against it.
pub release_name: Option<String>,
/// The title the file belongs to.
pub media: MediaRef,
}
/// One search put to one provider.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SearchRequest {
/// The file subtitles are wanted for.
pub file: MediaFile,
/// The languages worth returning. A provider may answer with fewer, and
/// answering with more is not an error — ranking discards the rest.
pub languages: Vec<Language>,
}
/// One subtitle a provider is offering, with the facts ranking needs.
///
/// Nothing here is normalised or scored. A provider reports what its API says
/// and leaves every judgement to `arr-core` (#185), so that the rule which
/// rejected a candidate can be named against the fact that triggered it.
#[derive(Clone, Debug, PartialEq)]
pub struct Candidate {
/// The provider offering it.
pub provider: ProviderId,
/// That provider's handle for it, for [`Provider::download`].
///
/// [`Provider::download`]: crate::Provider::download
pub id: CandidateId,
/// The language it claims to be in, pt-PT and pt-BR kept apart.
pub language: Language,
/// Whether the provider matched it by `moviehash` — the exact file, not
/// merely the same title.
pub hash_match: bool,
/// The release the subtitle was timed against, when the provider says.
pub release_name: Option<String>,
/// The release group of that release.
pub group: Option<String>,
/// The source of that release.
pub source: Option<Source>,
/// Uploader rating, on whatever scale the provider uses. A tiebreaker
/// only, so the scale never has to be reconciled between providers.
pub rating: Option<f32>,
/// How many times it has been downloaded. The second tiebreaker.
pub download_count: Option<u64>,
/// A forced track: foreign lines and on-screen signs only. It never
/// satisfies a want, and arr never goes looking for one (DESIGN.md §15).
pub forced: bool,
/// Subtitles for the deaf and hard of hearing. Complete, so it satisfies,
/// but ranked below a plain subtitle for the same language.
pub sdh: bool,
}
impl Candidate {
/// The same candidate in the shape `arr_core::subs::rank` eats.
///
/// The two types are deliberately separate — this crate reports what a
/// provider said, `arr-core` decides what it means — so the mapping
/// between them is decided here, once, rather than reinvented by every
/// caller:
///
/// * `hash_match` is a boolean here because that is what a provider
/// answers, while ranking compares hashes. A hash match is therefore
/// expressed by handing ranking `target_moviehash`; no match is `None`,
/// which never compares equal.
/// * `rating` and `download_count` are optional here because a provider
/// may not report them. Both are tiebreakers, so a missing one sorts
/// last rather than blocking the candidate: `0.0` and `0`.
///
/// `language` is dropped: ranking runs over one wanted language at a
/// time, so the caller has already filtered by it.
#[must_use]
pub fn to_core<'a>(
&'a self,
target_moviehash: Option<&'a str>,
) -> arr_core::subs::SubtitleCandidate<'a> {
arr_core::subs::SubtitleCandidate {
forced: self.forced,
hearing_impaired: self.sdh,
moviehash: if self.hash_match {
target_moviehash
} else {
None
},
release_name: self.release_name.as_deref(),
release_group: self.group.as_deref(),
source: self.source,
uploader_rating: f64::from(self.rating.unwrap_or(0.0)),
download_count: self.download_count.unwrap_or(0),
}
}
}
/// The wire format of a downloaded subtitle.
///
/// Sidecars on disk are SRT (DESIGN.md §15), but providers serve other things
/// and converting is not this crate's decision to make silently.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum SubtitleFormat {
/// `SubRip`, the format sidecars are written in.
Srt,
/// Advanced `SubStation` Alpha, and SSA with it.
Ass,
/// `WebVTT`.
Vtt,
/// Something else, spelled as the provider spelled it.
Other(String),
}
impl fmt::Display for SubtitleFormat {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Srt => formatter.write_str("srt"),
Self::Ass => formatter.write_str("ass"),
Self::Vtt => formatter.write_str("vtt"),
Self::Other(format) => formatter.write_str(format),
}
}
}
/// A downloaded subtitle, in memory.
///
/// Bytes rather than a path: what happens next is not the provider's call.
/// Syncing runs `alass` over it (#194) and only then does it get a name and a
/// place in the title folder (#195).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Fetched {
/// The candidate that was downloaded.
pub id: CandidateId,
/// The language it is in.
pub language: Language,
/// The format the provider served.
pub format: SubtitleFormat,
/// The subtitle itself, exactly as it arrived. Not decoded to UTF-8 here:
/// providers serve Latin-1 and Windows-1252 files, and guessing wrong is
/// worse than handing the bytes on. Call [`Fetched::decode`] to get text.
pub content: Vec<u8>,
}
#[cfg(test)]
mod tests {
use arr_core::Language;
use super::{Candidate, CandidateId, ProviderId, SubtitleFormat};
fn candidate() -> Candidate {
Candidate {
provider: ProviderId::new("opensubtitles"),
id: CandidateId::new("1"),
language: Language::PortuguesePortugal,
hash_match: false,
release_name: Some("Movie.2024.1080p.WEB-DL-GROUP".into()),
group: Some("GROUP".into()),
source: None,
rating: None,
download_count: None,
forced: false,
sdh: true,
}
}
#[test]
fn a_hash_match_is_handed_to_ranking_as_the_target_hash() {
let matched = Candidate {
hash_match: true,
..candidate()
};
assert_eq!(matched.to_core(Some("abc123")).moviehash, Some("abc123"));
// No match must never compare equal, whatever the target carries.
let unmatched = candidate();
assert_eq!(unmatched.to_core(Some("abc123")).moviehash, None);
}
#[test]
fn missing_tiebreakers_sort_last_rather_than_blocking_a_candidate() {
let candidate = candidate();
let core = candidate.to_core(None);
assert!((core.uploader_rating - 0.0).abs() < f64::EPSILON);
assert_eq!(core.download_count, 0);
}
#[test]
fn the_sdh_and_group_facts_survive_the_rename_across_the_seam() {
let candidate = candidate();
let core = candidate.to_core(None);
assert!(core.hearing_impaired);
assert!(!core.forced);
assert_eq!(core.release_group, Some("GROUP"));
}
#[test]
fn ids_render_as_the_string_they_wrap() {
assert_eq!(
ProviderId::new("opensubtitles").to_string(),
"opensubtitles"
);
assert_eq!(CandidateId::new("123456").as_str(), "123456");
}
#[test]
fn an_unknown_format_keeps_its_own_spelling() {
assert_eq!(SubtitleFormat::Srt.to_string(), "srt");
assert_eq!(SubtitleFormat::Other("sub".to_owned()).to_string(), "sub");
}
}