1use 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#[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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
39 pub server: Option<LibraryServer>,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
45#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
46pub struct LibraryServer {
47 pub server_id: String,
49 pub name: String,
51 pub online: bool,
54}
55
56#[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#[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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
77#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
78pub struct PlaybackState {
79 #[serde(with = "serde_time::millis::option_required")]
81 pub position: Option<Duration>,
82 pub watched: bool,
83 #[serde(default, with = "serde_time::unix_seconds::option")]
92 pub last_viewed_at: Option<SystemTime>,
93 #[serde(default)]
97 pub play_count: u32,
98 #[serde(default, with = "serde_time::unix_seconds::option")]
102 pub last_played_at: Option<SystemTime>,
103}
104
105impl PlaybackState {
106 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 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#[derive(Debug, Clone, Copy, PartialEq)]
132pub struct Progress {
133 pub position: Duration,
135 pub remaining: Option<Duration>,
137 pub fraction: Option<f64>,
140 pub watched: bool,
141}
142
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
144#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
145pub struct Movie {
146 pub id: MediaId,
147 pub title: String,
148 pub year: Option<u16>,
150 pub release_date: Option<CalendarDate>,
156 pub summary: Option<String>,
157 pub content_rating: Option<String>,
160 #[serde(with = "serde_time::millis::option_required")]
161 pub duration: Option<Duration>,
162 #[serde(default)]
164 pub cast: Vec<CastMember>,
165 pub artwork: Vec<Artwork>,
166 pub playback: PlaybackState,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
170#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
171pub struct Show {
172 pub id: MediaId,
173 pub title: String,
174 pub year: Option<u16>,
175 pub summary: Option<String>,
176 pub content_rating: Option<String>,
179 pub season_count: Option<u32>,
182 pub genres: Vec<String>,
186 pub last_aired: Option<CalendarDate>,
197 #[serde(default)]
199 pub cast: Vec<CastMember>,
200 pub artwork: Vec<Artwork>,
201}
202
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
205pub struct Season {
206 pub id: MediaId,
207 pub show_id: MediaId,
208 #[serde(deserialize_with = "crate::required::option")]
210 pub show_title: Option<String>,
211 pub season: u32,
213 pub title: String,
214 pub artwork: Vec<Artwork>,
215}
216
217#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
218#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
219pub struct Episode {
220 pub id: MediaId,
221 pub show_id: MediaId,
222 #[serde(deserialize_with = "crate::required::option")]
225 pub show_title: Option<String>,
226 pub season_id: MediaId,
227 pub season: u32,
228 pub episode: u32,
229 pub title: String,
230 pub summary: Option<String>,
231 pub content_rating: Option<String>,
234 pub year: Option<u16>,
240 pub air_date: Option<CalendarDate>,
242 #[serde(with = "serde_time::millis::option_required")]
243 pub duration: Option<Duration>,
244 #[serde(default)]
248 pub cast: Vec<CastMember>,
249 pub artwork: Vec<Artwork>,
250 pub playback: PlaybackState,
251}
252
253#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
261#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
262pub struct CastMember {
263 pub id: PersonId,
266 pub name: String,
267 pub role: PersonRole,
268 #[serde(deserialize_with = "crate::required::option")]
271 pub character: Option<String>,
272 #[serde(deserialize_with = "crate::required::option")]
275 pub photo: Option<ArtworkId>,
276}
277
278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
280pub struct Artist {
281 pub id: MediaId,
282 pub name: String,
283 pub summary: Option<String>,
284 pub artwork: Vec<Artwork>,
285}
286
287#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
288#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
289pub struct Album {
290 pub id: MediaId,
291 pub artist_id: MediaId,
292 #[serde(deserialize_with = "crate::required::option")]
294 pub artist_name: Option<String>,
295 pub title: String,
296 pub year: Option<u16>,
297 pub track_count: Option<u32>,
301 pub artwork: Vec<Artwork>,
302}
303
304#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
305#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
306pub struct Track {
307 pub id: MediaId,
308 pub album_id: MediaId,
309 pub artist_id: MediaId,
310 pub artist_name: Option<String>,
314 pub album_title: Option<String>,
316 pub title: String,
317 pub track: Option<u32>,
319 pub disc: Option<u32>,
320 pub album_track_count: Option<u32>,
324 pub codec: Option<AudioCodec>,
326 pub bit_depth: Option<u32>,
330 pub sample_rate: Option<u32>,
333 #[serde(with = "serde_time::millis::option_required")]
334 pub duration: Option<Duration>,
335 pub artwork: Vec<Artwork>,
337 pub playback: PlaybackState,
338}
339
340#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
342#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
343#[serde(rename_all = "snake_case")]
344pub enum MarkerKind {
345 Intro,
346 Credits,
347 #[serde(other)]
350 Unknown,
351}
352
353#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
355#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
356pub struct Marker {
357 pub kind: MarkerKind,
358 #[serde(rename = "start_ms", with = "serde_time::millis")]
361 pub start: Duration,
362 #[serde(rename = "end_ms", with = "serde_time::millis")]
366 pub end: Duration,
367 pub to_end: bool,
370}
371
372#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
377#[serde(transparent)]
378pub struct Markers(Vec<Marker>);
379
380impl Markers {
381 pub fn into_vec(self) -> Vec<Marker> {
382 self.0
383 }
384}
385
386impl From<Vec<Marker>> for Markers {
387 fn from(mut markers: Vec<Marker>) -> Self {
388 markers.retain(|m| m.kind != MarkerKind::Unknown);
389 Self(markers)
390 }
391}
392
393impl<'de> Deserialize<'de> for Markers {
394 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
395 Vec::<Marker>::deserialize(d).map(Self::from)
396 }
397}
398
399impl std::ops::Deref for Markers {
400 type Target = [Marker];
401
402 fn deref(&self) -> &[Marker] {
403 &self.0
404 }
405}
406
407impl IntoIterator for Markers {
408 type Item = Marker;
409 type IntoIter = std::vec::IntoIter<Marker>;
410
411 fn into_iter(self) -> Self::IntoIter {
412 self.0.into_iter()
413 }
414}
415
416impl<'a> IntoIterator for &'a Markers {
417 type Item = &'a Marker;
418 type IntoIter = std::slice::Iter<'a, Marker>;
419
420 fn into_iter(self) -> Self::IntoIter {
421 self.0.iter()
422 }
423}
424
425#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
428#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
429#[serde(tag = "kind", rename_all = "snake_case")]
430pub enum Item {
431 Movie(Movie),
432 Show(Show),
433 Season(Season),
434 Episode(Episode),
435 Artist(Artist),
436 Album(Album),
437 Track(Track),
438}
439
440#[derive(Debug, Clone, Copy, PartialEq, Eq)]
442#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
443pub enum YearsAired {
444 One(u16),
446 Running(u16),
448 Between(u16, u16),
450}
451
452impl std::fmt::Display for YearsAired {
454 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
455 match self {
456 YearsAired::One(year) => write!(f, "{year}"),
457 YearsAired::Running(first) => write!(f, "{first}\u{2013}"),
458 YearsAired::Between(first, last) => write!(f, "{first}\u{2013}{last}"),
459 }
460 }
461}
462
463impl Show {
464 pub fn year_range(&self, today: CalendarDate) -> Option<YearsAired> {
470 let Some(last) = self.last_aired else {
471 return self.year.map(YearsAired::One);
472 };
473 let Some(first) = self.year else {
474 return Some(YearsAired::One(last.year()));
475 };
476 if last.year() <= first {
477 return Some(YearsAired::One(first));
478 }
479 let year_ago = (today.year() - 1, today.month(), today.day());
482 if (last.year(), last.month(), last.day()) >= year_ago {
483 Some(YearsAired::Running(first))
484 } else {
485 Some(YearsAired::Between(first, last.year()))
486 }
487 }
488
489 pub fn years_label(&self, today: CalendarDate) -> Option<String> {
491 self.year_range(today).map(|years| years.to_string())
492 }
493}
494
495#[derive(Debug, Clone, PartialEq, Eq)]
497#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
498pub enum Caption {
499 Year(u16),
501 Years(YearsAired),
503 Show(String),
505 Episode {
507 show: Option<String>,
508 season: u32,
509 episode: u32,
510 },
511 Album {
513 artist: Option<String>,
514 year: Option<u16>,
515 },
516 Length(Duration),
518}
519
520impl Item {
521 pub fn duration(&self) -> Option<Duration> {
523 match self {
524 Item::Movie(m) => m.duration,
525 Item::Episode(e) => e.duration,
526 Item::Track(t) => t.duration,
527 _ => None,
528 }
529 }
530}
531
532impl Item {
533 pub fn caption_parts(&self, today: CalendarDate) -> Option<Caption> {
536 match self {
537 Item::Movie(m) => m.year.map(Caption::Year),
538 Item::Show(s) => s.year_range(today).map(Caption::Years),
539 Item::Season(s) => s.show_title.clone().map(Caption::Show),
540 Item::Episode(e) => Some(Caption::Episode {
541 show: e.show_title.clone(),
542 season: e.season,
543 episode: e.episode,
544 }),
545 Item::Album(a) => {
546 (a.artist_name.is_some() || a.year.is_some()).then(|| Caption::Album {
547 artist: a.artist_name.clone(),
548 year: a.year,
549 })
550 }
551 Item::Track(t) => t.duration.map(Caption::Length),
552 Item::Artist(_) => None,
553 }
554 }
555
556 pub fn id(&self) -> &MediaId {
557 match self {
558 Item::Movie(m) => &m.id,
559 Item::Show(s) => &s.id,
560 Item::Season(s) => &s.id,
561 Item::Episode(e) => &e.id,
562 Item::Artist(a) => &a.id,
563 Item::Album(a) => &a.id,
564 Item::Track(t) => &t.id,
565 }
566 }
567
568 pub fn title(&self) -> &str {
571 match self {
572 Item::Movie(m) => &m.title,
573 Item::Show(s) => &s.title,
574 Item::Season(s) => &s.title,
575 Item::Episode(e) => &e.title,
576 Item::Artist(a) => &a.name,
577 Item::Album(a) => &a.title,
578 Item::Track(t) => &t.title,
579 }
580 }
581
582 pub fn artwork(&self) -> &[Artwork] {
584 match self {
585 Item::Movie(m) => &m.artwork,
586 Item::Show(s) => &s.artwork,
587 Item::Season(s) => &s.artwork,
588 Item::Episode(e) => &e.artwork,
589 Item::Artist(a) => &a.artwork,
590 Item::Album(a) => &a.artwork,
591 Item::Track(t) => &t.artwork,
592 }
593 }
594
595 pub fn artwork_of(&self, kind: ArtworkKind) -> Option<&Artwork> {
597 self.artwork().iter().find(|a| a.kind == kind)
598 }
599
600 pub fn playback(&self) -> Option<&PlaybackState> {
603 match self {
604 Item::Movie(m) => Some(&m.playback),
605 Item::Episode(e) => Some(&e.playback),
606 Item::Track(t) => Some(&t.playback),
607 _ => None,
608 }
609 }
610
611 pub fn is_watched(&self) -> bool {
613 self.playback().is_some_and(|p| p.watched)
614 }
615
616 pub fn resume_position(&self) -> Option<Duration> {
618 self.playback().and_then(|p| p.position)
619 }
620
621 pub fn resume_from(&self) -> Option<Duration> {
623 self.playback().and_then(PlaybackState::resume_from)
624 }
625
626 pub fn progress(&self) -> Option<Progress> {
629 Some(self.playback()?.progress(self.duration()))
630 }
631}
632
633#[cfg(test)]
634mod tests {
635 use std::fmt::Debug;
636 use std::time::UNIX_EPOCH;
637
638 use serde::de::DeserializeOwned;
639
640 use super::*;
641 use crate::id::{MediaKind, Namespace};
642
643 fn round_trip<T: Serialize + DeserializeOwned + PartialEq + Debug>(value: T) {
644 let json = serde_json::to_string(&value).unwrap();
645 assert_eq!(serde_json::from_str::<T>(&json).unwrap(), value, "{json}");
646 }
647
648 fn media(kind: MediaKind, key: &str) -> MediaId {
649 MediaId::new(Namespace::Plex, kind, key).unwrap()
650 }
651
652 fn poster() -> Vec<Artwork> {
653 vec![Artwork {
654 id: ArtworkId::new(Namespace::Plex, "/library/metadata/1/thumb/9").unwrap(),
655 kind: ArtworkKind::Poster,
656 }]
657 }
658
659 fn halfway() -> PlaybackState {
660 PlaybackState {
661 position: Some(Duration::from_millis(2_220_500)),
662 watched: false,
663 last_viewed_at: None,
664 play_count: 0,
665 last_played_at: None,
666 }
667 }
668
669 fn ripley() -> CastMember {
670 CastMember {
671 id: PersonId::new(Namespace::Plex, "actor-13").unwrap(),
672 name: "Sigourney Weaver".into(),
673 role: PersonRole::Actor,
674 character: Some("Ellen Ripley".into()),
675 photo: Some(ArtworkId::new(Namespace::Plex, "/people/1/a/b.jpg").unwrap()),
676 }
677 }
678
679 fn scott() -> CastMember {
680 CastMember {
681 id: PersonId::new(Namespace::Plex, "director-7").unwrap(),
682 name: "Ridley Scott".into(),
683 role: PersonRole::Director,
684 character: None,
685 photo: None,
686 }
687 }
688
689 #[test]
690 fn a_cast_member_is_their_person_id_role_and_photo_on_the_wire() {
691 assert_eq!(
692 serde_json::to_value(ripley()).unwrap(),
693 serde_json::json!({
694 "id": "plex:actor-13",
695 "name": "Sigourney Weaver",
696 "role": "actor",
697 "character": "Ellen Ripley",
698 "photo": "plex:/people/1/a/b.jpg",
699 })
700 );
701 round_trip(ripley());
702 round_trip(scott());
703 }
704
705 #[test]
707 fn a_cast_member_s_character_and_photo_are_required() {
708 crate::test_support::assert_each_required(&scott(), &["character", "photo"]);
709 }
710
711 #[test]
714 fn items_from_a_server_without_cast_or_dates_still_decode() {
715 let movie = Movie {
716 id: media(MediaKind::Movie, "10"),
717 title: "Alien".into(),
718 year: Some(1979),
719 release_date: CalendarDate::new(1979, 5, 25),
720 summary: None,
721 content_rating: None,
722 duration: None,
723 cast: vec![ripley()],
724 artwork: Vec::new(),
725 playback: PlaybackState::default(),
726 };
727 let mut json = serde_json::to_value(&movie).unwrap();
728 assert_eq!(json["release_date"], "1979-05-25");
729 let object = json.as_object_mut().unwrap();
730 object.remove("release_date");
731 object.remove("cast");
732 let older: Movie = serde_json::from_value(json).unwrap();
733 assert_eq!((older.release_date, older.cast), (None, Vec::new()));
734
735 let show = Show {
736 id: media(MediaKind::Show, "20"),
737 title: "The Expanse".into(),
738 year: Some(2015),
739 summary: None,
740 content_rating: None,
741 season_count: None,
742 genres: Vec::new(),
743 last_aired: CalendarDate::new(2022, 4, 8),
744 cast: vec![ripley()],
745 artwork: Vec::new(),
746 };
747 let mut json = serde_json::to_value(&show).unwrap();
748 assert_eq!(json["last_aired"], "2022-04-08");
749 let object = json.as_object_mut().unwrap();
750 object.remove("last_aired");
751 object.remove("cast");
752 let older: Show = serde_json::from_value(json).unwrap();
753 assert_eq!((older.last_aired, older.cast), (None, Vec::new()));
754
755 let episode = Episode {
756 id: media(MediaKind::Episode, "22"),
757 show_id: media(MediaKind::Show, "20"),
758 show_title: None,
759 season_id: media(MediaKind::Season, "21"),
760 season: 1,
761 episode: 1,
762 title: "Dulcinea".into(),
763 summary: None,
764 content_rating: None,
765 year: None,
766 air_date: None,
767 duration: None,
768 cast: vec![scott()],
769 artwork: Vec::new(),
770 playback: PlaybackState::default(),
771 };
772 let mut json = serde_json::to_value(&episode).unwrap();
773 json.as_object_mut().unwrap().remove("cast");
774 let older: Episode = serde_json::from_value(json).unwrap();
775 assert_eq!(older.cast, Vec::new());
776 }
777
778 #[test]
779 fn a_track_s_format_is_plain_numbers_on_the_wire() {
780 let track = Track {
781 id: media(MediaKind::Track, "224630"),
782 album_id: media(MediaKind::Album, "224629"),
783 artist_id: media(MediaKind::Artist, "224303"),
784 artist_name: None,
785 album_title: None,
786 title: "Catch".into(),
787 track: Some(1),
788 disc: Some(1),
789 album_track_count: Some(3),
790 codec: Some(AudioCodec::Flac),
791 bit_depth: Some(24),
792 sample_rate: Some(96_000),
793 duration: None,
794 artwork: Vec::new(),
795 playback: PlaybackState::default(),
796 };
797 let json = serde_json::to_value(&track).unwrap();
798 assert_eq!(
799 (
800 &json["codec"],
801 &json["bit_depth"],
802 &json["sample_rate"],
803 &json["album_track_count"]
804 ),
805 (
806 &serde_json::json!("flac"),
807 &serde_json::json!(24),
808 &serde_json::json!(96_000),
809 &serde_json::json!(3)
810 )
811 );
812 }
813
814 #[test]
815 fn library_kinds_are_snake_case_on_the_wire() {
816 assert_eq!(
817 serde_json::to_string(&LibraryKind::Movies).unwrap(),
818 r#""movies""#
819 );
820 }
821
822 #[test]
823 fn an_item_carries_its_kind_on_the_wire() {
824 let item = Item::Show(Show {
825 id: media(MediaKind::Show, "20"),
826 title: "The Expanse".into(),
827 year: None,
828 summary: None,
829 content_rating: None,
830 season_count: None,
831 genres: Vec::new(),
832 last_aired: None,
833 cast: Vec::new(),
834 artwork: Vec::new(),
835 });
836 let json = serde_json::to_value(&item).unwrap();
837 assert_eq!(json["kind"], "show");
838 assert_eq!(json["id"], "plex:show:20");
839 round_trip(item);
840 }
841
842 #[test]
845 fn a_parent_s_name_left_out_is_refused() {
846 let season = Season {
847 id: media(MediaKind::Season, "21"),
848 show_id: media(MediaKind::Show, "20"),
849 show_title: None,
850 season: 1,
851 title: "Season 1".into(),
852 artwork: Vec::new(),
853 };
854 crate::test_support::assert_each_required(&season, &["show_title"]);
855 let episode = Episode {
856 id: media(MediaKind::Episode, "22"),
857 show_id: media(MediaKind::Show, "20"),
858 show_title: None,
859 season_id: media(MediaKind::Season, "21"),
860 season: 1,
861 episode: 1,
862 title: "Dulcinea".into(),
863 summary: None,
864 content_rating: None,
865 year: None,
866 air_date: None,
867 duration: None,
868 cast: Vec::new(),
869 artwork: Vec::new(),
870 playback: PlaybackState::default(),
871 };
872 crate::test_support::assert_each_required(&episode, &["show_title"]);
873 let album = Album {
874 id: media(MediaKind::Album, "30"),
875 artist_id: media(MediaKind::Artist, "31"),
876 artist_name: None,
877 title: "Moon Safari".into(),
878 year: None,
879 track_count: None,
880 artwork: Vec::new(),
881 };
882 crate::test_support::assert_each_required(&album, &["artist_name"]);
883 round_trip(album);
885 }
886
887 #[test]
888 fn an_episode_from_a_server_without_air_dates_still_decodes() {
889 let episode = Episode {
890 id: media(MediaKind::Episode, "22"),
891 show_id: media(MediaKind::Show, "20"),
892 show_title: None,
893 season_id: media(MediaKind::Season, "21"),
894 season: 1,
895 episode: 1,
896 title: "Dulcinea".into(),
897 summary: None,
898 content_rating: None,
899 year: Some(2015),
900 air_date: CalendarDate::new(2015, 11, 23),
901 duration: None,
902 cast: Vec::new(),
903 artwork: Vec::new(),
904 playback: PlaybackState::default(),
905 };
906 let mut json = serde_json::to_value(&episode).unwrap();
907 assert_eq!(json["air_date"], "2015-11-23");
908 let object = json.as_object_mut().unwrap();
909 object.remove("year");
910 object.remove("air_date");
911 let older: Episode = serde_json::from_value(json).unwrap();
912 assert_eq!((older.year, older.air_date), (None, None));
913 }
914
915 fn years(year: Option<u16>, last_aired: Option<(u16, u8, u8)>) -> Option<String> {
917 let show = Show {
918 id: media(MediaKind::Show, "20"),
919 title: "Andor".into(),
920 year,
921 summary: None,
922 content_rating: None,
923 season_count: None,
924 genres: Vec::new(),
925 last_aired: last_aired.and_then(|(y, m, d)| CalendarDate::new(y, m, d)),
926 cast: Vec::new(),
927 artwork: Vec::new(),
928 };
929 show.years_label(CalendarDate::new(2026, 10, 14).unwrap())
930 }
931
932 #[test]
933 fn a_show_s_years_come_in_parts() {
934 let show = |last: (u16, u8, u8)| Show {
935 id: media(MediaKind::Show, "20"),
936 title: "Andor".into(),
937 year: Some(2022),
938 summary: None,
939 content_rating: None,
940 season_count: None,
941 genres: Vec::new(),
942 last_aired: CalendarDate::new(last.0, last.1, last.2),
943 cast: Vec::new(),
944 artwork: Vec::new(),
945 };
946 let today = CalendarDate::new(2026, 10, 14).unwrap();
947 assert_eq!(
948 show((2025, 10, 14)).year_range(today),
949 Some(YearsAired::Running(2022))
950 );
951 assert_eq!(
952 show((2025, 10, 13)).year_range(today),
953 Some(YearsAired::Between(2022, 2025))
954 );
955 assert_eq!(
956 Item::Show(show((2022, 5, 1))).caption_parts(today),
957 Some(Caption::Years(YearsAired::One(2022)))
958 );
959 }
960
961 #[test]
962 fn a_show_with_no_air_date_shows_its_first_year() {
963 assert_eq!(years(Some(2022), None), Some("2022".into()));
964 assert_eq!(years(None, None), None);
965 }
966
967 #[test]
968 fn a_show_last_aired_in_its_first_year_shows_that_year() {
969 assert_eq!(years(Some(2022), Some((2022, 12, 1))), Some("2022".into()));
970 }
971
972 #[test]
973 fn a_show_aired_in_the_last_twelve_months_is_an_open_range() {
974 assert_eq!(
975 years(Some(2022), Some((2025, 10, 14))),
976 Some("2022\u{2013}".into())
977 );
978 }
979
980 #[test]
981 fn a_show_last_aired_over_a_year_ago_shows_both_years() {
982 assert_eq!(
983 years(Some(2022), Some((2025, 10, 13))),
984 Some("2022\u{2013}2025".into())
985 );
986 }
987
988 #[test]
989 fn a_show_with_no_first_year_shows_when_it_last_aired() {
990 assert_eq!(years(None, Some((2019, 3, 2))), Some("2019".into()));
991 }
992
993 #[test]
994 fn every_model_type_round_trips() {
995 round_trip(Library {
996 id: LibraryId::new(Namespace::Plex, "1").unwrap(),
997 title: "Movies".into(),
998 kind: LibraryKind::Movies,
999 server: None,
1000 });
1001 round_trip(Movie {
1002 id: media(MediaKind::Movie, "10"),
1003 title: "Alien".into(),
1004 year: Some(1979),
1005 release_date: CalendarDate::new(1979, 5, 25),
1006 summary: Some("In space no one can hear you scream.".into()),
1007 content_rating: Some("R".into()),
1008 duration: Some(Duration::from_secs(7020)),
1009 cast: vec![ripley(), scott()],
1010 artwork: poster(),
1011 playback: halfway(),
1012 });
1013 round_trip(Show {
1014 id: media(MediaKind::Show, "20"),
1015 title: "The Expanse".into(),
1016 year: Some(2015),
1017 summary: None,
1018 content_rating: Some("TV-14".into()),
1019 season_count: Some(6),
1020 genres: vec!["Science Fiction".into(), "Drama".into()],
1021 last_aired: CalendarDate::new(2022, 4, 8),
1022 cast: vec![ripley()],
1023 artwork: poster(),
1024 });
1025 round_trip(Season {
1026 id: media(MediaKind::Season, "21"),
1027 show_id: media(MediaKind::Show, "20"),
1028 show_title: Some("The Expanse".into()),
1029 season: 1,
1030 title: "Season 1".into(),
1031 artwork: Vec::new(),
1032 });
1033 round_trip(Episode {
1034 id: media(MediaKind::Episode, "22"),
1035 show_id: media(MediaKind::Show, "20"),
1036 show_title: Some("The Expanse".into()),
1037 season_id: media(MediaKind::Season, "21"),
1038 season: 1,
1039 episode: 1,
1040 title: "Dulcinea".into(),
1041 summary: None,
1042 content_rating: Some("TV-14".into()),
1043 year: Some(2015),
1044 air_date: CalendarDate::new(2015, 11, 23),
1045 duration: Some(Duration::from_secs(2640)),
1046 cast: vec![scott()],
1047 artwork: poster(),
1048 playback: PlaybackState::default(),
1049 });
1050 round_trip(Artist {
1051 id: media(MediaKind::Artist, "30"),
1052 name: "Boards of Canada".into(),
1053 summary: None,
1054 artwork: poster(),
1055 });
1056 round_trip(Album {
1057 id: media(MediaKind::Album, "31"),
1058 artist_id: media(MediaKind::Artist, "30"),
1059 artist_name: Some("Boards of Canada".into()),
1060 title: "Music Has the Right to Children".into(),
1061 year: Some(1998),
1062 track_count: Some(18),
1063 artwork: poster(),
1064 });
1065 round_trip(Track {
1066 id: media(MediaKind::Track, "32"),
1067 album_id: media(MediaKind::Album, "31"),
1068 artist_id: media(MediaKind::Artist, "30"),
1069 artist_name: Some("Boards of Canada".into()),
1070 album_title: Some("Music Has the Right to Children".into()),
1071 title: "Roygbiv".into(),
1072 track: Some(10),
1073 disc: Some(1),
1074 album_track_count: Some(18),
1075 codec: Some(AudioCodec::Flac),
1076 bit_depth: Some(16),
1077 sample_rate: Some(44_100),
1078 duration: Some(Duration::from_secs(151)),
1079 artwork: poster(),
1080 playback: PlaybackState {
1081 position: None,
1082 watched: true,
1083 last_viewed_at: None,
1084 play_count: 0,
1085 last_played_at: None,
1086 },
1087 });
1088 }
1089
1090 fn alien(playback: PlaybackState, duration: Option<Duration>) -> Item {
1091 Item::Movie(Movie {
1092 id: media(MediaKind::Movie, "10"),
1093 title: "Alien".into(),
1094 year: Some(1979),
1095 release_date: None,
1096 summary: None,
1097 content_rating: None,
1098 duration,
1099 cast: Vec::new(),
1100 artwork: Vec::new(),
1101 playback,
1102 })
1103 }
1104
1105 #[test]
1109 fn markers_and_watch_times_keep_their_wire_form() {
1110 let marker = Marker {
1111 kind: MarkerKind::Intro,
1112 start: Duration::from_millis(258_865),
1113 end: Duration::from_millis(319_865),
1114 to_end: false,
1115 };
1116 let state = PlaybackState {
1117 last_viewed_at: Some(UNIX_EPOCH + Duration::from_secs(1_761_700_000)),
1118 play_count: 2,
1119 last_played_at: Some(UNIX_EPOCH + Duration::from_secs(1_761_600_000)),
1120 ..PlaybackState::default()
1121 };
1122 assert_eq!(
1123 (
1124 serde_json::to_value(marker).unwrap(),
1125 serde_json::to_value(&state).unwrap(),
1126 serde_json::to_value(halfway()).unwrap()["position"].clone(),
1127 ),
1128 (
1129 serde_json::json!({
1130 "kind": "intro", "start_ms": 258_865, "end_ms": 319_865, "to_end": false
1131 }),
1132 serde_json::json!({
1133 "position": null, "watched": false, "last_viewed_at": 1_761_700_000,
1134 "play_count": 2, "last_played_at": 1_761_600_000
1135 }),
1136 serde_json::json!(2_220_500),
1137 )
1138 );
1139 round_trip(marker);
1140 round_trip(state);
1141 }
1142
1143 #[test]
1144 fn a_marker_list_leaves_out_kinds_this_build_does_not_know() {
1145 let listed: Markers = serde_json::from_value(serde_json::json!([
1146 { "kind": "recap", "start_ms": 0, "end_ms": 60_000, "to_end": false },
1147 { "kind": "intro", "start_ms": 60_000, "end_ms": 90_000, "to_end": false },
1148 ]))
1149 .unwrap();
1150 let intro = Marker {
1151 kind: MarkerKind::Intro,
1152 start: Duration::from_millis(60_000),
1153 end: Duration::from_millis(90_000),
1154 to_end: false,
1155 };
1156 assert_eq!(*listed, [intro]);
1157 assert_eq!(
1158 serde_json::to_value(&listed).unwrap()[0]["start_ms"],
1159 60_000
1160 );
1161 }
1162
1163 #[test]
1164 fn an_item_s_artwork_of_a_kind_is_its_first_one() {
1165 let art = |kind, path: &str| Artwork {
1166 id: ArtworkId::new(Namespace::Plex, path).unwrap(),
1167 kind,
1168 };
1169 let Item::Movie(mut movie) = alien(PlaybackState::default(), None) else {
1170 unreachable!()
1171 };
1172 movie.artwork = vec![
1173 art(ArtworkKind::Background, "/bg"),
1174 art(ArtworkKind::Poster, "/p1"),
1175 art(ArtworkKind::Poster, "/p2"),
1176 ];
1177 let item = Item::Movie(movie);
1178 assert_eq!(
1179 [
1180 ArtworkKind::Poster,
1181 ArtworkKind::Background,
1182 ArtworkKind::Thumb
1183 ]
1184 .map(|kind| item.artwork_of(kind).cloned()),
1185 [
1186 Some(art(ArtworkKind::Poster, "/p1")),
1187 Some(art(ArtworkKind::Background, "/bg")),
1188 None
1189 ]
1190 );
1191 }
1192
1193 fn at(secs: u64, watched: bool) -> PlaybackState {
1194 PlaybackState {
1195 position: Some(Duration::from_secs(secs)),
1196 watched,
1197 ..PlaybackState::default()
1198 }
1199 }
1200
1201 #[test]
1202 fn a_film_stopped_part_way_resumes_where_it_stopped() {
1203 assert_eq!(at(600, false).resume_from(), Some(Duration::from_secs(600)));
1204 }
1205
1206 #[test]
1207 fn a_watched_film_plays_from_the_start() {
1208 assert_eq!(at(600, true).resume_from(), None);
1209 }
1210
1211 #[test]
1212 fn a_film_never_begun_plays_from_the_start() {
1213 assert_eq!(PlaybackState::default().resume_from(), None);
1214 assert_eq!(at(0, false).resume_from(), None);
1215 }
1216
1217 #[test]
1218 fn progress_is_the_fraction_watched_and_the_time_left() {
1219 let progress = at(1_500, false).progress(Some(Duration::from_secs(6_000)));
1220 assert_eq!(
1221 progress,
1222 Progress {
1223 position: Duration::from_secs(1_500),
1224 remaining: Some(Duration::from_secs(4_500)),
1225 fraction: Some(0.25),
1226 watched: false,
1227 }
1228 );
1229 }
1230
1231 #[test]
1232 fn progress_past_the_length_is_whole_with_nothing_left() {
1233 let progress = at(7_000, true).progress(Some(Duration::from_secs(6_000)));
1234 assert_eq!(
1235 (progress.fraction, progress.remaining, progress.watched),
1236 (Some(1.0), Some(Duration::ZERO), true)
1237 );
1238 }
1239
1240 #[test]
1241 fn progress_with_no_length_has_no_fraction() {
1242 for length in [None, Some(Duration::ZERO)] {
1243 let progress = at(60, false).progress(length);
1244 assert_eq!((progress.fraction, progress.remaining), (None, None));
1245 }
1246 }
1247
1248 #[test]
1249 fn an_item_answers_from_its_own_playback() {
1250 let item = alien(at(600, false), Some(Duration::from_secs(1_200)));
1251 assert_eq!(item.title(), "Alien");
1252 assert!(!item.is_watched());
1253 assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
1254 assert_eq!(item.resume_from(), Some(Duration::from_secs(600)));
1255 assert_eq!(item.progress().and_then(|p| p.fraction), Some(0.5));
1256 }
1257
1258 #[test]
1259 fn a_watched_item_keeps_its_position_but_resumes_from_the_start() {
1260 let item = alien(at(600, true), None);
1261 assert!(item.is_watched());
1262 assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
1263 assert_eq!(item.resume_from(), None);
1264 }
1265
1266 #[test]
1267 fn an_artist_has_a_title_but_no_progress() {
1268 let show = Item::Artist(Artist {
1269 id: media(MediaKind::Artist, "30"),
1270 name: "Daft Punk".into(),
1271 summary: None,
1272 artwork: Vec::new(),
1273 });
1274 assert_eq!(show.title(), "Daft Punk");
1275 assert_eq!(show.progress(), None);
1276 assert!(!show.is_watched());
1277 assert_eq!(show.resume_from(), None);
1278 }
1279}