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