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;
8
9use serde::{Deserialize, Serialize};
10
11use crate::codec::AudioCodec;
12use crate::date::CalendarDate;
13use crate::duration_ms;
14use crate::id::{ArtworkId, LibraryId, MediaId, PersonId};
15use crate::search::PersonRole;
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 = "duration_ms::option")]
81    pub position: Option<Duration>,
82    pub watched: bool,
83    /// When the user last viewed it, Unix seconds: 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)]
92    pub last_viewed_at: Option<i64>,
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: the end of their
99    /// latest counted play. Filled where `play_count` is; `None` for an
100    /// item never played.
101    #[serde(default)]
102    pub last_played_at: Option<i64>,
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 = "duration_ms::option")]
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 = "duration_ms::option")]
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 = "duration_ms::option")]
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, in milliseconds from the start of the item.
359    pub start_ms: u64,
360    /// Where it ends. On a marker that runs to the end this may be a
361    /// little off the item's duration, either way: go by `to_end`.
362    pub end_ms: u64,
363    /// Nothing follows it: credits with no scene after them. The catalog
364    /// says so; it is never worked out from `end_ms` and the duration.
365    pub to_end: bool,
366}
367
368/// Any one item a catalog returns. On the wire it is the item's own object
369/// with a `kind` field added, for example `{"kind": "movie", "id": …}`.
370#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
371#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
372#[serde(tag = "kind", rename_all = "snake_case")]
373pub enum Item {
374    Movie(Movie),
375    Show(Show),
376    Season(Season),
377    Episode(Episode),
378    Artist(Artist),
379    Album(Album),
380    Track(Track),
381}
382
383/// The years a show ran, as its card says them.
384#[derive(Debug, Clone, Copy, PartialEq, Eq)]
385#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
386pub enum YearsAired {
387    /// "2019": it ran in one year, or only one is known.
388    One(u16),
389    /// "2019–": an episode aired in the last twelve months.
390    Running(u16),
391    /// "2019–2023".
392    Between(u16, u16),
393}
394
395/// "2019", "2019–", "2019–2023".
396impl std::fmt::Display for YearsAired {
397    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
398        match self {
399            YearsAired::One(year) => write!(f, "{year}"),
400            YearsAired::Running(first) => write!(f, "{first}\u{2013}"),
401            YearsAired::Between(first, last) => write!(f, "{first}\u{2013}{last}"),
402        }
403    }
404}
405
406impl Show {
407    /// The years it ran, from its first year and the day its latest
408    /// episode aired: one year when that was the same year, running when
409    /// it aired in the twelve months up to `today`, else both years. With
410    /// no first year, the latest episode's year alone; `None` with
411    /// neither.
412    pub fn year_range(&self, today: CalendarDate) -> Option<YearsAired> {
413        let Some(last) = self.last_aired else {
414            return self.year.map(YearsAired::One);
415        };
416        let Some(first) = self.year else {
417            return Some(YearsAired::One(last.year()));
418        };
419        if last.year() <= first {
420            return Some(YearsAired::One(first));
421        }
422        // A year back from today, compared field by field: most years have
423        // no 29 February to land on.
424        let year_ago = (today.year() - 1, today.month(), today.day());
425        if (last.year(), last.month(), last.day()) >= year_ago {
426            Some(YearsAired::Running(first))
427        } else {
428            Some(YearsAired::Between(first, last.year()))
429        }
430    }
431
432    /// [`Show::year_range`] as text: "2019", "2019–", "2019–2023".
433    pub fn years_label(&self, today: CalendarDate) -> Option<String> {
434        self.year_range(today).map(|years| years.to_string())
435    }
436}
437
438/// The line under a card's title, in parts.
439#[derive(Debug, Clone, PartialEq, Eq)]
440#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
441pub enum Caption {
442    /// A film's year.
443    Year(u16),
444    /// A show's years.
445    Years(YearsAired),
446    /// A season's show.
447    Show(String),
448    /// An episode: its show, and where it is in it ("S2 · E5").
449    Episode {
450        show: Option<String>,
451        season: u32,
452        episode: u32,
453    },
454    /// An album's artist and year.
455    Album {
456        artist: Option<String>,
457        year: Option<u16>,
458    },
459    /// A track's length.
460    Length(Duration),
461}
462
463impl Item {
464    /// What a card says under its title on `today`; `None` for an artist
465    /// or where nothing is known.
466    pub fn caption_parts(&self, today: CalendarDate) -> Option<Caption> {
467        match self {
468            Item::Movie(m) => m.year.map(Caption::Year),
469            Item::Show(s) => s.year_range(today).map(Caption::Years),
470            Item::Season(s) => s.show_title.clone().map(Caption::Show),
471            Item::Episode(e) => Some(Caption::Episode {
472                show: e.show_title.clone(),
473                season: e.season,
474                episode: e.episode,
475            }),
476            Item::Album(a) => {
477                (a.artist_name.is_some() || a.year.is_some()).then(|| Caption::Album {
478                    artist: a.artist_name.clone(),
479                    year: a.year,
480                })
481            }
482            Item::Track(t) => t.duration.map(Caption::Length),
483            Item::Artist(_) => None,
484        }
485    }
486
487    pub fn id(&self) -> &MediaId {
488        match self {
489            Item::Movie(m) => &m.id,
490            Item::Show(s) => &s.id,
491            Item::Season(s) => &s.id,
492            Item::Episode(e) => &e.id,
493            Item::Artist(a) => &a.id,
494            Item::Album(a) => &a.id,
495            Item::Track(t) => &t.id,
496        }
497    }
498
499    /// Its own name: a film's, an episode's or a track's title; an
500    /// artist's name.
501    pub fn title(&self) -> &str {
502        match self {
503            Item::Movie(m) => &m.title,
504            Item::Show(s) => &s.title,
505            Item::Season(s) => &s.title,
506            Item::Episode(e) => &e.title,
507            Item::Artist(a) => &a.name,
508            Item::Album(a) => &a.title,
509            Item::Track(t) => &t.title,
510        }
511    }
512
513    /// The user's progress on a film, an episode or a track; `None` for
514    /// the kinds that do not play themselves.
515    pub fn playback(&self) -> Option<&PlaybackState> {
516        match self {
517            Item::Movie(m) => Some(&m.playback),
518            Item::Episode(e) => Some(&e.playback),
519            Item::Track(t) => Some(&t.playback),
520            _ => None,
521        }
522    }
523
524    /// Its length, for the kinds that play.
525    pub fn duration(&self) -> Option<Duration> {
526        match self {
527            Item::Movie(m) => m.duration,
528            Item::Episode(e) => e.duration,
529            Item::Track(t) => t.duration,
530            _ => None,
531        }
532    }
533
534    /// The user watched it (or played it to its end).
535    pub fn is_watched(&self) -> bool {
536        self.playback().is_some_and(|p| p.watched)
537    }
538
539    /// Where the user stopped in it, watched or not.
540    pub fn resume_position(&self) -> Option<Duration> {
541        self.playback().and_then(|p| p.position)
542    }
543
544    /// Where a Play goes on from ([`PlaybackState::resume_from`]).
545    pub fn resume_from(&self) -> Option<Duration> {
546        self.playback().and_then(PlaybackState::resume_from)
547    }
548
549    /// How far through it the user is ([`PlaybackState::progress`]);
550    /// `None` for the kinds that do not play themselves.
551    pub fn progress(&self) -> Option<Progress> {
552        Some(self.playback()?.progress(self.duration()))
553    }
554}
555
556#[cfg(test)]
557mod tests {
558    use std::fmt::Debug;
559
560    use serde::de::DeserializeOwned;
561
562    use super::*;
563    use crate::id::{MediaKind, Namespace};
564
565    fn round_trip<T: Serialize + DeserializeOwned + PartialEq + Debug>(value: T) {
566        let json = serde_json::to_string(&value).unwrap();
567        assert_eq!(serde_json::from_str::<T>(&json).unwrap(), value, "{json}");
568    }
569
570    fn media(kind: MediaKind, key: &str) -> MediaId {
571        MediaId::new(Namespace::Plex, kind, key).unwrap()
572    }
573
574    fn poster() -> Vec<Artwork> {
575        vec![Artwork {
576            id: ArtworkId::new(Namespace::Plex, "/library/metadata/1/thumb/9").unwrap(),
577            kind: ArtworkKind::Poster,
578        }]
579    }
580
581    fn halfway() -> PlaybackState {
582        PlaybackState {
583            position: Some(Duration::from_millis(2_220_500)),
584            watched: false,
585            last_viewed_at: None,
586            play_count: 0,
587            last_played_at: None,
588        }
589    }
590
591    fn ripley() -> CastMember {
592        CastMember {
593            id: PersonId::new(Namespace::Plex, "actor-13").unwrap(),
594            name: "Sigourney Weaver".into(),
595            role: PersonRole::Actor,
596            character: Some("Ellen Ripley".into()),
597            photo: Some(ArtworkId::new(Namespace::Plex, "/people/1/a/b.jpg").unwrap()),
598        }
599    }
600
601    fn scott() -> CastMember {
602        CastMember {
603            id: PersonId::new(Namespace::Plex, "director-7").unwrap(),
604            name: "Ridley Scott".into(),
605            role: PersonRole::Director,
606            character: None,
607            photo: None,
608        }
609    }
610
611    #[test]
612    fn a_cast_member_is_their_person_id_role_and_photo_on_the_wire() {
613        assert_eq!(
614            serde_json::to_value(ripley()).unwrap(),
615            serde_json::json!({
616                "id": "plex:actor-13",
617                "name": "Sigourney Weaver",
618                "role": "actor",
619                "character": "Ellen Ripley",
620                "photo": "plex:/people/1/a/b.jpg",
621            })
622        );
623        round_trip(ripley());
624        round_trip(scott());
625    }
626
627    /// A new type, so every field is sent (PX-15): `null` for none.
628    #[test]
629    fn a_cast_member_s_character_and_photo_are_required() {
630        crate::test_support::assert_each_required(&scott(), &["character", "photo"]);
631    }
632
633    /// `cast`, `release_date` and `last_aired` came without a revision
634    /// bump: a server from before them leaves them out.
635    #[test]
636    fn items_from_a_server_without_cast_or_dates_still_decode() {
637        let movie = Movie {
638            id: media(MediaKind::Movie, "10"),
639            title: "Alien".into(),
640            year: Some(1979),
641            release_date: CalendarDate::new(1979, 5, 25),
642            summary: None,
643            content_rating: None,
644            duration: None,
645            cast: vec![ripley()],
646            artwork: Vec::new(),
647            playback: PlaybackState::default(),
648        };
649        let mut json = serde_json::to_value(&movie).unwrap();
650        assert_eq!(json["release_date"], "1979-05-25");
651        let object = json.as_object_mut().unwrap();
652        object.remove("release_date");
653        object.remove("cast");
654        let older: Movie = serde_json::from_value(json).unwrap();
655        assert_eq!((older.release_date, older.cast), (None, Vec::new()));
656
657        let show = Show {
658            id: media(MediaKind::Show, "20"),
659            title: "The Expanse".into(),
660            year: Some(2015),
661            summary: None,
662            content_rating: None,
663            season_count: None,
664            genres: Vec::new(),
665            last_aired: CalendarDate::new(2022, 4, 8),
666            cast: vec![ripley()],
667            artwork: Vec::new(),
668        };
669        let mut json = serde_json::to_value(&show).unwrap();
670        assert_eq!(json["last_aired"], "2022-04-08");
671        let object = json.as_object_mut().unwrap();
672        object.remove("last_aired");
673        object.remove("cast");
674        let older: Show = serde_json::from_value(json).unwrap();
675        assert_eq!((older.last_aired, older.cast), (None, Vec::new()));
676
677        let episode = Episode {
678            id: media(MediaKind::Episode, "22"),
679            show_id: media(MediaKind::Show, "20"),
680            show_title: None,
681            season_id: media(MediaKind::Season, "21"),
682            season: 1,
683            episode: 1,
684            title: "Dulcinea".into(),
685            summary: None,
686            content_rating: None,
687            year: None,
688            air_date: None,
689            duration: None,
690            cast: vec![scott()],
691            artwork: Vec::new(),
692            playback: PlaybackState::default(),
693        };
694        let mut json = serde_json::to_value(&episode).unwrap();
695        json.as_object_mut().unwrap().remove("cast");
696        let older: Episode = serde_json::from_value(json).unwrap();
697        assert_eq!(older.cast, Vec::new());
698    }
699
700    #[test]
701    fn durations_are_whole_milliseconds_on_the_wire() {
702        let json = serde_json::to_value(halfway()).unwrap();
703        assert_eq!(json["position"], 2_220_500);
704    }
705
706    #[test]
707    fn an_unstarted_item_has_a_null_position() {
708        let json = serde_json::to_value(PlaybackState::default()).unwrap();
709        assert!(json["position"].is_null());
710    }
711
712    #[test]
713    fn a_track_s_format_is_plain_numbers_on_the_wire() {
714        let track = Track {
715            id: media(MediaKind::Track, "224630"),
716            album_id: media(MediaKind::Album, "224629"),
717            artist_id: media(MediaKind::Artist, "224303"),
718            artist_name: None,
719            album_title: None,
720            title: "Catch".into(),
721            track: Some(1),
722            disc: Some(1),
723            album_track_count: Some(3),
724            codec: Some(AudioCodec::Flac),
725            bit_depth: Some(24),
726            sample_rate: Some(96_000),
727            duration: None,
728            artwork: Vec::new(),
729            playback: PlaybackState::default(),
730        };
731        let json = serde_json::to_value(&track).unwrap();
732        assert_eq!(
733            (
734                &json["codec"],
735                &json["bit_depth"],
736                &json["sample_rate"],
737                &json["album_track_count"]
738            ),
739            (
740                &serde_json::json!("flac"),
741                &serde_json::json!(24),
742                &serde_json::json!(96_000),
743                &serde_json::json!(3)
744            )
745        );
746    }
747
748    #[test]
749    fn library_kinds_are_snake_case_on_the_wire() {
750        assert_eq!(
751            serde_json::to_string(&LibraryKind::Movies).unwrap(),
752            r#""movies""#
753        );
754    }
755
756    #[test]
757    fn a_marker_is_milliseconds_and_a_snake_case_kind_on_the_wire() {
758        let marker = Marker {
759            kind: MarkerKind::Credits,
760            start_ms: 2_662_962,
761            end_ms: 2_709_958,
762            to_end: true,
763        };
764        assert_eq!(
765            serde_json::to_value(marker).unwrap(),
766            serde_json::json!({
767                "kind": "credits",
768                "start_ms": 2_662_962,
769                "end_ms": 2_709_958,
770                "to_end": true,
771            })
772        );
773        round_trip(marker);
774    }
775
776    #[test]
777    fn a_marker_kind_from_a_newer_server_is_unknown() {
778        let marker: Marker = serde_json::from_str(
779            r#"{"kind": "recap", "start_ms": 0, "end_ms": 30000, "to_end": false}"#,
780        )
781        .unwrap();
782        assert_eq!(marker.kind, MarkerKind::Unknown);
783    }
784
785    #[test]
786    fn an_item_carries_its_kind_on_the_wire() {
787        let item = Item::Show(Show {
788            id: media(MediaKind::Show, "20"),
789            title: "The Expanse".into(),
790            year: None,
791            summary: None,
792            content_rating: None,
793            season_count: None,
794            genres: Vec::new(),
795            last_aired: None,
796            cast: Vec::new(),
797            artwork: Vec::new(),
798        });
799        let json = serde_json::to_value(&item).unwrap();
800        assert_eq!(json["kind"], "show");
801        assert_eq!(json["id"], "plex:show:20");
802        round_trip(item);
803    }
804
805    /// The parent's name on a season, an episode and an album was once
806    /// `serde(default)`; every field is now required (PX-15).
807    #[test]
808    fn a_parent_s_name_left_out_is_refused() {
809        let season = Season {
810            id: media(MediaKind::Season, "21"),
811            show_id: media(MediaKind::Show, "20"),
812            show_title: None,
813            season: 1,
814            title: "Season 1".into(),
815            artwork: Vec::new(),
816        };
817        crate::test_support::assert_each_required(&season, &["show_title"]);
818        let episode = Episode {
819            id: media(MediaKind::Episode, "22"),
820            show_id: media(MediaKind::Show, "20"),
821            show_title: None,
822            season_id: media(MediaKind::Season, "21"),
823            season: 1,
824            episode: 1,
825            title: "Dulcinea".into(),
826            summary: None,
827            content_rating: None,
828            year: None,
829            air_date: None,
830            duration: None,
831            cast: Vec::new(),
832            artwork: Vec::new(),
833            playback: PlaybackState::default(),
834        };
835        crate::test_support::assert_each_required(&episode, &["show_title"]);
836        let album = Album {
837            id: media(MediaKind::Album, "30"),
838            artist_id: media(MediaKind::Artist, "31"),
839            artist_name: None,
840            title: "Moon Safari".into(),
841            year: None,
842            track_count: None,
843            artwork: Vec::new(),
844        };
845        crate::test_support::assert_each_required(&album, &["artist_name"]);
846        // `null` is how none is sent.
847        round_trip(album);
848    }
849
850    #[test]
851    fn an_episode_from_a_server_without_air_dates_still_decodes() {
852        let episode = Episode {
853            id: media(MediaKind::Episode, "22"),
854            show_id: media(MediaKind::Show, "20"),
855            show_title: None,
856            season_id: media(MediaKind::Season, "21"),
857            season: 1,
858            episode: 1,
859            title: "Dulcinea".into(),
860            summary: None,
861            content_rating: None,
862            year: Some(2015),
863            air_date: CalendarDate::new(2015, 11, 23),
864            duration: None,
865            cast: Vec::new(),
866            artwork: Vec::new(),
867            playback: PlaybackState::default(),
868        };
869        let mut json = serde_json::to_value(&episode).unwrap();
870        assert_eq!(json["air_date"], "2015-11-23");
871        let object = json.as_object_mut().unwrap();
872        object.remove("year");
873        object.remove("air_date");
874        let older: Episode = serde_json::from_value(json).unwrap();
875        assert_eq!((older.year, older.air_date), (None, None));
876    }
877
878    /// "Today" for a show's years: 14 October 2026.
879    fn years(year: Option<u16>, last_aired: Option<(u16, u8, u8)>) -> Option<String> {
880        let show = Show {
881            id: media(MediaKind::Show, "20"),
882            title: "Andor".into(),
883            year,
884            summary: None,
885            content_rating: None,
886            season_count: None,
887            genres: Vec::new(),
888            last_aired: last_aired.and_then(|(y, m, d)| CalendarDate::new(y, m, d)),
889            cast: Vec::new(),
890            artwork: Vec::new(),
891        };
892        show.years_label(CalendarDate::new(2026, 10, 14).unwrap())
893    }
894
895    #[test]
896    fn a_show_s_years_come_in_parts() {
897        let show = |last: (u16, u8, u8)| Show {
898            id: media(MediaKind::Show, "20"),
899            title: "Andor".into(),
900            year: Some(2022),
901            summary: None,
902            content_rating: None,
903            season_count: None,
904            genres: Vec::new(),
905            last_aired: CalendarDate::new(last.0, last.1, last.2),
906            cast: Vec::new(),
907            artwork: Vec::new(),
908        };
909        let today = CalendarDate::new(2026, 10, 14).unwrap();
910        assert_eq!(
911            show((2025, 10, 14)).year_range(today),
912            Some(YearsAired::Running(2022))
913        );
914        assert_eq!(
915            show((2025, 10, 13)).year_range(today),
916            Some(YearsAired::Between(2022, 2025))
917        );
918        assert_eq!(
919            Item::Show(show((2022, 5, 1))).caption_parts(today),
920            Some(Caption::Years(YearsAired::One(2022)))
921        );
922    }
923
924    #[test]
925    fn a_show_with_no_air_date_shows_its_first_year() {
926        assert_eq!(years(Some(2022), None), Some("2022".into()));
927        assert_eq!(years(None, None), None);
928    }
929
930    #[test]
931    fn a_show_last_aired_in_its_first_year_shows_that_year() {
932        assert_eq!(years(Some(2022), Some((2022, 12, 1))), Some("2022".into()));
933    }
934
935    #[test]
936    fn a_show_aired_in_the_last_twelve_months_is_an_open_range() {
937        assert_eq!(
938            years(Some(2022), Some((2025, 10, 14))),
939            Some("2022\u{2013}".into())
940        );
941    }
942
943    #[test]
944    fn a_show_last_aired_over_a_year_ago_shows_both_years() {
945        assert_eq!(
946            years(Some(2022), Some((2025, 10, 13))),
947            Some("2022\u{2013}2025".into())
948        );
949    }
950
951    #[test]
952    fn a_show_with_no_first_year_shows_when_it_last_aired() {
953        assert_eq!(years(None, Some((2019, 3, 2))), Some("2019".into()));
954    }
955
956    #[test]
957    fn every_model_type_round_trips() {
958        round_trip(Library {
959            id: LibraryId::new(Namespace::Plex, "1").unwrap(),
960            title: "Movies".into(),
961            kind: LibraryKind::Movies,
962            server: None,
963        });
964        round_trip(Movie {
965            id: media(MediaKind::Movie, "10"),
966            title: "Alien".into(),
967            year: Some(1979),
968            release_date: CalendarDate::new(1979, 5, 25),
969            summary: Some("In space no one can hear you scream.".into()),
970            content_rating: Some("R".into()),
971            duration: Some(Duration::from_secs(7020)),
972            cast: vec![ripley(), scott()],
973            artwork: poster(),
974            playback: halfway(),
975        });
976        round_trip(Show {
977            id: media(MediaKind::Show, "20"),
978            title: "The Expanse".into(),
979            year: Some(2015),
980            summary: None,
981            content_rating: Some("TV-14".into()),
982            season_count: Some(6),
983            genres: vec!["Science Fiction".into(), "Drama".into()],
984            last_aired: CalendarDate::new(2022, 4, 8),
985            cast: vec![ripley()],
986            artwork: poster(),
987        });
988        round_trip(Season {
989            id: media(MediaKind::Season, "21"),
990            show_id: media(MediaKind::Show, "20"),
991            show_title: Some("The Expanse".into()),
992            season: 1,
993            title: "Season 1".into(),
994            artwork: Vec::new(),
995        });
996        round_trip(Episode {
997            id: media(MediaKind::Episode, "22"),
998            show_id: media(MediaKind::Show, "20"),
999            show_title: Some("The Expanse".into()),
1000            season_id: media(MediaKind::Season, "21"),
1001            season: 1,
1002            episode: 1,
1003            title: "Dulcinea".into(),
1004            summary: None,
1005            content_rating: Some("TV-14".into()),
1006            year: Some(2015),
1007            air_date: CalendarDate::new(2015, 11, 23),
1008            duration: Some(Duration::from_secs(2640)),
1009            cast: vec![scott()],
1010            artwork: poster(),
1011            playback: PlaybackState::default(),
1012        });
1013        round_trip(Artist {
1014            id: media(MediaKind::Artist, "30"),
1015            name: "Boards of Canada".into(),
1016            summary: None,
1017            artwork: poster(),
1018        });
1019        round_trip(Album {
1020            id: media(MediaKind::Album, "31"),
1021            artist_id: media(MediaKind::Artist, "30"),
1022            artist_name: Some("Boards of Canada".into()),
1023            title: "Music Has the Right to Children".into(),
1024            year: Some(1998),
1025            track_count: Some(18),
1026            artwork: poster(),
1027        });
1028        round_trip(Track {
1029            id: media(MediaKind::Track, "32"),
1030            album_id: media(MediaKind::Album, "31"),
1031            artist_id: media(MediaKind::Artist, "30"),
1032            artist_name: Some("Boards of Canada".into()),
1033            album_title: Some("Music Has the Right to Children".into()),
1034            title: "Roygbiv".into(),
1035            track: Some(10),
1036            disc: Some(1),
1037            album_track_count: Some(18),
1038            codec: Some(AudioCodec::Flac),
1039            bit_depth: Some(16),
1040            sample_rate: Some(44_100),
1041            duration: Some(Duration::from_secs(151)),
1042            artwork: poster(),
1043            playback: PlaybackState {
1044                position: None,
1045                watched: true,
1046                last_viewed_at: None,
1047                play_count: 0,
1048                last_played_at: None,
1049            },
1050        });
1051    }
1052
1053    fn alien(playback: PlaybackState, duration: Option<Duration>) -> Item {
1054        Item::Movie(Movie {
1055            id: media(MediaKind::Movie, "10"),
1056            title: "Alien".into(),
1057            year: Some(1979),
1058            release_date: None,
1059            summary: None,
1060            content_rating: None,
1061            duration,
1062            cast: Vec::new(),
1063            artwork: Vec::new(),
1064            playback,
1065        })
1066    }
1067
1068    fn at(secs: u64, watched: bool) -> PlaybackState {
1069        PlaybackState {
1070            position: Some(Duration::from_secs(secs)),
1071            watched,
1072            ..PlaybackState::default()
1073        }
1074    }
1075
1076    #[test]
1077    fn a_film_stopped_part_way_resumes_where_it_stopped() {
1078        assert_eq!(at(600, false).resume_from(), Some(Duration::from_secs(600)));
1079    }
1080
1081    #[test]
1082    fn a_watched_film_plays_from_the_start() {
1083        assert_eq!(at(600, true).resume_from(), None);
1084    }
1085
1086    #[test]
1087    fn a_film_never_begun_plays_from_the_start() {
1088        assert_eq!(PlaybackState::default().resume_from(), None);
1089        assert_eq!(at(0, false).resume_from(), None);
1090    }
1091
1092    #[test]
1093    fn progress_is_the_fraction_watched_and_the_time_left() {
1094        let progress = at(1_500, false).progress(Some(Duration::from_secs(6_000)));
1095        assert_eq!(
1096            progress,
1097            Progress {
1098                position: Duration::from_secs(1_500),
1099                remaining: Some(Duration::from_secs(4_500)),
1100                fraction: Some(0.25),
1101                watched: false,
1102            }
1103        );
1104    }
1105
1106    #[test]
1107    fn progress_past_the_length_is_whole_with_nothing_left() {
1108        let progress = at(7_000, true).progress(Some(Duration::from_secs(6_000)));
1109        assert_eq!(
1110            (progress.fraction, progress.remaining, progress.watched),
1111            (Some(1.0), Some(Duration::ZERO), true)
1112        );
1113    }
1114
1115    #[test]
1116    fn progress_with_no_length_has_no_fraction() {
1117        for length in [None, Some(Duration::ZERO)] {
1118            let progress = at(60, false).progress(length);
1119            assert_eq!((progress.fraction, progress.remaining), (None, None));
1120        }
1121    }
1122
1123    #[test]
1124    fn an_item_answers_from_its_own_playback() {
1125        let item = alien(at(600, false), Some(Duration::from_secs(1_200)));
1126        assert_eq!(item.title(), "Alien");
1127        assert!(!item.is_watched());
1128        assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
1129        assert_eq!(item.resume_from(), Some(Duration::from_secs(600)));
1130        assert_eq!(item.progress().and_then(|p| p.fraction), Some(0.5));
1131    }
1132
1133    #[test]
1134    fn a_watched_item_keeps_its_position_but_resumes_from_the_start() {
1135        let item = alien(at(600, true), None);
1136        assert!(item.is_watched());
1137        assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
1138        assert_eq!(item.resume_from(), None);
1139    }
1140
1141    #[test]
1142    fn an_artist_has_a_title_but_no_progress() {
1143        let show = Item::Artist(Artist {
1144            id: media(MediaKind::Artist, "30"),
1145            name: "Daft Punk".into(),
1146            summary: None,
1147            artwork: Vec::new(),
1148        });
1149        assert_eq!(show.title(), "Daft Punk");
1150        assert_eq!(show.progress(), None);
1151        assert!(!show.is_watched());
1152        assert_eq!(show.resume_from(), None);
1153    }
1154}