use std::time::Duration;
use serde::{Deserialize, Serialize};
use crate::codec::AudioCodec;
use crate::date::CalendarDate;
use crate::duration_ms;
use crate::id::{ArtworkId, LibraryId, MediaId, PersonId};
use crate::search::PersonRole;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LibraryKind {
Movies,
Shows,
Music,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
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)]
pub struct LibraryServer {
pub server_id: String,
pub name: String,
pub online: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArtworkKind {
Poster,
Background,
Thumb,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Artwork {
pub id: ArtworkId,
pub kind: ArtworkKind,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlaybackState {
#[serde(with = "duration_ms::option")]
pub position: Option<Duration>,
pub watched: bool,
#[serde(default)]
pub last_viewed_at: Option<i64>,
#[serde(default)]
pub play_count: u32,
#[serde(default)]
pub last_played_at: Option<i64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
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 = "duration_ms::option")]
pub duration: Option<Duration>,
#[serde(default)]
pub cast: Vec<CastMember>,
pub artwork: Vec<Artwork>,
pub playback: PlaybackState,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
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)]
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)]
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 = "duration_ms::option")]
pub duration: Option<Duration>,
#[serde(default)]
pub cast: Vec<CastMember>,
pub artwork: Vec<Artwork>,
pub playback: PlaybackState,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
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)]
pub struct Artist {
pub id: MediaId,
pub name: String,
pub summary: Option<String>,
pub artwork: Vec<Artwork>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
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)]
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 = "duration_ms::option")]
pub duration: Option<Duration>,
pub artwork: Vec<Artwork>,
pub playback: PlaybackState,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MarkerKind {
Intro,
Credits,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Marker {
pub kind: MarkerKind,
pub start_ms: u64,
pub end_ms: u64,
pub to_end: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Item {
Movie(Movie),
Show(Show),
Season(Season),
Episode(Episode),
Artist(Artist),
Album(Album),
Track(Track),
}
impl Item {
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,
}
}
}
#[cfg(test)]
mod tests {
use std::fmt::Debug;
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 durations_are_whole_milliseconds_on_the_wire() {
let json = serde_json::to_value(halfway()).unwrap();
assert_eq!(json["position"], 2_220_500);
}
#[test]
fn an_unstarted_item_has_a_null_position() {
let json = serde_json::to_value(PlaybackState::default()).unwrap();
assert!(json["position"].is_null());
}
#[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 a_marker_is_milliseconds_and_a_snake_case_kind_on_the_wire() {
let marker = Marker {
kind: MarkerKind::Credits,
start_ms: 2_662_962,
end_ms: 2_709_958,
to_end: true,
};
assert_eq!(
serde_json::to_value(marker).unwrap(),
serde_json::json!({
"kind": "credits",
"start_ms": 2_662_962,
"end_ms": 2_709_958,
"to_end": true,
})
);
round_trip(marker);
}
#[test]
fn a_marker_kind_from_a_newer_server_is_unknown() {
let marker: Marker = serde_json::from_str(
r#"{"kind": "recap", "start_ms": 0, "end_ms": 30000, "to_end": false}"#,
)
.unwrap();
assert_eq!(marker.kind, MarkerKind::Unknown);
}
#[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));
}
#[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,
},
});
}
}