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