use std::time::{Duration, SystemTime};
use serde::{Deserialize, Serialize};
use crate::codec::AudioCodec;
use crate::date::CalendarDate;
use crate::id::{ArtworkId, LibraryId, MediaId, PersonId};
use crate::search::PersonRole;
use crate::serde_time;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[serde(rename_all = "snake_case")]
pub enum LibraryKind {
Movies,
Shows,
Music,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Library {
pub id: LibraryId,
pub title: String,
pub kind: LibraryKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub server: Option<LibraryServer>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct LibraryServer {
pub server_id: String,
pub name: String,
pub online: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[serde(rename_all = "snake_case")]
pub enum ArtworkKind {
Poster,
Background,
Thumb,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Artwork {
pub id: ArtworkId,
pub kind: ArtworkKind,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct PlaybackState {
#[serde(with = "serde_time::millis::option_required")]
pub position: Option<Duration>,
pub watched: bool,
#[serde(default, with = "serde_time::unix_seconds::option")]
pub last_viewed_at: Option<SystemTime>,
#[serde(default)]
pub play_count: u32,
#[serde(default, with = "serde_time::unix_seconds::option")]
pub last_played_at: Option<SystemTime>,
}
impl PlaybackState {
pub fn resume_from(&self) -> Option<Duration> {
if self.watched {
return None;
}
self.position.filter(|p| !p.is_zero())
}
pub fn progress(&self, duration: Option<Duration>) -> Progress {
let position = self.position.unwrap_or_default();
let duration = duration.filter(|d| !d.is_zero());
Progress {
position,
remaining: duration.map(|d| d.saturating_sub(position)),
fraction: duration.map(|d| (position.as_secs_f64() / d.as_secs_f64()).clamp(0.0, 1.0)),
watched: self.watched,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Progress {
pub position: Duration,
pub remaining: Option<Duration>,
pub fraction: Option<f64>,
pub watched: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Movie {
pub id: MediaId,
pub title: String,
pub year: Option<u16>,
pub release_date: Option<CalendarDate>,
pub summary: Option<String>,
pub content_rating: Option<String>,
#[serde(with = "serde_time::millis::option_required")]
pub duration: Option<Duration>,
#[serde(default)]
pub cast: Vec<CastMember>,
pub artwork: Vec<Artwork>,
pub playback: PlaybackState,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Show {
pub id: MediaId,
pub title: String,
pub year: Option<u16>,
pub summary: Option<String>,
pub content_rating: Option<String>,
pub season_count: Option<u32>,
pub genres: Vec<String>,
pub last_aired: Option<CalendarDate>,
#[serde(default)]
pub cast: Vec<CastMember>,
pub artwork: Vec<Artwork>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Season {
pub id: MediaId,
pub show_id: MediaId,
#[serde(deserialize_with = "crate::required::option")]
pub show_title: Option<String>,
pub season: u32,
pub title: String,
pub artwork: Vec<Artwork>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Episode {
pub id: MediaId,
pub show_id: MediaId,
#[serde(deserialize_with = "crate::required::option")]
pub show_title: Option<String>,
pub season_id: MediaId,
pub season: u32,
pub episode: u32,
pub title: String,
pub summary: Option<String>,
pub content_rating: Option<String>,
pub year: Option<u16>,
pub air_date: Option<CalendarDate>,
#[serde(with = "serde_time::millis::option_required")]
pub duration: Option<Duration>,
#[serde(default)]
pub cast: Vec<CastMember>,
pub artwork: Vec<Artwork>,
pub playback: PlaybackState,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct CastMember {
pub id: PersonId,
pub name: String,
pub role: PersonRole,
#[serde(deserialize_with = "crate::required::option")]
pub character: Option<String>,
#[serde(deserialize_with = "crate::required::option")]
pub photo: Option<ArtworkId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Artist {
pub id: MediaId,
pub name: String,
pub summary: Option<String>,
pub artwork: Vec<Artwork>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Album {
pub id: MediaId,
pub artist_id: MediaId,
#[serde(deserialize_with = "crate::required::option")]
pub artist_name: Option<String>,
pub title: String,
pub year: Option<u16>,
pub track_count: Option<u32>,
pub artwork: Vec<Artwork>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Track {
pub id: MediaId,
pub album_id: MediaId,
pub artist_id: MediaId,
pub artist_name: Option<String>,
pub album_title: Option<String>,
pub title: String,
pub track: Option<u32>,
pub disc: Option<u32>,
pub album_track_count: Option<u32>,
pub codec: Option<AudioCodec>,
pub bit_depth: Option<u32>,
pub sample_rate: Option<u32>,
#[serde(with = "serde_time::millis::option_required")]
pub duration: Option<Duration>,
pub artwork: Vec<Artwork>,
pub playback: PlaybackState,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[serde(rename_all = "snake_case")]
pub enum MarkerKind {
Intro,
Credits,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Marker {
pub kind: MarkerKind,
#[serde(rename = "start_ms", with = "serde_time::millis")]
pub start: Duration,
#[serde(rename = "end_ms", with = "serde_time::millis")]
pub end: Duration,
pub to_end: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct Markers(Vec<Marker>);
impl Markers {
pub fn into_vec(self) -> Vec<Marker> {
self.0
}
}
impl From<Vec<Marker>> for Markers {
fn from(mut markers: Vec<Marker>) -> Self {
markers.retain(|m| m.kind != MarkerKind::Unknown);
Self(markers)
}
}
impl<'de> Deserialize<'de> for Markers {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Vec::<Marker>::deserialize(d).map(Self::from)
}
}
impl std::ops::Deref for Markers {
type Target = [Marker];
fn deref(&self) -> &[Marker] {
&self.0
}
}
impl IntoIterator for Markers {
type Item = Marker;
type IntoIter = std::vec::IntoIter<Marker>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<'a> IntoIterator for &'a Markers {
type Item = &'a Marker;
type IntoIter = std::slice::Iter<'a, Marker>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Item {
Movie(Movie),
Show(Show),
Season(Season),
Episode(Episode),
Artist(Artist),
Album(Album),
Track(Track),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
pub enum YearsAired {
One(u16),
Running(u16),
Between(u16, u16),
}
impl std::fmt::Display for YearsAired {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
YearsAired::One(year) => write!(f, "{year}"),
YearsAired::Running(first) => write!(f, "{first}\u{2013}"),
YearsAired::Between(first, last) => write!(f, "{first}\u{2013}{last}"),
}
}
}
impl Show {
pub fn year_range(&self, today: CalendarDate) -> Option<YearsAired> {
let Some(last) = self.last_aired else {
return self.year.map(YearsAired::One);
};
let Some(first) = self.year else {
return Some(YearsAired::One(last.year()));
};
if last.year() <= first {
return Some(YearsAired::One(first));
}
let year_ago = (today.year() - 1, today.month(), today.day());
if (last.year(), last.month(), last.day()) >= year_ago {
Some(YearsAired::Running(first))
} else {
Some(YearsAired::Between(first, last.year()))
}
}
pub fn years_label(&self, today: CalendarDate) -> Option<String> {
self.year_range(today).map(|years| years.to_string())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
pub enum Caption {
Year(u16),
Years(YearsAired),
Show(String),
Episode {
show: Option<String>,
season: u32,
episode: u32,
},
Album {
artist: Option<String>,
year: Option<u16>,
},
Length(Duration),
}
impl Item {
pub fn duration(&self) -> Option<Duration> {
match self {
Item::Movie(m) => m.duration,
Item::Episode(e) => e.duration,
Item::Track(t) => t.duration,
_ => None,
}
}
}
impl Item {
pub fn caption_parts(&self, today: CalendarDate) -> Option<Caption> {
match self {
Item::Movie(m) => m.year.map(Caption::Year),
Item::Show(s) => s.year_range(today).map(Caption::Years),
Item::Season(s) => s.show_title.clone().map(Caption::Show),
Item::Episode(e) => Some(Caption::Episode {
show: e.show_title.clone(),
season: e.season,
episode: e.episode,
}),
Item::Album(a) => {
(a.artist_name.is_some() || a.year.is_some()).then(|| Caption::Album {
artist: a.artist_name.clone(),
year: a.year,
})
}
Item::Track(t) => t.duration.map(Caption::Length),
Item::Artist(_) => None,
}
}
pub fn id(&self) -> &MediaId {
match self {
Item::Movie(m) => &m.id,
Item::Show(s) => &s.id,
Item::Season(s) => &s.id,
Item::Episode(e) => &e.id,
Item::Artist(a) => &a.id,
Item::Album(a) => &a.id,
Item::Track(t) => &t.id,
}
}
pub fn title(&self) -> &str {
match self {
Item::Movie(m) => &m.title,
Item::Show(s) => &s.title,
Item::Season(s) => &s.title,
Item::Episode(e) => &e.title,
Item::Artist(a) => &a.name,
Item::Album(a) => &a.title,
Item::Track(t) => &t.title,
}
}
pub fn artwork(&self) -> &[Artwork] {
match self {
Item::Movie(m) => &m.artwork,
Item::Show(s) => &s.artwork,
Item::Season(s) => &s.artwork,
Item::Episode(e) => &e.artwork,
Item::Artist(a) => &a.artwork,
Item::Album(a) => &a.artwork,
Item::Track(t) => &t.artwork,
}
}
pub fn artwork_of(&self, kind: ArtworkKind) -> Option<&Artwork> {
self.artwork().iter().find(|a| a.kind == kind)
}
pub fn playback(&self) -> Option<&PlaybackState> {
match self {
Item::Movie(m) => Some(&m.playback),
Item::Episode(e) => Some(&e.playback),
Item::Track(t) => Some(&t.playback),
_ => None,
}
}
pub fn is_watched(&self) -> bool {
self.playback().is_some_and(|p| p.watched)
}
pub fn resume_position(&self) -> Option<Duration> {
self.playback().and_then(|p| p.position)
}
pub fn resume_from(&self) -> Option<Duration> {
self.playback().and_then(PlaybackState::resume_from)
}
pub fn progress(&self) -> Option<Progress> {
Some(self.playback()?.progress(self.duration()))
}
}
#[cfg(test)]
mod tests {
use std::fmt::Debug;
use std::time::UNIX_EPOCH;
use serde::de::DeserializeOwned;
use super::*;
use crate::id::{MediaKind, Namespace};
fn round_trip<T: Serialize + DeserializeOwned + PartialEq + Debug>(value: T) {
let json = serde_json::to_string(&value).unwrap();
assert_eq!(serde_json::from_str::<T>(&json).unwrap(), value, "{json}");
}
fn media(kind: MediaKind, key: &str) -> MediaId {
MediaId::new(Namespace::Plex, kind, key).unwrap()
}
fn poster() -> Vec<Artwork> {
vec![Artwork {
id: ArtworkId::new(Namespace::Plex, "/library/metadata/1/thumb/9").unwrap(),
kind: ArtworkKind::Poster,
}]
}
fn halfway() -> PlaybackState {
PlaybackState {
position: Some(Duration::from_millis(2_220_500)),
watched: false,
last_viewed_at: None,
play_count: 0,
last_played_at: None,
}
}
fn ripley() -> CastMember {
CastMember {
id: PersonId::new(Namespace::Plex, "actor-13").unwrap(),
name: "Sigourney Weaver".into(),
role: PersonRole::Actor,
character: Some("Ellen Ripley".into()),
photo: Some(ArtworkId::new(Namespace::Plex, "/people/1/a/b.jpg").unwrap()),
}
}
fn scott() -> CastMember {
CastMember {
id: PersonId::new(Namespace::Plex, "director-7").unwrap(),
name: "Ridley Scott".into(),
role: PersonRole::Director,
character: None,
photo: None,
}
}
#[test]
fn a_cast_member_is_their_person_id_role_and_photo_on_the_wire() {
assert_eq!(
serde_json::to_value(ripley()).unwrap(),
serde_json::json!({
"id": "plex:actor-13",
"name": "Sigourney Weaver",
"role": "actor",
"character": "Ellen Ripley",
"photo": "plex:/people/1/a/b.jpg",
})
);
round_trip(ripley());
round_trip(scott());
}
#[test]
fn a_cast_member_s_character_and_photo_are_required() {
crate::test_support::assert_each_required(&scott(), &["character", "photo"]);
}
#[test]
fn items_from_a_server_without_cast_or_dates_still_decode() {
let movie = Movie {
id: media(MediaKind::Movie, "10"),
title: "Alien".into(),
year: Some(1979),
release_date: CalendarDate::new(1979, 5, 25),
summary: None,
content_rating: None,
duration: None,
cast: vec![ripley()],
artwork: Vec::new(),
playback: PlaybackState::default(),
};
let mut json = serde_json::to_value(&movie).unwrap();
assert_eq!(json["release_date"], "1979-05-25");
let object = json.as_object_mut().unwrap();
object.remove("release_date");
object.remove("cast");
let older: Movie = serde_json::from_value(json).unwrap();
assert_eq!((older.release_date, older.cast), (None, Vec::new()));
let show = Show {
id: media(MediaKind::Show, "20"),
title: "The Expanse".into(),
year: Some(2015),
summary: None,
content_rating: None,
season_count: None,
genres: Vec::new(),
last_aired: CalendarDate::new(2022, 4, 8),
cast: vec![ripley()],
artwork: Vec::new(),
};
let mut json = serde_json::to_value(&show).unwrap();
assert_eq!(json["last_aired"], "2022-04-08");
let object = json.as_object_mut().unwrap();
object.remove("last_aired");
object.remove("cast");
let older: Show = serde_json::from_value(json).unwrap();
assert_eq!((older.last_aired, older.cast), (None, Vec::new()));
let episode = Episode {
id: media(MediaKind::Episode, "22"),
show_id: media(MediaKind::Show, "20"),
show_title: None,
season_id: media(MediaKind::Season, "21"),
season: 1,
episode: 1,
title: "Dulcinea".into(),
summary: None,
content_rating: None,
year: None,
air_date: None,
duration: None,
cast: vec![scott()],
artwork: Vec::new(),
playback: PlaybackState::default(),
};
let mut json = serde_json::to_value(&episode).unwrap();
json.as_object_mut().unwrap().remove("cast");
let older: Episode = serde_json::from_value(json).unwrap();
assert_eq!(older.cast, Vec::new());
}
#[test]
fn a_track_s_format_is_plain_numbers_on_the_wire() {
let track = Track {
id: media(MediaKind::Track, "224630"),
album_id: media(MediaKind::Album, "224629"),
artist_id: media(MediaKind::Artist, "224303"),
artist_name: None,
album_title: None,
title: "Catch".into(),
track: Some(1),
disc: Some(1),
album_track_count: Some(3),
codec: Some(AudioCodec::Flac),
bit_depth: Some(24),
sample_rate: Some(96_000),
duration: None,
artwork: Vec::new(),
playback: PlaybackState::default(),
};
let json = serde_json::to_value(&track).unwrap();
assert_eq!(
(
&json["codec"],
&json["bit_depth"],
&json["sample_rate"],
&json["album_track_count"]
),
(
&serde_json::json!("flac"),
&serde_json::json!(24),
&serde_json::json!(96_000),
&serde_json::json!(3)
)
);
}
#[test]
fn library_kinds_are_snake_case_on_the_wire() {
assert_eq!(
serde_json::to_string(&LibraryKind::Movies).unwrap(),
r#""movies""#
);
}
#[test]
fn an_item_carries_its_kind_on_the_wire() {
let item = Item::Show(Show {
id: media(MediaKind::Show, "20"),
title: "The Expanse".into(),
year: None,
summary: None,
content_rating: None,
season_count: None,
genres: Vec::new(),
last_aired: None,
cast: Vec::new(),
artwork: Vec::new(),
});
let json = serde_json::to_value(&item).unwrap();
assert_eq!(json["kind"], "show");
assert_eq!(json["id"], "plex:show:20");
round_trip(item);
}
#[test]
fn a_parent_s_name_left_out_is_refused() {
let season = Season {
id: media(MediaKind::Season, "21"),
show_id: media(MediaKind::Show, "20"),
show_title: None,
season: 1,
title: "Season 1".into(),
artwork: Vec::new(),
};
crate::test_support::assert_each_required(&season, &["show_title"]);
let episode = Episode {
id: media(MediaKind::Episode, "22"),
show_id: media(MediaKind::Show, "20"),
show_title: None,
season_id: media(MediaKind::Season, "21"),
season: 1,
episode: 1,
title: "Dulcinea".into(),
summary: None,
content_rating: None,
year: None,
air_date: None,
duration: None,
cast: Vec::new(),
artwork: Vec::new(),
playback: PlaybackState::default(),
};
crate::test_support::assert_each_required(&episode, &["show_title"]);
let album = Album {
id: media(MediaKind::Album, "30"),
artist_id: media(MediaKind::Artist, "31"),
artist_name: None,
title: "Moon Safari".into(),
year: None,
track_count: None,
artwork: Vec::new(),
};
crate::test_support::assert_each_required(&album, &["artist_name"]);
round_trip(album);
}
#[test]
fn an_episode_from_a_server_without_air_dates_still_decodes() {
let episode = Episode {
id: media(MediaKind::Episode, "22"),
show_id: media(MediaKind::Show, "20"),
show_title: None,
season_id: media(MediaKind::Season, "21"),
season: 1,
episode: 1,
title: "Dulcinea".into(),
summary: None,
content_rating: None,
year: Some(2015),
air_date: CalendarDate::new(2015, 11, 23),
duration: None,
cast: Vec::new(),
artwork: Vec::new(),
playback: PlaybackState::default(),
};
let mut json = serde_json::to_value(&episode).unwrap();
assert_eq!(json["air_date"], "2015-11-23");
let object = json.as_object_mut().unwrap();
object.remove("year");
object.remove("air_date");
let older: Episode = serde_json::from_value(json).unwrap();
assert_eq!((older.year, older.air_date), (None, None));
}
fn years(year: Option<u16>, last_aired: Option<(u16, u8, u8)>) -> Option<String> {
let show = Show {
id: media(MediaKind::Show, "20"),
title: "Andor".into(),
year,
summary: None,
content_rating: None,
season_count: None,
genres: Vec::new(),
last_aired: last_aired.and_then(|(y, m, d)| CalendarDate::new(y, m, d)),
cast: Vec::new(),
artwork: Vec::new(),
};
show.years_label(CalendarDate::new(2026, 10, 14).unwrap())
}
#[test]
fn a_show_s_years_come_in_parts() {
let show = |last: (u16, u8, u8)| Show {
id: media(MediaKind::Show, "20"),
title: "Andor".into(),
year: Some(2022),
summary: None,
content_rating: None,
season_count: None,
genres: Vec::new(),
last_aired: CalendarDate::new(last.0, last.1, last.2),
cast: Vec::new(),
artwork: Vec::new(),
};
let today = CalendarDate::new(2026, 10, 14).unwrap();
assert_eq!(
show((2025, 10, 14)).year_range(today),
Some(YearsAired::Running(2022))
);
assert_eq!(
show((2025, 10, 13)).year_range(today),
Some(YearsAired::Between(2022, 2025))
);
assert_eq!(
Item::Show(show((2022, 5, 1))).caption_parts(today),
Some(Caption::Years(YearsAired::One(2022)))
);
}
#[test]
fn a_show_with_no_air_date_shows_its_first_year() {
assert_eq!(years(Some(2022), None), Some("2022".into()));
assert_eq!(years(None, None), None);
}
#[test]
fn a_show_last_aired_in_its_first_year_shows_that_year() {
assert_eq!(years(Some(2022), Some((2022, 12, 1))), Some("2022".into()));
}
#[test]
fn a_show_aired_in_the_last_twelve_months_is_an_open_range() {
assert_eq!(
years(Some(2022), Some((2025, 10, 14))),
Some("2022\u{2013}".into())
);
}
#[test]
fn a_show_last_aired_over_a_year_ago_shows_both_years() {
assert_eq!(
years(Some(2022), Some((2025, 10, 13))),
Some("2022\u{2013}2025".into())
);
}
#[test]
fn a_show_with_no_first_year_shows_when_it_last_aired() {
assert_eq!(years(None, Some((2019, 3, 2))), Some("2019".into()));
}
#[test]
fn every_model_type_round_trips() {
round_trip(Library {
id: LibraryId::new(Namespace::Plex, "1").unwrap(),
title: "Movies".into(),
kind: LibraryKind::Movies,
server: None,
});
round_trip(Movie {
id: media(MediaKind::Movie, "10"),
title: "Alien".into(),
year: Some(1979),
release_date: CalendarDate::new(1979, 5, 25),
summary: Some("In space no one can hear you scream.".into()),
content_rating: Some("R".into()),
duration: Some(Duration::from_secs(7020)),
cast: vec![ripley(), scott()],
artwork: poster(),
playback: halfway(),
});
round_trip(Show {
id: media(MediaKind::Show, "20"),
title: "The Expanse".into(),
year: Some(2015),
summary: None,
content_rating: Some("TV-14".into()),
season_count: Some(6),
genres: vec!["Science Fiction".into(), "Drama".into()],
last_aired: CalendarDate::new(2022, 4, 8),
cast: vec![ripley()],
artwork: poster(),
});
round_trip(Season {
id: media(MediaKind::Season, "21"),
show_id: media(MediaKind::Show, "20"),
show_title: Some("The Expanse".into()),
season: 1,
title: "Season 1".into(),
artwork: Vec::new(),
});
round_trip(Episode {
id: media(MediaKind::Episode, "22"),
show_id: media(MediaKind::Show, "20"),
show_title: Some("The Expanse".into()),
season_id: media(MediaKind::Season, "21"),
season: 1,
episode: 1,
title: "Dulcinea".into(),
summary: None,
content_rating: Some("TV-14".into()),
year: Some(2015),
air_date: CalendarDate::new(2015, 11, 23),
duration: Some(Duration::from_secs(2640)),
cast: vec![scott()],
artwork: poster(),
playback: PlaybackState::default(),
});
round_trip(Artist {
id: media(MediaKind::Artist, "30"),
name: "Boards of Canada".into(),
summary: None,
artwork: poster(),
});
round_trip(Album {
id: media(MediaKind::Album, "31"),
artist_id: media(MediaKind::Artist, "30"),
artist_name: Some("Boards of Canada".into()),
title: "Music Has the Right to Children".into(),
year: Some(1998),
track_count: Some(18),
artwork: poster(),
});
round_trip(Track {
id: media(MediaKind::Track, "32"),
album_id: media(MediaKind::Album, "31"),
artist_id: media(MediaKind::Artist, "30"),
artist_name: Some("Boards of Canada".into()),
album_title: Some("Music Has the Right to Children".into()),
title: "Roygbiv".into(),
track: Some(10),
disc: Some(1),
album_track_count: Some(18),
codec: Some(AudioCodec::Flac),
bit_depth: Some(16),
sample_rate: Some(44_100),
duration: Some(Duration::from_secs(151)),
artwork: poster(),
playback: PlaybackState {
position: None,
watched: true,
last_viewed_at: None,
play_count: 0,
last_played_at: None,
},
});
}
fn alien(playback: PlaybackState, duration: Option<Duration>) -> Item {
Item::Movie(Movie {
id: media(MediaKind::Movie, "10"),
title: "Alien".into(),
year: Some(1979),
release_date: None,
summary: None,
content_rating: None,
duration,
cast: Vec::new(),
artwork: Vec::new(),
playback,
})
}
#[test]
fn markers_and_watch_times_keep_their_wire_form() {
let marker = Marker {
kind: MarkerKind::Intro,
start: Duration::from_millis(258_865),
end: Duration::from_millis(319_865),
to_end: false,
};
let state = PlaybackState {
last_viewed_at: Some(UNIX_EPOCH + Duration::from_secs(1_761_700_000)),
play_count: 2,
last_played_at: Some(UNIX_EPOCH + Duration::from_secs(1_761_600_000)),
..PlaybackState::default()
};
assert_eq!(
(
serde_json::to_value(marker).unwrap(),
serde_json::to_value(&state).unwrap(),
serde_json::to_value(halfway()).unwrap()["position"].clone(),
),
(
serde_json::json!({
"kind": "intro", "start_ms": 258_865, "end_ms": 319_865, "to_end": false
}),
serde_json::json!({
"position": null, "watched": false, "last_viewed_at": 1_761_700_000,
"play_count": 2, "last_played_at": 1_761_600_000
}),
serde_json::json!(2_220_500),
)
);
round_trip(marker);
round_trip(state);
}
#[test]
fn a_marker_list_leaves_out_kinds_this_build_does_not_know() {
let listed: Markers = serde_json::from_value(serde_json::json!([
{ "kind": "recap", "start_ms": 0, "end_ms": 60_000, "to_end": false },
{ "kind": "intro", "start_ms": 60_000, "end_ms": 90_000, "to_end": false },
]))
.unwrap();
let intro = Marker {
kind: MarkerKind::Intro,
start: Duration::from_millis(60_000),
end: Duration::from_millis(90_000),
to_end: false,
};
assert_eq!(*listed, [intro]);
assert_eq!(
serde_json::to_value(&listed).unwrap()[0]["start_ms"],
60_000
);
}
#[test]
fn an_item_s_artwork_of_a_kind_is_its_first_one() {
let art = |kind, path: &str| Artwork {
id: ArtworkId::new(Namespace::Plex, path).unwrap(),
kind,
};
let Item::Movie(mut movie) = alien(PlaybackState::default(), None) else {
unreachable!()
};
movie.artwork = vec![
art(ArtworkKind::Background, "/bg"),
art(ArtworkKind::Poster, "/p1"),
art(ArtworkKind::Poster, "/p2"),
];
let item = Item::Movie(movie);
assert_eq!(
[
ArtworkKind::Poster,
ArtworkKind::Background,
ArtworkKind::Thumb
]
.map(|kind| item.artwork_of(kind).cloned()),
[
Some(art(ArtworkKind::Poster, "/p1")),
Some(art(ArtworkKind::Background, "/bg")),
None
]
);
}
fn at(secs: u64, watched: bool) -> PlaybackState {
PlaybackState {
position: Some(Duration::from_secs(secs)),
watched,
..PlaybackState::default()
}
}
#[test]
fn a_film_stopped_part_way_resumes_where_it_stopped() {
assert_eq!(at(600, false).resume_from(), Some(Duration::from_secs(600)));
}
#[test]
fn a_watched_film_plays_from_the_start() {
assert_eq!(at(600, true).resume_from(), None);
}
#[test]
fn a_film_never_begun_plays_from_the_start() {
assert_eq!(PlaybackState::default().resume_from(), None);
assert_eq!(at(0, false).resume_from(), None);
}
#[test]
fn progress_is_the_fraction_watched_and_the_time_left() {
let progress = at(1_500, false).progress(Some(Duration::from_secs(6_000)));
assert_eq!(
progress,
Progress {
position: Duration::from_secs(1_500),
remaining: Some(Duration::from_secs(4_500)),
fraction: Some(0.25),
watched: false,
}
);
}
#[test]
fn progress_past_the_length_is_whole_with_nothing_left() {
let progress = at(7_000, true).progress(Some(Duration::from_secs(6_000)));
assert_eq!(
(progress.fraction, progress.remaining, progress.watched),
(Some(1.0), Some(Duration::ZERO), true)
);
}
#[test]
fn progress_with_no_length_has_no_fraction() {
for length in [None, Some(Duration::ZERO)] {
let progress = at(60, false).progress(length);
assert_eq!((progress.fraction, progress.remaining), (None, None));
}
}
#[test]
fn an_item_answers_from_its_own_playback() {
let item = alien(at(600, false), Some(Duration::from_secs(1_200)));
assert_eq!(item.title(), "Alien");
assert!(!item.is_watched());
assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
assert_eq!(item.resume_from(), Some(Duration::from_secs(600)));
assert_eq!(item.progress().and_then(|p| p.fraction), Some(0.5));
}
#[test]
fn a_watched_item_keeps_its_position_but_resumes_from_the_start() {
let item = alien(at(600, true), None);
assert!(item.is_watched());
assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
assert_eq!(item.resume_from(), None);
}
#[test]
fn an_artist_has_a_title_but_no_progress() {
let show = Item::Artist(Artist {
id: media(MediaKind::Artist, "30"),
name: "Daft Punk".into(),
summary: None,
artwork: Vec::new(),
});
assert_eq!(show.title(), "Daft Punk");
assert_eq!(show.progress(), None);
assert!(!show.is_watched());
assert_eq!(show.resume_from(), None);
}
}