Skip to main content

spoolframe_types/
model.rs

1//! The media model clients browse: libraries, and the movies, shows and
2//! music in them.
3//!
4//! `playback` is filled in by the server for the session's own user; it
5//! never comes from Plex.
6
7use std::time::{Duration, SystemTime};
8
9use serde::{Deserialize, Serialize};
10
11use crate::codec::AudioCodec;
12use crate::date::CalendarDate;
13use crate::id::{ArtworkId, LibraryId, MediaId, PersonId};
14use crate::search::PersonRole;
15use crate::serde_time;
16
17/// What a library holds.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
19#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
20#[serde(rename_all = "snake_case")]
21pub enum LibraryKind {
22    Movies,
23    Shows,
24    Music,
25}
26
27/// A library of one kind of media.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
30pub struct Library {
31    pub id: LibraryId,
32    pub title: String,
33    pub kind: LibraryKind,
34    /// The paired server a library is shared from (experimental
35    /// `federation`): only on a library of another server's, and
36    /// only to a client that named the feature. `None` for the server's
37    /// own libraries, and left out then, as experimental fields are.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub server: Option<LibraryServer>,
40}
41
42/// The server a library of another server's is shared from, so a
43/// client groups libraries by server, an offline one last and greyed.
44#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
45#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
46pub struct LibraryServer {
47    /// Its server id: the origin a `fed:` id names.
48    pub server_id: String,
49    /// What it calls itself.
50    pub name: String,
51    /// Whether this server is connected to it now. Offline, what it shared
52    /// is still browsed from the cache, and its items do not play.
53    pub online: bool,
54}
55
56/// The role a piece of artwork plays.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
58#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
59#[serde(rename_all = "snake_case")]
60pub enum ArtworkKind {
61    Poster,
62    Background,
63    Thumb,
64}
65
66/// A reference to artwork. Clients fetch the image through the client
67/// protocol with the `id`.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
70pub struct Artwork {
71    pub id: ArtworkId,
72    pub kind: ArtworkKind,
73}
74
75/// The session user's progress on an item.
76#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
77#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
78pub struct PlaybackState {
79    /// Where playback stopped, or `None` if it never started.
80    #[serde(with = "serde_time::millis::option_required")]
81    pub position: Option<Duration>,
82    pub watched: bool,
83    /// When the user last viewed it (Unix seconds on the wire): their last progress
84    /// report on it from any device, or its last mark as watched or
85    /// unwatched. Filled where its reply says so (Home's rows, an item's
86    /// details); `None` elsewhere, and for an item never viewed.
87    ///
88    /// This and the two below are read as none when left out: the SDK
89    /// keeps an item with its download, and a download kept by an older
90    /// SDK lacks the keys.
91    #[serde(default, with = "serde_time::unix_seconds::option")]
92    pub last_viewed_at: Option<SystemTime>,
93    /// How many times the user played it through: their counted plays
94    /// from any device. Filled where its reply says so (an
95    /// item's details, Recently played); 0 elsewhere.
96    #[serde(default)]
97    pub play_count: u32,
98    /// When the user last played it (Unix seconds on the wire): the end of their
99    /// latest counted play. Filled where `play_count` is; `None` for an
100    /// item never played.
101    #[serde(default, with = "serde_time::unix_seconds::option")]
102    pub last_played_at: Option<SystemTime>,
103}
104
105impl PlaybackState {
106    /// Where a Play goes on from, as `PlaybackOptions::start` takes it:
107    /// `None`, the start, once watched or never begun; else where it
108    /// stopped.
109    pub fn resume_from(&self) -> Option<Duration> {
110        if self.watched {
111            return None;
112        }
113        self.position.filter(|p| !p.is_zero())
114    }
115
116    /// How far through an item of `duration` the user is, for a
117    /// progress bar and "20 min left".
118    pub fn progress(&self, duration: Option<Duration>) -> Progress {
119        let position = self.position.unwrap_or_default();
120        let duration = duration.filter(|d| !d.is_zero());
121        Progress {
122            position,
123            remaining: duration.map(|d| d.saturating_sub(position)),
124            fraction: duration.map(|d| (position.as_secs_f64() / d.as_secs_f64()).clamp(0.0, 1.0)),
125            watched: self.watched,
126        }
127    }
128}
129
130/// How far through an item the user is ([`PlaybackState::progress`]).
131#[derive(Debug, Clone, Copy, PartialEq)]
132pub struct Progress {
133    /// Where playback stopped; zero if it never started.
134    pub position: Duration,
135    /// What is left to play; `None` with no length known.
136    pub remaining: Option<Duration>,
137    /// `position` over the length, from 0 to 1; `None` with no length
138    /// known.
139    pub fraction: Option<f64>,
140    pub watched: bool,
141}
142
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
144#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
145pub struct Movie {
146    pub id: MediaId,
147    pub title: String,
148    /// The year it came out: the catalog's own, else `release_date`'s.
149    pub year: Option<u16>,
150    /// The day it came out, `"YYYY-MM-DD"`.
151    ///
152    /// This and `cast` are read as `None` and no one when left out, though
153    /// every server sends them: the SDK keeps an item with its download,
154    /// and a download kept by an older SDK lacks the keys.
155    pub release_date: Option<CalendarDate>,
156    pub summary: Option<String>,
157    /// The age rating as the catalog has it ("R", "TV-MA"), shown as
158    /// is; `None` when it has none.
159    pub content_rating: Option<String>,
160    #[serde(with = "serde_time::millis::option_required")]
161    pub duration: Option<Duration>,
162    /// Who is in it and who directed it (see [`CastMember`]).
163    #[serde(default)]
164    pub cast: Vec<CastMember>,
165    pub artwork: Vec<Artwork>,
166    pub playback: PlaybackState,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
170#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
171pub struct Show {
172    pub id: MediaId,
173    pub title: String,
174    pub year: Option<u16>,
175    pub summary: Option<String>,
176    /// The age rating as the catalog has it ("R", "TV-MA"), shown as
177    /// is; `None` when it has none.
178    pub content_rating: Option<String>,
179    /// How many seasons it has, specials counted as one, as the catalog
180    /// counts them; `None` when it does not say.
181    pub season_count: Option<u32>,
182    /// Its genres, by the catalog's names and in its order. A listing
183    /// may hold only the first few: Plex gives two in listings and
184    /// search, and all of them on the show itself.
185    pub genres: Vec<String>,
186    /// The day its latest episode in the library first aired, for the
187    /// end of "2015–2018". Only the show's own item has it; `None` in
188    /// listings and search, and where no episode has a date.
189    ///
190    /// A catalog that does not know whether a show has ended (Plex does
191    /// not) still sets it on a running show: a client that shows a run
192    /// from it may show one that has not ended.
193    ///
194    /// This and `cast` are read as `None` and no one when left out, as
195    /// [`Movie::release_date`] is.
196    pub last_aired: Option<CalendarDate>,
197    /// Who is in it and who directed it (see [`CastMember`]).
198    #[serde(default)]
199    pub cast: Vec<CastMember>,
200    pub artwork: Vec<Artwork>,
201}
202
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
205pub struct Season {
206    pub id: MediaId,
207    pub show_id: MediaId,
208    /// The show's title, so a season shown alone needs no second request.
209    #[serde(deserialize_with = "crate::required::option")]
210    pub show_title: Option<String>,
211    /// The season number; 0 is specials.
212    pub season: u32,
213    pub title: String,
214    pub artwork: Vec<Artwork>,
215}
216
217#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
218#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
219pub struct Episode {
220    pub id: MediaId,
221    pub show_id: MediaId,
222    /// The show's title, so an episode shown alone (Continue watching)
223    /// needs no second request.
224    #[serde(deserialize_with = "crate::required::option")]
225    pub show_title: Option<String>,
226    pub season_id: MediaId,
227    pub season: u32,
228    pub episode: u32,
229    pub title: String,
230    pub summary: Option<String>,
231    /// The episode's own age rating, as on a movie; a client that has
232    /// none here may show the show's.
233    pub content_rating: Option<String>,
234    /// The year it first aired, for "2019" on its page: the catalog's
235    /// own, else `air_date`'s.
236    ///
237    /// This and `air_date` are not `required::option`, as
238    /// [`Movie::release_date`] is not.
239    pub year: Option<u16>,
240    /// The day it first aired, `"YYYY-MM-DD"`.
241    pub air_date: Option<CalendarDate>,
242    #[serde(with = "serde_time::millis::option_required")]
243    pub duration: Option<Duration>,
244    /// Who is in it and who directed it (see [`CastMember`]): the
245    /// episode's own, which may leave out the show's regulars. Left out,
246    /// no one, as [`Movie::cast`].
247    #[serde(default)]
248    pub cast: Vec<CastMember>,
249    pub artwork: Vec<Artwork>,
250    pub playback: PlaybackState,
251}
252
253/// Someone in a movie's, show's or episode's credits: an actor, with the
254/// part they play, or a director.
255///
256/// An item's `cast` is in the catalog's billing order, actors first, then
257/// directors. Only the item's own read (`Item`) has it; it is empty in
258/// listings, search and the home rows, where Plex gives names without
259/// the ids a person is listed by.
260#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
261#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
262pub struct CastMember {
263    /// The id a person search gives them: their items are listed with
264    /// `PersonItems`, as a found person's are.
265    pub id: PersonId,
266    pub name: String,
267    pub role: PersonRole,
268    /// The part an actor plays ("Ellen Ripley"), as the catalog has it;
269    /// `None` for a director, and for an actor where it does not say.
270    #[serde(deserialize_with = "crate::required::option")]
271    pub character: Option<String>,
272    /// Their portrait, fetched through the client protocol as any
273    /// artwork is; `None` where the catalog has none.
274    #[serde(deserialize_with = "crate::required::option")]
275    pub photo: Option<ArtworkId>,
276}
277
278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
280pub struct Artist {
281    pub id: MediaId,
282    pub name: String,
283    pub summary: Option<String>,
284    pub artwork: Vec<Artwork>,
285}
286
287#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
288#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
289pub struct Album {
290    pub id: MediaId,
291    pub artist_id: MediaId,
292    /// The artist's name, for the same reason.
293    #[serde(deserialize_with = "crate::required::option")]
294    pub artist_name: Option<String>,
295    pub title: String,
296    pub year: Option<u16>,
297    /// How many tracks it has, on every disc. `None` where the catalog
298    /// does not say: Plex counts them on the album itself, not in
299    /// listings or search.
300    pub track_count: Option<u32>,
301    pub artwork: Vec<Artwork>,
302}
303
304#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
305#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
306pub struct Track {
307    pub id: MediaId,
308    pub album_id: MediaId,
309    pub artist_id: MediaId,
310    /// Who it is by, so a track shown alone (a search result, a queue)
311    /// says whose it is: the track's own artist where its tags name one
312    /// ("Adele with Chris Stapleton"), else its album's.
313    pub artist_name: Option<String>,
314    /// Its album's title, for the same reason.
315    pub album_title: Option<String>,
316    pub title: String,
317    /// Position on its disc, when the tags say.
318    pub track: Option<u32>,
319    pub disc: Option<u32>,
320    /// How many tracks its album has (as `Album::track_count`), for
321    /// "track 3 of 9". Set on an album's own tracks, the children of
322    /// its item; `None` elsewhere.
323    pub album_track_count: Option<u32>,
324    /// The audio codec, `None` when the catalog does not say.
325    pub codec: Option<AudioCodec>,
326    /// Bits per sample (16, 24); `None` when not known, and for lossy
327    /// codecs, which have none. Known for an album's own tracks and a
328    /// track's own item, not in other listings or search.
329    pub bit_depth: Option<u32>,
330    /// Samples per second, in Hz (44_100, 96_000); known where
331    /// `bit_depth` is.
332    pub sample_rate: Option<u32>,
333    #[serde(with = "serde_time::millis::option_required")]
334    pub duration: Option<Duration>,
335    /// Its album's cover as the poster, and its artist's background.
336    pub artwork: Vec<Artwork>,
337    pub playback: PlaybackState,
338}
339
340/// What a marked stretch of an item is.
341#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
342#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
343#[serde(rename_all = "snake_case")]
344pub enum MarkerKind {
345    Intro,
346    Credits,
347    /// A kind this build does not know, from a newer server. Show nothing
348    /// for it.
349    #[serde(other)]
350    Unknown,
351}
352
353/// A stretch of a movie or episode a viewer may want to skip.
354#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
355#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
356pub struct Marker {
357    pub kind: MarkerKind,
358    /// Where it starts, from the start of the item (`start_ms` on the
359    /// wire).
360    #[serde(rename = "start_ms", with = "serde_time::millis")]
361    pub start: Duration,
362    /// Where it ends (`end_ms` on the wire). On a marker that runs to the
363    /// end this may be a little off the item's duration, either way: go
364    /// by `to_end`.
365    #[serde(rename = "end_ms", with = "serde_time::millis")]
366    pub end: Duration,
367    /// Nothing follows it: credits with no scene after them. The catalog
368    /// says so; it is never worked out from `end` and the duration.
369    pub to_end: bool,
370}
371
372/// An item's markers, in order of start, without the kinds this build
373/// does not know: one from a newer server (`MarkerKind::Unknown`), which
374/// an app shows nothing for, is left out as the list is read. The same
375/// list as `Vec<Marker>` on the wire and to Swift and Kotlin.
376#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
377#[serde(transparent)]
378pub struct Markers(Vec<Marker>);
379
380impl Markers {
381    pub fn into_vec(self) -> Vec<Marker> {
382        self.0
383    }
384}
385
386impl From<Vec<Marker>> for Markers {
387    fn from(mut markers: Vec<Marker>) -> Self {
388        markers.retain(|m| m.kind != MarkerKind::Unknown);
389        Self(markers)
390    }
391}
392
393impl<'de> Deserialize<'de> for Markers {
394    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
395        Vec::<Marker>::deserialize(d).map(Self::from)
396    }
397}
398
399impl std::ops::Deref for Markers {
400    type Target = [Marker];
401
402    fn deref(&self) -> &[Marker] {
403        &self.0
404    }
405}
406
407impl IntoIterator for Markers {
408    type Item = Marker;
409    type IntoIter = std::vec::IntoIter<Marker>;
410
411    fn into_iter(self) -> Self::IntoIter {
412        self.0.into_iter()
413    }
414}
415
416impl<'a> IntoIterator for &'a Markers {
417    type Item = &'a Marker;
418    type IntoIter = std::slice::Iter<'a, Marker>;
419
420    fn into_iter(self) -> Self::IntoIter {
421        self.0.iter()
422    }
423}
424
425/// Any one item a catalog returns. On the wire it is the item's own object
426/// with a `kind` field added, for example `{"kind": "movie", "id": …}`.
427#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
428#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
429#[serde(tag = "kind", rename_all = "snake_case")]
430pub enum Item {
431    Movie(Movie),
432    Show(Show),
433    Season(Season),
434    Episode(Episode),
435    Artist(Artist),
436    Album(Album),
437    Track(Track),
438}
439
440/// The years a show ran, as its card says them.
441#[derive(Debug, Clone, Copy, PartialEq, Eq)]
442#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
443pub enum YearsAired {
444    /// "2019": it ran in one year, or only one is known.
445    One(u16),
446    /// "2019–": an episode aired in the last twelve months.
447    Running(u16),
448    /// "2019–2023".
449    Between(u16, u16),
450}
451
452/// "2019", "2019–", "2019–2023".
453impl std::fmt::Display for YearsAired {
454    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
455        match self {
456            YearsAired::One(year) => write!(f, "{year}"),
457            YearsAired::Running(first) => write!(f, "{first}\u{2013}"),
458            YearsAired::Between(first, last) => write!(f, "{first}\u{2013}{last}"),
459        }
460    }
461}
462
463impl Show {
464    /// The years it ran, from its first year and the day its latest
465    /// episode aired: one year when that was the same year, running when
466    /// it aired in the twelve months up to `today`, else both years. With
467    /// no first year, the latest episode's year alone; `None` with
468    /// neither.
469    pub fn year_range(&self, today: CalendarDate) -> Option<YearsAired> {
470        let Some(last) = self.last_aired else {
471            return self.year.map(YearsAired::One);
472        };
473        let Some(first) = self.year else {
474            return Some(YearsAired::One(last.year()));
475        };
476        if last.year() <= first {
477            return Some(YearsAired::One(first));
478        }
479        // A year back from today, compared field by field: most years have
480        // no 29 February to land on.
481        let year_ago = (today.year() - 1, today.month(), today.day());
482        if (last.year(), last.month(), last.day()) >= year_ago {
483            Some(YearsAired::Running(first))
484        } else {
485            Some(YearsAired::Between(first, last.year()))
486        }
487    }
488
489    /// [`Show::year_range`] as text: "2019", "2019–", "2019–2023".
490    pub fn years_label(&self, today: CalendarDate) -> Option<String> {
491        self.year_range(today).map(|years| years.to_string())
492    }
493}
494
495/// The line under a card's title, in parts.
496#[derive(Debug, Clone, PartialEq, Eq)]
497#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
498pub enum Caption {
499    /// A film's year.
500    Year(u16),
501    /// A show's years.
502    Years(YearsAired),
503    /// A season's show.
504    Show(String),
505    /// An episode: its show, and where it is in it ("S2 · E5").
506    Episode {
507        show: Option<String>,
508        season: u32,
509        episode: u32,
510    },
511    /// An album's artist and year.
512    Album {
513        artist: Option<String>,
514        year: Option<u16>,
515    },
516    /// A track's length.
517    Length(Duration),
518}
519
520#[cfg_attr(feature = "uniffi", uniffi::export)]
521impl Item {
522    /// Its length, for the kinds that play.
523    pub fn duration(&self) -> Option<Duration> {
524        match self {
525            Item::Movie(m) => m.duration,
526            Item::Episode(e) => e.duration,
527            Item::Track(t) => t.duration,
528            _ => None,
529        }
530    }
531}
532
533impl Item {
534    /// What a card says under its title on `today`; `None` for an artist
535    /// or where nothing is known.
536    pub fn caption_parts(&self, today: CalendarDate) -> Option<Caption> {
537        match self {
538            Item::Movie(m) => m.year.map(Caption::Year),
539            Item::Show(s) => s.year_range(today).map(Caption::Years),
540            Item::Season(s) => s.show_title.clone().map(Caption::Show),
541            Item::Episode(e) => Some(Caption::Episode {
542                show: e.show_title.clone(),
543                season: e.season,
544                episode: e.episode,
545            }),
546            Item::Album(a) => {
547                (a.artist_name.is_some() || a.year.is_some()).then(|| Caption::Album {
548                    artist: a.artist_name.clone(),
549                    year: a.year,
550                })
551            }
552            Item::Track(t) => t.duration.map(Caption::Length),
553            Item::Artist(_) => None,
554        }
555    }
556
557    pub fn id(&self) -> &MediaId {
558        match self {
559            Item::Movie(m) => &m.id,
560            Item::Show(s) => &s.id,
561            Item::Season(s) => &s.id,
562            Item::Episode(e) => &e.id,
563            Item::Artist(a) => &a.id,
564            Item::Album(a) => &a.id,
565            Item::Track(t) => &t.id,
566        }
567    }
568
569    /// Its own name: a film's, an episode's or a track's title; an
570    /// artist's name.
571    pub fn title(&self) -> &str {
572        match self {
573            Item::Movie(m) => &m.title,
574            Item::Show(s) => &s.title,
575            Item::Season(s) => &s.title,
576            Item::Episode(e) => &e.title,
577            Item::Artist(a) => &a.name,
578            Item::Album(a) => &a.title,
579            Item::Track(t) => &t.title,
580        }
581    }
582
583    /// Its artwork, whatever kind it is.
584    pub fn artwork(&self) -> &[Artwork] {
585        match self {
586            Item::Movie(m) => &m.artwork,
587            Item::Show(s) => &s.artwork,
588            Item::Season(s) => &s.artwork,
589            Item::Episode(e) => &e.artwork,
590            Item::Artist(a) => &a.artwork,
591            Item::Album(a) => &a.artwork,
592            Item::Track(t) => &t.artwork,
593        }
594    }
595
596    /// Its first artwork of `kind`: what a row or a page shows.
597    pub fn artwork_of(&self, kind: ArtworkKind) -> Option<&Artwork> {
598        self.artwork().iter().find(|a| a.kind == kind)
599    }
600
601    /// The user's progress on a film, an episode or a track; `None` for
602    /// the kinds that do not play themselves.
603    pub fn playback(&self) -> Option<&PlaybackState> {
604        match self {
605            Item::Movie(m) => Some(&m.playback),
606            Item::Episode(e) => Some(&e.playback),
607            Item::Track(t) => Some(&t.playback),
608            _ => None,
609        }
610    }
611
612    /// The user watched it (or played it to its end).
613    pub fn is_watched(&self) -> bool {
614        self.playback().is_some_and(|p| p.watched)
615    }
616
617    /// Where the user stopped in it, watched or not.
618    pub fn resume_position(&self) -> Option<Duration> {
619        self.playback().and_then(|p| p.position)
620    }
621
622    /// Where a Play goes on from ([`PlaybackState::resume_from`]).
623    pub fn resume_from(&self) -> Option<Duration> {
624        self.playback().and_then(PlaybackState::resume_from)
625    }
626
627    /// How far through it the user is ([`PlaybackState::progress`]);
628    /// `None` for the kinds that do not play themselves.
629    pub fn progress(&self) -> Option<Progress> {
630        Some(self.playback()?.progress(self.duration()))
631    }
632}
633
634#[cfg(test)]
635mod tests {
636    use std::fmt::Debug;
637    use std::time::UNIX_EPOCH;
638
639    use serde::de::DeserializeOwned;
640
641    use super::*;
642    use crate::id::{MediaKind, Namespace};
643
644    fn round_trip<T: Serialize + DeserializeOwned + PartialEq + Debug>(value: T) {
645        let json = serde_json::to_string(&value).unwrap();
646        assert_eq!(serde_json::from_str::<T>(&json).unwrap(), value, "{json}");
647    }
648
649    fn media(kind: MediaKind, key: &str) -> MediaId {
650        MediaId::new(Namespace::Plex, kind, key).unwrap()
651    }
652
653    fn poster() -> Vec<Artwork> {
654        vec![Artwork {
655            id: ArtworkId::new(Namespace::Plex, "/library/metadata/1/thumb/9").unwrap(),
656            kind: ArtworkKind::Poster,
657        }]
658    }
659
660    fn halfway() -> PlaybackState {
661        PlaybackState {
662            position: Some(Duration::from_millis(2_220_500)),
663            watched: false,
664            last_viewed_at: None,
665            play_count: 0,
666            last_played_at: None,
667        }
668    }
669
670    fn ripley() -> CastMember {
671        CastMember {
672            id: PersonId::new(Namespace::Plex, "actor-13").unwrap(),
673            name: "Sigourney Weaver".into(),
674            role: PersonRole::Actor,
675            character: Some("Ellen Ripley".into()),
676            photo: Some(ArtworkId::new(Namespace::Plex, "/people/1/a/b.jpg").unwrap()),
677        }
678    }
679
680    fn scott() -> CastMember {
681        CastMember {
682            id: PersonId::new(Namespace::Plex, "director-7").unwrap(),
683            name: "Ridley Scott".into(),
684            role: PersonRole::Director,
685            character: None,
686            photo: None,
687        }
688    }
689
690    #[test]
691    fn a_cast_member_is_their_person_id_role_and_photo_on_the_wire() {
692        assert_eq!(
693            serde_json::to_value(ripley()).unwrap(),
694            serde_json::json!({
695                "id": "plex:actor-13",
696                "name": "Sigourney Weaver",
697                "role": "actor",
698                "character": "Ellen Ripley",
699                "photo": "plex:/people/1/a/b.jpg",
700            })
701        );
702        round_trip(ripley());
703        round_trip(scott());
704    }
705
706    /// A new type, so every field is sent (PX-15): `null` for none.
707    #[test]
708    fn a_cast_member_s_character_and_photo_are_required() {
709        crate::test_support::assert_each_required(&scott(), &["character", "photo"]);
710    }
711
712    /// `cast`, `release_date` and `last_aired` came without a revision
713    /// bump: a server from before them leaves them out.
714    #[test]
715    fn items_from_a_server_without_cast_or_dates_still_decode() {
716        let movie = Movie {
717            id: media(MediaKind::Movie, "10"),
718            title: "Alien".into(),
719            year: Some(1979),
720            release_date: CalendarDate::new(1979, 5, 25),
721            summary: None,
722            content_rating: None,
723            duration: None,
724            cast: vec![ripley()],
725            artwork: Vec::new(),
726            playback: PlaybackState::default(),
727        };
728        let mut json = serde_json::to_value(&movie).unwrap();
729        assert_eq!(json["release_date"], "1979-05-25");
730        let object = json.as_object_mut().unwrap();
731        object.remove("release_date");
732        object.remove("cast");
733        let older: Movie = serde_json::from_value(json).unwrap();
734        assert_eq!((older.release_date, older.cast), (None, Vec::new()));
735
736        let show = Show {
737            id: media(MediaKind::Show, "20"),
738            title: "The Expanse".into(),
739            year: Some(2015),
740            summary: None,
741            content_rating: None,
742            season_count: None,
743            genres: Vec::new(),
744            last_aired: CalendarDate::new(2022, 4, 8),
745            cast: vec![ripley()],
746            artwork: Vec::new(),
747        };
748        let mut json = serde_json::to_value(&show).unwrap();
749        assert_eq!(json["last_aired"], "2022-04-08");
750        let object = json.as_object_mut().unwrap();
751        object.remove("last_aired");
752        object.remove("cast");
753        let older: Show = serde_json::from_value(json).unwrap();
754        assert_eq!((older.last_aired, older.cast), (None, Vec::new()));
755
756        let episode = Episode {
757            id: media(MediaKind::Episode, "22"),
758            show_id: media(MediaKind::Show, "20"),
759            show_title: None,
760            season_id: media(MediaKind::Season, "21"),
761            season: 1,
762            episode: 1,
763            title: "Dulcinea".into(),
764            summary: None,
765            content_rating: None,
766            year: None,
767            air_date: None,
768            duration: None,
769            cast: vec![scott()],
770            artwork: Vec::new(),
771            playback: PlaybackState::default(),
772        };
773        let mut json = serde_json::to_value(&episode).unwrap();
774        json.as_object_mut().unwrap().remove("cast");
775        let older: Episode = serde_json::from_value(json).unwrap();
776        assert_eq!(older.cast, Vec::new());
777    }
778
779    #[test]
780    fn a_track_s_format_is_plain_numbers_on_the_wire() {
781        let track = Track {
782            id: media(MediaKind::Track, "224630"),
783            album_id: media(MediaKind::Album, "224629"),
784            artist_id: media(MediaKind::Artist, "224303"),
785            artist_name: None,
786            album_title: None,
787            title: "Catch".into(),
788            track: Some(1),
789            disc: Some(1),
790            album_track_count: Some(3),
791            codec: Some(AudioCodec::Flac),
792            bit_depth: Some(24),
793            sample_rate: Some(96_000),
794            duration: None,
795            artwork: Vec::new(),
796            playback: PlaybackState::default(),
797        };
798        let json = serde_json::to_value(&track).unwrap();
799        assert_eq!(
800            (
801                &json["codec"],
802                &json["bit_depth"],
803                &json["sample_rate"],
804                &json["album_track_count"]
805            ),
806            (
807                &serde_json::json!("flac"),
808                &serde_json::json!(24),
809                &serde_json::json!(96_000),
810                &serde_json::json!(3)
811            )
812        );
813    }
814
815    #[test]
816    fn library_kinds_are_snake_case_on_the_wire() {
817        assert_eq!(
818            serde_json::to_string(&LibraryKind::Movies).unwrap(),
819            r#""movies""#
820        );
821    }
822
823    #[test]
824    fn an_item_carries_its_kind_on_the_wire() {
825        let item = Item::Show(Show {
826            id: media(MediaKind::Show, "20"),
827            title: "The Expanse".into(),
828            year: None,
829            summary: None,
830            content_rating: None,
831            season_count: None,
832            genres: Vec::new(),
833            last_aired: None,
834            cast: Vec::new(),
835            artwork: Vec::new(),
836        });
837        let json = serde_json::to_value(&item).unwrap();
838        assert_eq!(json["kind"], "show");
839        assert_eq!(json["id"], "plex:show:20");
840        round_trip(item);
841    }
842
843    /// The parent's name on a season, an episode and an album was once
844    /// `serde(default)`; every field is now required (PX-15).
845    #[test]
846    fn a_parent_s_name_left_out_is_refused() {
847        let season = Season {
848            id: media(MediaKind::Season, "21"),
849            show_id: media(MediaKind::Show, "20"),
850            show_title: None,
851            season: 1,
852            title: "Season 1".into(),
853            artwork: Vec::new(),
854        };
855        crate::test_support::assert_each_required(&season, &["show_title"]);
856        let episode = Episode {
857            id: media(MediaKind::Episode, "22"),
858            show_id: media(MediaKind::Show, "20"),
859            show_title: None,
860            season_id: media(MediaKind::Season, "21"),
861            season: 1,
862            episode: 1,
863            title: "Dulcinea".into(),
864            summary: None,
865            content_rating: None,
866            year: None,
867            air_date: None,
868            duration: None,
869            cast: Vec::new(),
870            artwork: Vec::new(),
871            playback: PlaybackState::default(),
872        };
873        crate::test_support::assert_each_required(&episode, &["show_title"]);
874        let album = Album {
875            id: media(MediaKind::Album, "30"),
876            artist_id: media(MediaKind::Artist, "31"),
877            artist_name: None,
878            title: "Moon Safari".into(),
879            year: None,
880            track_count: None,
881            artwork: Vec::new(),
882        };
883        crate::test_support::assert_each_required(&album, &["artist_name"]);
884        // `null` is how none is sent.
885        round_trip(album);
886    }
887
888    #[test]
889    fn an_episode_from_a_server_without_air_dates_still_decodes() {
890        let episode = Episode {
891            id: media(MediaKind::Episode, "22"),
892            show_id: media(MediaKind::Show, "20"),
893            show_title: None,
894            season_id: media(MediaKind::Season, "21"),
895            season: 1,
896            episode: 1,
897            title: "Dulcinea".into(),
898            summary: None,
899            content_rating: None,
900            year: Some(2015),
901            air_date: CalendarDate::new(2015, 11, 23),
902            duration: None,
903            cast: Vec::new(),
904            artwork: Vec::new(),
905            playback: PlaybackState::default(),
906        };
907        let mut json = serde_json::to_value(&episode).unwrap();
908        assert_eq!(json["air_date"], "2015-11-23");
909        let object = json.as_object_mut().unwrap();
910        object.remove("year");
911        object.remove("air_date");
912        let older: Episode = serde_json::from_value(json).unwrap();
913        assert_eq!((older.year, older.air_date), (None, None));
914    }
915
916    /// "Today" for a show's years: 14 October 2026.
917    fn years(year: Option<u16>, last_aired: Option<(u16, u8, u8)>) -> Option<String> {
918        let show = Show {
919            id: media(MediaKind::Show, "20"),
920            title: "Andor".into(),
921            year,
922            summary: None,
923            content_rating: None,
924            season_count: None,
925            genres: Vec::new(),
926            last_aired: last_aired.and_then(|(y, m, d)| CalendarDate::new(y, m, d)),
927            cast: Vec::new(),
928            artwork: Vec::new(),
929        };
930        show.years_label(CalendarDate::new(2026, 10, 14).unwrap())
931    }
932
933    #[test]
934    fn a_show_s_years_come_in_parts() {
935        let show = |last: (u16, u8, u8)| Show {
936            id: media(MediaKind::Show, "20"),
937            title: "Andor".into(),
938            year: Some(2022),
939            summary: None,
940            content_rating: None,
941            season_count: None,
942            genres: Vec::new(),
943            last_aired: CalendarDate::new(last.0, last.1, last.2),
944            cast: Vec::new(),
945            artwork: Vec::new(),
946        };
947        let today = CalendarDate::new(2026, 10, 14).unwrap();
948        assert_eq!(
949            show((2025, 10, 14)).year_range(today),
950            Some(YearsAired::Running(2022))
951        );
952        assert_eq!(
953            show((2025, 10, 13)).year_range(today),
954            Some(YearsAired::Between(2022, 2025))
955        );
956        assert_eq!(
957            Item::Show(show((2022, 5, 1))).caption_parts(today),
958            Some(Caption::Years(YearsAired::One(2022)))
959        );
960    }
961
962    #[test]
963    fn a_show_with_no_air_date_shows_its_first_year() {
964        assert_eq!(years(Some(2022), None), Some("2022".into()));
965        assert_eq!(years(None, None), None);
966    }
967
968    #[test]
969    fn a_show_last_aired_in_its_first_year_shows_that_year() {
970        assert_eq!(years(Some(2022), Some((2022, 12, 1))), Some("2022".into()));
971    }
972
973    #[test]
974    fn a_show_aired_in_the_last_twelve_months_is_an_open_range() {
975        assert_eq!(
976            years(Some(2022), Some((2025, 10, 14))),
977            Some("2022\u{2013}".into())
978        );
979    }
980
981    #[test]
982    fn a_show_last_aired_over_a_year_ago_shows_both_years() {
983        assert_eq!(
984            years(Some(2022), Some((2025, 10, 13))),
985            Some("2022\u{2013}2025".into())
986        );
987    }
988
989    #[test]
990    fn a_show_with_no_first_year_shows_when_it_last_aired() {
991        assert_eq!(years(None, Some((2019, 3, 2))), Some("2019".into()));
992    }
993
994    #[test]
995    fn every_model_type_round_trips() {
996        round_trip(Library {
997            id: LibraryId::new(Namespace::Plex, "1").unwrap(),
998            title: "Movies".into(),
999            kind: LibraryKind::Movies,
1000            server: None,
1001        });
1002        round_trip(Movie {
1003            id: media(MediaKind::Movie, "10"),
1004            title: "Alien".into(),
1005            year: Some(1979),
1006            release_date: CalendarDate::new(1979, 5, 25),
1007            summary: Some("In space no one can hear you scream.".into()),
1008            content_rating: Some("R".into()),
1009            duration: Some(Duration::from_secs(7020)),
1010            cast: vec![ripley(), scott()],
1011            artwork: poster(),
1012            playback: halfway(),
1013        });
1014        round_trip(Show {
1015            id: media(MediaKind::Show, "20"),
1016            title: "The Expanse".into(),
1017            year: Some(2015),
1018            summary: None,
1019            content_rating: Some("TV-14".into()),
1020            season_count: Some(6),
1021            genres: vec!["Science Fiction".into(), "Drama".into()],
1022            last_aired: CalendarDate::new(2022, 4, 8),
1023            cast: vec![ripley()],
1024            artwork: poster(),
1025        });
1026        round_trip(Season {
1027            id: media(MediaKind::Season, "21"),
1028            show_id: media(MediaKind::Show, "20"),
1029            show_title: Some("The Expanse".into()),
1030            season: 1,
1031            title: "Season 1".into(),
1032            artwork: Vec::new(),
1033        });
1034        round_trip(Episode {
1035            id: media(MediaKind::Episode, "22"),
1036            show_id: media(MediaKind::Show, "20"),
1037            show_title: Some("The Expanse".into()),
1038            season_id: media(MediaKind::Season, "21"),
1039            season: 1,
1040            episode: 1,
1041            title: "Dulcinea".into(),
1042            summary: None,
1043            content_rating: Some("TV-14".into()),
1044            year: Some(2015),
1045            air_date: CalendarDate::new(2015, 11, 23),
1046            duration: Some(Duration::from_secs(2640)),
1047            cast: vec![scott()],
1048            artwork: poster(),
1049            playback: PlaybackState::default(),
1050        });
1051        round_trip(Artist {
1052            id: media(MediaKind::Artist, "30"),
1053            name: "Boards of Canada".into(),
1054            summary: None,
1055            artwork: poster(),
1056        });
1057        round_trip(Album {
1058            id: media(MediaKind::Album, "31"),
1059            artist_id: media(MediaKind::Artist, "30"),
1060            artist_name: Some("Boards of Canada".into()),
1061            title: "Music Has the Right to Children".into(),
1062            year: Some(1998),
1063            track_count: Some(18),
1064            artwork: poster(),
1065        });
1066        round_trip(Track {
1067            id: media(MediaKind::Track, "32"),
1068            album_id: media(MediaKind::Album, "31"),
1069            artist_id: media(MediaKind::Artist, "30"),
1070            artist_name: Some("Boards of Canada".into()),
1071            album_title: Some("Music Has the Right to Children".into()),
1072            title: "Roygbiv".into(),
1073            track: Some(10),
1074            disc: Some(1),
1075            album_track_count: Some(18),
1076            codec: Some(AudioCodec::Flac),
1077            bit_depth: Some(16),
1078            sample_rate: Some(44_100),
1079            duration: Some(Duration::from_secs(151)),
1080            artwork: poster(),
1081            playback: PlaybackState {
1082                position: None,
1083                watched: true,
1084                last_viewed_at: None,
1085                play_count: 0,
1086                last_played_at: None,
1087            },
1088        });
1089    }
1090
1091    fn alien(playback: PlaybackState, duration: Option<Duration>) -> Item {
1092        Item::Movie(Movie {
1093            id: media(MediaKind::Movie, "10"),
1094            title: "Alien".into(),
1095            year: Some(1979),
1096            release_date: None,
1097            summary: None,
1098            content_rating: None,
1099            duration,
1100            cast: Vec::new(),
1101            artwork: Vec::new(),
1102            playback,
1103        })
1104    }
1105
1106    /// Markers and watch times keep their wire names and units: `_ms`
1107    /// spans, a position in whole milliseconds (`null` unstarted) and Unix
1108    /// seconds.
1109    #[test]
1110    fn markers_and_watch_times_keep_their_wire_form() {
1111        let marker = Marker {
1112            kind: MarkerKind::Intro,
1113            start: Duration::from_millis(258_865),
1114            end: Duration::from_millis(319_865),
1115            to_end: false,
1116        };
1117        let state = PlaybackState {
1118            last_viewed_at: Some(UNIX_EPOCH + Duration::from_secs(1_761_700_000)),
1119            play_count: 2,
1120            last_played_at: Some(UNIX_EPOCH + Duration::from_secs(1_761_600_000)),
1121            ..PlaybackState::default()
1122        };
1123        assert_eq!(
1124            (
1125                serde_json::to_value(marker).unwrap(),
1126                serde_json::to_value(&state).unwrap(),
1127                serde_json::to_value(halfway()).unwrap()["position"].clone(),
1128            ),
1129            (
1130                serde_json::json!({
1131                    "kind": "intro", "start_ms": 258_865, "end_ms": 319_865, "to_end": false
1132                }),
1133                serde_json::json!({
1134                    "position": null, "watched": false, "last_viewed_at": 1_761_700_000,
1135                    "play_count": 2, "last_played_at": 1_761_600_000
1136                }),
1137                serde_json::json!(2_220_500),
1138            )
1139        );
1140        round_trip(marker);
1141        round_trip(state);
1142    }
1143
1144    #[test]
1145    fn a_marker_list_leaves_out_kinds_this_build_does_not_know() {
1146        let listed: Markers = serde_json::from_value(serde_json::json!([
1147            { "kind": "recap", "start_ms": 0, "end_ms": 60_000, "to_end": false },
1148            { "kind": "intro", "start_ms": 60_000, "end_ms": 90_000, "to_end": false },
1149        ]))
1150        .unwrap();
1151        let intro = Marker {
1152            kind: MarkerKind::Intro,
1153            start: Duration::from_millis(60_000),
1154            end: Duration::from_millis(90_000),
1155            to_end: false,
1156        };
1157        assert_eq!(*listed, [intro]);
1158        assert_eq!(
1159            serde_json::to_value(&listed).unwrap()[0]["start_ms"],
1160            60_000
1161        );
1162    }
1163
1164    #[test]
1165    fn an_item_s_artwork_of_a_kind_is_its_first_one() {
1166        let art = |kind, path: &str| Artwork {
1167            id: ArtworkId::new(Namespace::Plex, path).unwrap(),
1168            kind,
1169        };
1170        let Item::Movie(mut movie) = alien(PlaybackState::default(), None) else {
1171            unreachable!()
1172        };
1173        movie.artwork = vec![
1174            art(ArtworkKind::Background, "/bg"),
1175            art(ArtworkKind::Poster, "/p1"),
1176            art(ArtworkKind::Poster, "/p2"),
1177        ];
1178        let item = Item::Movie(movie);
1179        assert_eq!(
1180            [
1181                ArtworkKind::Poster,
1182                ArtworkKind::Background,
1183                ArtworkKind::Thumb
1184            ]
1185            .map(|kind| item.artwork_of(kind).cloned()),
1186            [
1187                Some(art(ArtworkKind::Poster, "/p1")),
1188                Some(art(ArtworkKind::Background, "/bg")),
1189                None
1190            ]
1191        );
1192    }
1193
1194    fn at(secs: u64, watched: bool) -> PlaybackState {
1195        PlaybackState {
1196            position: Some(Duration::from_secs(secs)),
1197            watched,
1198            ..PlaybackState::default()
1199        }
1200    }
1201
1202    #[test]
1203    fn a_film_stopped_part_way_resumes_where_it_stopped() {
1204        assert_eq!(at(600, false).resume_from(), Some(Duration::from_secs(600)));
1205    }
1206
1207    #[test]
1208    fn a_watched_film_plays_from_the_start() {
1209        assert_eq!(at(600, true).resume_from(), None);
1210    }
1211
1212    #[test]
1213    fn a_film_never_begun_plays_from_the_start() {
1214        assert_eq!(PlaybackState::default().resume_from(), None);
1215        assert_eq!(at(0, false).resume_from(), None);
1216    }
1217
1218    #[test]
1219    fn progress_is_the_fraction_watched_and_the_time_left() {
1220        let progress = at(1_500, false).progress(Some(Duration::from_secs(6_000)));
1221        assert_eq!(
1222            progress,
1223            Progress {
1224                position: Duration::from_secs(1_500),
1225                remaining: Some(Duration::from_secs(4_500)),
1226                fraction: Some(0.25),
1227                watched: false,
1228            }
1229        );
1230    }
1231
1232    #[test]
1233    fn progress_past_the_length_is_whole_with_nothing_left() {
1234        let progress = at(7_000, true).progress(Some(Duration::from_secs(6_000)));
1235        assert_eq!(
1236            (progress.fraction, progress.remaining, progress.watched),
1237            (Some(1.0), Some(Duration::ZERO), true)
1238        );
1239    }
1240
1241    #[test]
1242    fn progress_with_no_length_has_no_fraction() {
1243        for length in [None, Some(Duration::ZERO)] {
1244            let progress = at(60, false).progress(length);
1245            assert_eq!((progress.fraction, progress.remaining), (None, None));
1246        }
1247    }
1248
1249    #[test]
1250    fn an_item_answers_from_its_own_playback() {
1251        let item = alien(at(600, false), Some(Duration::from_secs(1_200)));
1252        assert_eq!(item.title(), "Alien");
1253        assert!(!item.is_watched());
1254        assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
1255        assert_eq!(item.resume_from(), Some(Duration::from_secs(600)));
1256        assert_eq!(item.progress().and_then(|p| p.fraction), Some(0.5));
1257    }
1258
1259    #[test]
1260    fn a_watched_item_keeps_its_position_but_resumes_from_the_start() {
1261        let item = alien(at(600, true), None);
1262        assert!(item.is_watched());
1263        assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
1264        assert_eq!(item.resume_from(), None);
1265    }
1266
1267    #[test]
1268    fn an_artist_has_a_title_but_no_progress() {
1269        let show = Item::Artist(Artist {
1270            id: media(MediaKind::Artist, "30"),
1271            name: "Daft Punk".into(),
1272            summary: None,
1273            artwork: Vec::new(),
1274        });
1275        assert_eq!(show.title(), "Daft Punk");
1276        assert_eq!(show.progress(), None);
1277        assert!(!show.is_watched());
1278        assert_eq!(show.resume_from(), None);
1279    }
1280}