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
520impl Item {
521    /// Its length, for the kinds that play.
522    pub fn duration(&self) -> Option<Duration> {
523        match self {
524            Item::Movie(m) => m.duration,
525            Item::Episode(e) => e.duration,
526            Item::Track(t) => t.duration,
527            _ => None,
528        }
529    }
530}
531
532impl Item {
533    /// What a card says under its title on `today`; `None` for an artist
534    /// or where nothing is known.
535    pub fn caption_parts(&self, today: CalendarDate) -> Option<Caption> {
536        match self {
537            Item::Movie(m) => m.year.map(Caption::Year),
538            Item::Show(s) => s.year_range(today).map(Caption::Years),
539            Item::Season(s) => s.show_title.clone().map(Caption::Show),
540            Item::Episode(e) => Some(Caption::Episode {
541                show: e.show_title.clone(),
542                season: e.season,
543                episode: e.episode,
544            }),
545            Item::Album(a) => {
546                (a.artist_name.is_some() || a.year.is_some()).then(|| Caption::Album {
547                    artist: a.artist_name.clone(),
548                    year: a.year,
549                })
550            }
551            Item::Track(t) => t.duration.map(Caption::Length),
552            Item::Artist(_) => None,
553        }
554    }
555
556    pub fn id(&self) -> &MediaId {
557        match self {
558            Item::Movie(m) => &m.id,
559            Item::Show(s) => &s.id,
560            Item::Season(s) => &s.id,
561            Item::Episode(e) => &e.id,
562            Item::Artist(a) => &a.id,
563            Item::Album(a) => &a.id,
564            Item::Track(t) => &t.id,
565        }
566    }
567
568    /// Its own name: a film's, an episode's or a track's title; an
569    /// artist's name.
570    pub fn title(&self) -> &str {
571        match self {
572            Item::Movie(m) => &m.title,
573            Item::Show(s) => &s.title,
574            Item::Season(s) => &s.title,
575            Item::Episode(e) => &e.title,
576            Item::Artist(a) => &a.name,
577            Item::Album(a) => &a.title,
578            Item::Track(t) => &t.title,
579        }
580    }
581
582    /// Its artwork, whatever kind it is.
583    pub fn artwork(&self) -> &[Artwork] {
584        match self {
585            Item::Movie(m) => &m.artwork,
586            Item::Show(s) => &s.artwork,
587            Item::Season(s) => &s.artwork,
588            Item::Episode(e) => &e.artwork,
589            Item::Artist(a) => &a.artwork,
590            Item::Album(a) => &a.artwork,
591            Item::Track(t) => &t.artwork,
592        }
593    }
594
595    /// Its first artwork of `kind`: what a row or a page shows.
596    pub fn artwork_of(&self, kind: ArtworkKind) -> Option<&Artwork> {
597        self.artwork().iter().find(|a| a.kind == kind)
598    }
599
600    /// The user's progress on a film, an episode or a track; `None` for
601    /// the kinds that do not play themselves.
602    pub fn playback(&self) -> Option<&PlaybackState> {
603        match self {
604            Item::Movie(m) => Some(&m.playback),
605            Item::Episode(e) => Some(&e.playback),
606            Item::Track(t) => Some(&t.playback),
607            _ => None,
608        }
609    }
610
611    /// The user watched it (or played it to its end).
612    pub fn is_watched(&self) -> bool {
613        self.playback().is_some_and(|p| p.watched)
614    }
615
616    /// Where the user stopped in it, watched or not.
617    pub fn resume_position(&self) -> Option<Duration> {
618        self.playback().and_then(|p| p.position)
619    }
620
621    /// Where a Play goes on from ([`PlaybackState::resume_from`]).
622    pub fn resume_from(&self) -> Option<Duration> {
623        self.playback().and_then(PlaybackState::resume_from)
624    }
625
626    /// How far through it the user is ([`PlaybackState::progress`]);
627    /// `None` for the kinds that do not play themselves.
628    pub fn progress(&self) -> Option<Progress> {
629        Some(self.playback()?.progress(self.duration()))
630    }
631}
632
633#[cfg(test)]
634mod tests {
635    use std::fmt::Debug;
636    use std::time::UNIX_EPOCH;
637
638    use serde::de::DeserializeOwned;
639
640    use super::*;
641    use crate::id::{MediaKind, Namespace};
642
643    fn round_trip<T: Serialize + DeserializeOwned + PartialEq + Debug>(value: T) {
644        let json = serde_json::to_string(&value).unwrap();
645        assert_eq!(serde_json::from_str::<T>(&json).unwrap(), value, "{json}");
646    }
647
648    fn media(kind: MediaKind, key: &str) -> MediaId {
649        MediaId::new(Namespace::Plex, kind, key).unwrap()
650    }
651
652    fn poster() -> Vec<Artwork> {
653        vec![Artwork {
654            id: ArtworkId::new(Namespace::Plex, "/library/metadata/1/thumb/9").unwrap(),
655            kind: ArtworkKind::Poster,
656        }]
657    }
658
659    fn halfway() -> PlaybackState {
660        PlaybackState {
661            position: Some(Duration::from_millis(2_220_500)),
662            watched: false,
663            last_viewed_at: None,
664            play_count: 0,
665            last_played_at: None,
666        }
667    }
668
669    fn ripley() -> CastMember {
670        CastMember {
671            id: PersonId::new(Namespace::Plex, "actor-13").unwrap(),
672            name: "Sigourney Weaver".into(),
673            role: PersonRole::Actor,
674            character: Some("Ellen Ripley".into()),
675            photo: Some(ArtworkId::new(Namespace::Plex, "/people/1/a/b.jpg").unwrap()),
676        }
677    }
678
679    fn scott() -> CastMember {
680        CastMember {
681            id: PersonId::new(Namespace::Plex, "director-7").unwrap(),
682            name: "Ridley Scott".into(),
683            role: PersonRole::Director,
684            character: None,
685            photo: None,
686        }
687    }
688
689    #[test]
690    fn a_cast_member_is_their_person_id_role_and_photo_on_the_wire() {
691        assert_eq!(
692            serde_json::to_value(ripley()).unwrap(),
693            serde_json::json!({
694                "id": "plex:actor-13",
695                "name": "Sigourney Weaver",
696                "role": "actor",
697                "character": "Ellen Ripley",
698                "photo": "plex:/people/1/a/b.jpg",
699            })
700        );
701        round_trip(ripley());
702        round_trip(scott());
703    }
704
705    /// A new type, so every field is sent (PX-15): `null` for none.
706    #[test]
707    fn a_cast_member_s_character_and_photo_are_required() {
708        crate::test_support::assert_each_required(&scott(), &["character", "photo"]);
709    }
710
711    /// `cast`, `release_date` and `last_aired` came without a revision
712    /// bump: a server from before them leaves them out.
713    #[test]
714    fn items_from_a_server_without_cast_or_dates_still_decode() {
715        let movie = Movie {
716            id: media(MediaKind::Movie, "10"),
717            title: "Alien".into(),
718            year: Some(1979),
719            release_date: CalendarDate::new(1979, 5, 25),
720            summary: None,
721            content_rating: None,
722            duration: None,
723            cast: vec![ripley()],
724            artwork: Vec::new(),
725            playback: PlaybackState::default(),
726        };
727        let mut json = serde_json::to_value(&movie).unwrap();
728        assert_eq!(json["release_date"], "1979-05-25");
729        let object = json.as_object_mut().unwrap();
730        object.remove("release_date");
731        object.remove("cast");
732        let older: Movie = serde_json::from_value(json).unwrap();
733        assert_eq!((older.release_date, older.cast), (None, Vec::new()));
734
735        let show = Show {
736            id: media(MediaKind::Show, "20"),
737            title: "The Expanse".into(),
738            year: Some(2015),
739            summary: None,
740            content_rating: None,
741            season_count: None,
742            genres: Vec::new(),
743            last_aired: CalendarDate::new(2022, 4, 8),
744            cast: vec![ripley()],
745            artwork: Vec::new(),
746        };
747        let mut json = serde_json::to_value(&show).unwrap();
748        assert_eq!(json["last_aired"], "2022-04-08");
749        let object = json.as_object_mut().unwrap();
750        object.remove("last_aired");
751        object.remove("cast");
752        let older: Show = serde_json::from_value(json).unwrap();
753        assert_eq!((older.last_aired, older.cast), (None, Vec::new()));
754
755        let episode = Episode {
756            id: media(MediaKind::Episode, "22"),
757            show_id: media(MediaKind::Show, "20"),
758            show_title: None,
759            season_id: media(MediaKind::Season, "21"),
760            season: 1,
761            episode: 1,
762            title: "Dulcinea".into(),
763            summary: None,
764            content_rating: None,
765            year: None,
766            air_date: None,
767            duration: None,
768            cast: vec![scott()],
769            artwork: Vec::new(),
770            playback: PlaybackState::default(),
771        };
772        let mut json = serde_json::to_value(&episode).unwrap();
773        json.as_object_mut().unwrap().remove("cast");
774        let older: Episode = serde_json::from_value(json).unwrap();
775        assert_eq!(older.cast, Vec::new());
776    }
777
778    #[test]
779    fn a_track_s_format_is_plain_numbers_on_the_wire() {
780        let track = Track {
781            id: media(MediaKind::Track, "224630"),
782            album_id: media(MediaKind::Album, "224629"),
783            artist_id: media(MediaKind::Artist, "224303"),
784            artist_name: None,
785            album_title: None,
786            title: "Catch".into(),
787            track: Some(1),
788            disc: Some(1),
789            album_track_count: Some(3),
790            codec: Some(AudioCodec::Flac),
791            bit_depth: Some(24),
792            sample_rate: Some(96_000),
793            duration: None,
794            artwork: Vec::new(),
795            playback: PlaybackState::default(),
796        };
797        let json = serde_json::to_value(&track).unwrap();
798        assert_eq!(
799            (
800                &json["codec"],
801                &json["bit_depth"],
802                &json["sample_rate"],
803                &json["album_track_count"]
804            ),
805            (
806                &serde_json::json!("flac"),
807                &serde_json::json!(24),
808                &serde_json::json!(96_000),
809                &serde_json::json!(3)
810            )
811        );
812    }
813
814    #[test]
815    fn library_kinds_are_snake_case_on_the_wire() {
816        assert_eq!(
817            serde_json::to_string(&LibraryKind::Movies).unwrap(),
818            r#""movies""#
819        );
820    }
821
822    #[test]
823    fn an_item_carries_its_kind_on_the_wire() {
824        let item = Item::Show(Show {
825            id: media(MediaKind::Show, "20"),
826            title: "The Expanse".into(),
827            year: None,
828            summary: None,
829            content_rating: None,
830            season_count: None,
831            genres: Vec::new(),
832            last_aired: None,
833            cast: Vec::new(),
834            artwork: Vec::new(),
835        });
836        let json = serde_json::to_value(&item).unwrap();
837        assert_eq!(json["kind"], "show");
838        assert_eq!(json["id"], "plex:show:20");
839        round_trip(item);
840    }
841
842    /// The parent's name on a season, an episode and an album was once
843    /// `serde(default)`; every field is now required (PX-15).
844    #[test]
845    fn a_parent_s_name_left_out_is_refused() {
846        let season = Season {
847            id: media(MediaKind::Season, "21"),
848            show_id: media(MediaKind::Show, "20"),
849            show_title: None,
850            season: 1,
851            title: "Season 1".into(),
852            artwork: Vec::new(),
853        };
854        crate::test_support::assert_each_required(&season, &["show_title"]);
855        let episode = Episode {
856            id: media(MediaKind::Episode, "22"),
857            show_id: media(MediaKind::Show, "20"),
858            show_title: None,
859            season_id: media(MediaKind::Season, "21"),
860            season: 1,
861            episode: 1,
862            title: "Dulcinea".into(),
863            summary: None,
864            content_rating: None,
865            year: None,
866            air_date: None,
867            duration: None,
868            cast: Vec::new(),
869            artwork: Vec::new(),
870            playback: PlaybackState::default(),
871        };
872        crate::test_support::assert_each_required(&episode, &["show_title"]);
873        let album = Album {
874            id: media(MediaKind::Album, "30"),
875            artist_id: media(MediaKind::Artist, "31"),
876            artist_name: None,
877            title: "Moon Safari".into(),
878            year: None,
879            track_count: None,
880            artwork: Vec::new(),
881        };
882        crate::test_support::assert_each_required(&album, &["artist_name"]);
883        // `null` is how none is sent.
884        round_trip(album);
885    }
886
887    #[test]
888    fn an_episode_from_a_server_without_air_dates_still_decodes() {
889        let episode = Episode {
890            id: media(MediaKind::Episode, "22"),
891            show_id: media(MediaKind::Show, "20"),
892            show_title: None,
893            season_id: media(MediaKind::Season, "21"),
894            season: 1,
895            episode: 1,
896            title: "Dulcinea".into(),
897            summary: None,
898            content_rating: None,
899            year: Some(2015),
900            air_date: CalendarDate::new(2015, 11, 23),
901            duration: None,
902            cast: Vec::new(),
903            artwork: Vec::new(),
904            playback: PlaybackState::default(),
905        };
906        let mut json = serde_json::to_value(&episode).unwrap();
907        assert_eq!(json["air_date"], "2015-11-23");
908        let object = json.as_object_mut().unwrap();
909        object.remove("year");
910        object.remove("air_date");
911        let older: Episode = serde_json::from_value(json).unwrap();
912        assert_eq!((older.year, older.air_date), (None, None));
913    }
914
915    /// "Today" for a show's years: 14 October 2026.
916    fn years(year: Option<u16>, last_aired: Option<(u16, u8, u8)>) -> Option<String> {
917        let show = Show {
918            id: media(MediaKind::Show, "20"),
919            title: "Andor".into(),
920            year,
921            summary: None,
922            content_rating: None,
923            season_count: None,
924            genres: Vec::new(),
925            last_aired: last_aired.and_then(|(y, m, d)| CalendarDate::new(y, m, d)),
926            cast: Vec::new(),
927            artwork: Vec::new(),
928        };
929        show.years_label(CalendarDate::new(2026, 10, 14).unwrap())
930    }
931
932    #[test]
933    fn a_show_s_years_come_in_parts() {
934        let show = |last: (u16, u8, u8)| Show {
935            id: media(MediaKind::Show, "20"),
936            title: "Andor".into(),
937            year: Some(2022),
938            summary: None,
939            content_rating: None,
940            season_count: None,
941            genres: Vec::new(),
942            last_aired: CalendarDate::new(last.0, last.1, last.2),
943            cast: Vec::new(),
944            artwork: Vec::new(),
945        };
946        let today = CalendarDate::new(2026, 10, 14).unwrap();
947        assert_eq!(
948            show((2025, 10, 14)).year_range(today),
949            Some(YearsAired::Running(2022))
950        );
951        assert_eq!(
952            show((2025, 10, 13)).year_range(today),
953            Some(YearsAired::Between(2022, 2025))
954        );
955        assert_eq!(
956            Item::Show(show((2022, 5, 1))).caption_parts(today),
957            Some(Caption::Years(YearsAired::One(2022)))
958        );
959    }
960
961    #[test]
962    fn a_show_with_no_air_date_shows_its_first_year() {
963        assert_eq!(years(Some(2022), None), Some("2022".into()));
964        assert_eq!(years(None, None), None);
965    }
966
967    #[test]
968    fn a_show_last_aired_in_its_first_year_shows_that_year() {
969        assert_eq!(years(Some(2022), Some((2022, 12, 1))), Some("2022".into()));
970    }
971
972    #[test]
973    fn a_show_aired_in_the_last_twelve_months_is_an_open_range() {
974        assert_eq!(
975            years(Some(2022), Some((2025, 10, 14))),
976            Some("2022\u{2013}".into())
977        );
978    }
979
980    #[test]
981    fn a_show_last_aired_over_a_year_ago_shows_both_years() {
982        assert_eq!(
983            years(Some(2022), Some((2025, 10, 13))),
984            Some("2022\u{2013}2025".into())
985        );
986    }
987
988    #[test]
989    fn a_show_with_no_first_year_shows_when_it_last_aired() {
990        assert_eq!(years(None, Some((2019, 3, 2))), Some("2019".into()));
991    }
992
993    #[test]
994    fn every_model_type_round_trips() {
995        round_trip(Library {
996            id: LibraryId::new(Namespace::Plex, "1").unwrap(),
997            title: "Movies".into(),
998            kind: LibraryKind::Movies,
999            server: None,
1000        });
1001        round_trip(Movie {
1002            id: media(MediaKind::Movie, "10"),
1003            title: "Alien".into(),
1004            year: Some(1979),
1005            release_date: CalendarDate::new(1979, 5, 25),
1006            summary: Some("In space no one can hear you scream.".into()),
1007            content_rating: Some("R".into()),
1008            duration: Some(Duration::from_secs(7020)),
1009            cast: vec![ripley(), scott()],
1010            artwork: poster(),
1011            playback: halfway(),
1012        });
1013        round_trip(Show {
1014            id: media(MediaKind::Show, "20"),
1015            title: "The Expanse".into(),
1016            year: Some(2015),
1017            summary: None,
1018            content_rating: Some("TV-14".into()),
1019            season_count: Some(6),
1020            genres: vec!["Science Fiction".into(), "Drama".into()],
1021            last_aired: CalendarDate::new(2022, 4, 8),
1022            cast: vec![ripley()],
1023            artwork: poster(),
1024        });
1025        round_trip(Season {
1026            id: media(MediaKind::Season, "21"),
1027            show_id: media(MediaKind::Show, "20"),
1028            show_title: Some("The Expanse".into()),
1029            season: 1,
1030            title: "Season 1".into(),
1031            artwork: Vec::new(),
1032        });
1033        round_trip(Episode {
1034            id: media(MediaKind::Episode, "22"),
1035            show_id: media(MediaKind::Show, "20"),
1036            show_title: Some("The Expanse".into()),
1037            season_id: media(MediaKind::Season, "21"),
1038            season: 1,
1039            episode: 1,
1040            title: "Dulcinea".into(),
1041            summary: None,
1042            content_rating: Some("TV-14".into()),
1043            year: Some(2015),
1044            air_date: CalendarDate::new(2015, 11, 23),
1045            duration: Some(Duration::from_secs(2640)),
1046            cast: vec![scott()],
1047            artwork: poster(),
1048            playback: PlaybackState::default(),
1049        });
1050        round_trip(Artist {
1051            id: media(MediaKind::Artist, "30"),
1052            name: "Boards of Canada".into(),
1053            summary: None,
1054            artwork: poster(),
1055        });
1056        round_trip(Album {
1057            id: media(MediaKind::Album, "31"),
1058            artist_id: media(MediaKind::Artist, "30"),
1059            artist_name: Some("Boards of Canada".into()),
1060            title: "Music Has the Right to Children".into(),
1061            year: Some(1998),
1062            track_count: Some(18),
1063            artwork: poster(),
1064        });
1065        round_trip(Track {
1066            id: media(MediaKind::Track, "32"),
1067            album_id: media(MediaKind::Album, "31"),
1068            artist_id: media(MediaKind::Artist, "30"),
1069            artist_name: Some("Boards of Canada".into()),
1070            album_title: Some("Music Has the Right to Children".into()),
1071            title: "Roygbiv".into(),
1072            track: Some(10),
1073            disc: Some(1),
1074            album_track_count: Some(18),
1075            codec: Some(AudioCodec::Flac),
1076            bit_depth: Some(16),
1077            sample_rate: Some(44_100),
1078            duration: Some(Duration::from_secs(151)),
1079            artwork: poster(),
1080            playback: PlaybackState {
1081                position: None,
1082                watched: true,
1083                last_viewed_at: None,
1084                play_count: 0,
1085                last_played_at: None,
1086            },
1087        });
1088    }
1089
1090    fn alien(playback: PlaybackState, duration: Option<Duration>) -> Item {
1091        Item::Movie(Movie {
1092            id: media(MediaKind::Movie, "10"),
1093            title: "Alien".into(),
1094            year: Some(1979),
1095            release_date: None,
1096            summary: None,
1097            content_rating: None,
1098            duration,
1099            cast: Vec::new(),
1100            artwork: Vec::new(),
1101            playback,
1102        })
1103    }
1104
1105    /// Markers and watch times keep their wire names and units: `_ms`
1106    /// spans, a position in whole milliseconds (`null` unstarted) and Unix
1107    /// seconds.
1108    #[test]
1109    fn markers_and_watch_times_keep_their_wire_form() {
1110        let marker = Marker {
1111            kind: MarkerKind::Intro,
1112            start: Duration::from_millis(258_865),
1113            end: Duration::from_millis(319_865),
1114            to_end: false,
1115        };
1116        let state = PlaybackState {
1117            last_viewed_at: Some(UNIX_EPOCH + Duration::from_secs(1_761_700_000)),
1118            play_count: 2,
1119            last_played_at: Some(UNIX_EPOCH + Duration::from_secs(1_761_600_000)),
1120            ..PlaybackState::default()
1121        };
1122        assert_eq!(
1123            (
1124                serde_json::to_value(marker).unwrap(),
1125                serde_json::to_value(&state).unwrap(),
1126                serde_json::to_value(halfway()).unwrap()["position"].clone(),
1127            ),
1128            (
1129                serde_json::json!({
1130                    "kind": "intro", "start_ms": 258_865, "end_ms": 319_865, "to_end": false
1131                }),
1132                serde_json::json!({
1133                    "position": null, "watched": false, "last_viewed_at": 1_761_700_000,
1134                    "play_count": 2, "last_played_at": 1_761_600_000
1135                }),
1136                serde_json::json!(2_220_500),
1137            )
1138        );
1139        round_trip(marker);
1140        round_trip(state);
1141    }
1142
1143    #[test]
1144    fn a_marker_list_leaves_out_kinds_this_build_does_not_know() {
1145        let listed: Markers = serde_json::from_value(serde_json::json!([
1146            { "kind": "recap", "start_ms": 0, "end_ms": 60_000, "to_end": false },
1147            { "kind": "intro", "start_ms": 60_000, "end_ms": 90_000, "to_end": false },
1148        ]))
1149        .unwrap();
1150        let intro = Marker {
1151            kind: MarkerKind::Intro,
1152            start: Duration::from_millis(60_000),
1153            end: Duration::from_millis(90_000),
1154            to_end: false,
1155        };
1156        assert_eq!(*listed, [intro]);
1157        assert_eq!(
1158            serde_json::to_value(&listed).unwrap()[0]["start_ms"],
1159            60_000
1160        );
1161    }
1162
1163    #[test]
1164    fn an_item_s_artwork_of_a_kind_is_its_first_one() {
1165        let art = |kind, path: &str| Artwork {
1166            id: ArtworkId::new(Namespace::Plex, path).unwrap(),
1167            kind,
1168        };
1169        let Item::Movie(mut movie) = alien(PlaybackState::default(), None) else {
1170            unreachable!()
1171        };
1172        movie.artwork = vec![
1173            art(ArtworkKind::Background, "/bg"),
1174            art(ArtworkKind::Poster, "/p1"),
1175            art(ArtworkKind::Poster, "/p2"),
1176        ];
1177        let item = Item::Movie(movie);
1178        assert_eq!(
1179            [
1180                ArtworkKind::Poster,
1181                ArtworkKind::Background,
1182                ArtworkKind::Thumb
1183            ]
1184            .map(|kind| item.artwork_of(kind).cloned()),
1185            [
1186                Some(art(ArtworkKind::Poster, "/p1")),
1187                Some(art(ArtworkKind::Background, "/bg")),
1188                None
1189            ]
1190        );
1191    }
1192
1193    fn at(secs: u64, watched: bool) -> PlaybackState {
1194        PlaybackState {
1195            position: Some(Duration::from_secs(secs)),
1196            watched,
1197            ..PlaybackState::default()
1198        }
1199    }
1200
1201    #[test]
1202    fn a_film_stopped_part_way_resumes_where_it_stopped() {
1203        assert_eq!(at(600, false).resume_from(), Some(Duration::from_secs(600)));
1204    }
1205
1206    #[test]
1207    fn a_watched_film_plays_from_the_start() {
1208        assert_eq!(at(600, true).resume_from(), None);
1209    }
1210
1211    #[test]
1212    fn a_film_never_begun_plays_from_the_start() {
1213        assert_eq!(PlaybackState::default().resume_from(), None);
1214        assert_eq!(at(0, false).resume_from(), None);
1215    }
1216
1217    #[test]
1218    fn progress_is_the_fraction_watched_and_the_time_left() {
1219        let progress = at(1_500, false).progress(Some(Duration::from_secs(6_000)));
1220        assert_eq!(
1221            progress,
1222            Progress {
1223                position: Duration::from_secs(1_500),
1224                remaining: Some(Duration::from_secs(4_500)),
1225                fraction: Some(0.25),
1226                watched: false,
1227            }
1228        );
1229    }
1230
1231    #[test]
1232    fn progress_past_the_length_is_whole_with_nothing_left() {
1233        let progress = at(7_000, true).progress(Some(Duration::from_secs(6_000)));
1234        assert_eq!(
1235            (progress.fraction, progress.remaining, progress.watched),
1236            (Some(1.0), Some(Duration::ZERO), true)
1237        );
1238    }
1239
1240    #[test]
1241    fn progress_with_no_length_has_no_fraction() {
1242        for length in [None, Some(Duration::ZERO)] {
1243            let progress = at(60, false).progress(length);
1244            assert_eq!((progress.fraction, progress.remaining), (None, None));
1245        }
1246    }
1247
1248    #[test]
1249    fn an_item_answers_from_its_own_playback() {
1250        let item = alien(at(600, false), Some(Duration::from_secs(1_200)));
1251        assert_eq!(item.title(), "Alien");
1252        assert!(!item.is_watched());
1253        assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
1254        assert_eq!(item.resume_from(), Some(Duration::from_secs(600)));
1255        assert_eq!(item.progress().and_then(|p| p.fraction), Some(0.5));
1256    }
1257
1258    #[test]
1259    fn a_watched_item_keeps_its_position_but_resumes_from_the_start() {
1260        let item = alien(at(600, true), None);
1261        assert!(item.is_watched());
1262        assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
1263        assert_eq!(item.resume_from(), None);
1264    }
1265
1266    #[test]
1267    fn an_artist_has_a_title_but_no_progress() {
1268        let show = Item::Artist(Artist {
1269            id: media(MediaKind::Artist, "30"),
1270            name: "Daft Punk".into(),
1271            summary: None,
1272            artwork: Vec::new(),
1273        });
1274        assert_eq!(show.title(), "Daft Punk");
1275        assert_eq!(show.progress(), None);
1276        assert!(!show.is_watched());
1277        assert_eq!(show.resume_from(), None);
1278    }
1279}