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, Default, PartialEq, Eq, Serialize, Deserialize)]
147#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
148pub struct MergeFacts {
149 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
162 #[cfg_attr(feature = "uniffi", uniffi(default = None))]
163 pub rating_tenths: Option<u16>,
164 #[serde(default, skip_serializing_if = "Option::is_none")]
167 #[cfg_attr(feature = "uniffi", uniffi(default = None))]
168 pub audience_rating_tenths: Option<u16>,
169 #[serde(default, skip_serializing_if = "Option::is_none")]
172 #[cfg_attr(feature = "uniffi", uniffi(default = None))]
173 pub size: Option<u64>,
174 #[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 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 pub year: Option<u16>,
198 pub release_date: Option<CalendarDate>,
204 pub summary: Option<String>,
205 pub content_rating: Option<String>,
208 #[serde(with = "serde_time::millis::option_required")]
209 pub duration: Option<Duration>,
210 #[serde(default)]
212 pub cast: Vec<CastMember>,
213 #[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 pub content_rating: Option<String>,
232 pub season_count: Option<u32>,
235 pub genres: Vec<String>,
239 pub last_aired: Option<CalendarDate>,
250 #[serde(default)]
252 pub cast: Vec<CastMember>,
253 #[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 #[serde(deserialize_with = "crate::required::option")]
268 pub show_title: Option<String>,
269 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 #[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 pub content_rating: Option<String>,
292 pub year: Option<u16>,
298 pub air_date: Option<CalendarDate>,
300 #[serde(with = "serde_time::millis::option_required")]
301 pub duration: Option<Duration>,
302 #[serde(default)]
306 pub cast: Vec<CastMember>,
307 #[serde(default, skip_serializing_if = "MergeFacts::is_empty")]
311 pub merge: MergeFacts,
312 pub artwork: Vec<Artwork>,
313 pub playback: PlaybackState,
314}
315
316#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
324#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
325pub struct CastMember {
326 pub id: PersonId,
329 pub name: String,
330 pub role: PersonRole,
331 #[serde(deserialize_with = "crate::required::option")]
334 pub character: Option<String>,
335 #[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 #[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 #[serde(deserialize_with = "crate::required::option")]
362 pub artist_name: Option<String>,
363 pub title: String,
364 pub year: Option<u16>,
365 pub track_count: Option<u32>,
369 #[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 pub artist_name: Option<String>,
387 pub album_title: Option<String>,
389 pub title: String,
390 pub track: Option<u32>,
392 pub disc: Option<u32>,
393 pub album_track_count: Option<u32>,
397 pub codec: Option<AudioCodec>,
399 pub bit_depth: Option<u32>,
403 pub sample_rate: Option<u32>,
406 #[serde(with = "serde_time::millis::option_required")]
407 pub duration: Option<Duration>,
408 #[serde(default, skip_serializing_if = "MergeFacts::is_empty")]
412 pub merge: MergeFacts,
413 pub artwork: Vec<Artwork>,
415 pub playback: PlaybackState,
416}
417
418#[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 #[serde(other)]
428 Unknown,
429}
430
431#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
433#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
434pub struct Marker {
435 pub kind: MarkerKind,
436 #[serde(rename = "start_ms", with = "serde_time::millis")]
439 pub start: Duration,
440 #[serde(rename = "end_ms", with = "serde_time::millis")]
444 pub end: Duration,
445 pub to_end: bool,
448}
449
450#[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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
520#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
521pub enum YearsAired {
522 One(u16),
524 Running(u16),
526 Between(u16, u16),
528}
529
530impl 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 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 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 pub fn years_label(&self, today: CalendarDate) -> Option<String> {
569 self.year_range(today).map(|years| years.to_string())
570 }
571}
572
573#[derive(Debug, Clone, PartialEq, Eq)]
575#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
576pub enum Caption {
577 Year(u16),
579 Years(YearsAired),
581 Show(String),
583 Episode {
585 show: Option<String>,
586 season: u32,
587 episode: u32,
588 },
589 Album {
591 artist: Option<String>,
592 year: Option<u16>,
593 },
594 Length(Duration),
596}
597
598impl Item {
599 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 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 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 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 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 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 pub fn artwork_of(&self, kind: ArtworkKind) -> Option<&Artwork> {
702 self.artwork().iter().find(|a| a.kind == kind)
703 }
704
705 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 pub fn is_watched(&self) -> bool {
718 self.playback().is_some_and(|p| p.watched)
719 }
720
721 pub fn resume_position(&self) -> Option<Duration> {
723 self.playback().and_then(|p| p.position)
724 }
725
726 pub fn resume_from(&self) -> Option<Duration> {
728 self.playback().and_then(PlaybackState::resume_from)
729 }
730
731 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 #[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 #[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 #[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 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 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 #[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}