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