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")]
173 #[cfg_attr(feature = "uniffi", uniffi(default = None))]
174 pub rating_source: Option<crate::RatingSource>,
175 #[serde(default, skip_serializing_if = "Option::is_none")]
177 #[cfg_attr(feature = "uniffi", uniffi(default = None))]
178 pub audience_rating_source: Option<crate::RatingSource>,
179 #[serde(default, skip_serializing_if = "Option::is_none")]
182 #[cfg_attr(feature = "uniffi", uniffi(default = None))]
183 pub size: Option<u64>,
184 #[serde(default, skip_serializing_if = "Vec::is_empty")]
190 #[cfg_attr(feature = "uniffi", uniffi(default = []))]
191 pub external_ids: Vec<String>,
192}
193
194impl MergeFacts {
195 pub fn is_empty(&self) -> bool {
197 *self == Self::default()
198 }
199}
200
201#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
202#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
203pub struct Movie {
204 pub id: MediaId,
205 pub title: String,
206 pub year: Option<u16>,
208 pub release_date: Option<CalendarDate>,
214 pub summary: Option<String>,
215 pub content_rating: Option<String>,
218 #[serde(with = "serde_time::millis::option_required")]
219 pub duration: Option<Duration>,
220 #[serde(default)]
222 pub cast: Vec<CastMember>,
223 #[serde(default, skip_serializing_if = "MergeFacts::is_empty")]
227 pub merge: MergeFacts,
228 pub artwork: Vec<Artwork>,
229 pub playback: PlaybackState,
230}
231
232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
234pub struct Show {
235 pub id: MediaId,
236 pub title: String,
237 pub year: Option<u16>,
238 pub summary: Option<String>,
239 pub content_rating: Option<String>,
242 pub season_count: Option<u32>,
245 pub genres: Vec<String>,
249 pub last_aired: Option<CalendarDate>,
260 #[serde(default)]
262 pub cast: Vec<CastMember>,
263 #[serde(default, skip_serializing_if = "MergeFacts::is_empty")]
267 pub merge: MergeFacts,
268 pub artwork: Vec<Artwork>,
269}
270
271#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
272#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
273pub struct Season {
274 pub id: MediaId,
275 pub show_id: MediaId,
276 #[serde(deserialize_with = "crate::required::option")]
278 pub show_title: Option<String>,
279 pub season: u32,
281 pub title: String,
282 pub artwork: Vec<Artwork>,
283}
284
285#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
286#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
287pub struct Episode {
288 pub id: MediaId,
289 pub show_id: MediaId,
290 #[serde(deserialize_with = "crate::required::option")]
293 pub show_title: Option<String>,
294 pub season_id: MediaId,
295 pub season: u32,
296 pub episode: u32,
297 pub title: String,
298 pub summary: Option<String>,
299 pub content_rating: Option<String>,
302 pub year: Option<u16>,
308 pub air_date: Option<CalendarDate>,
310 #[serde(with = "serde_time::millis::option_required")]
311 pub duration: Option<Duration>,
312 #[serde(default)]
316 pub cast: Vec<CastMember>,
317 #[serde(default, skip_serializing_if = "MergeFacts::is_empty")]
321 pub merge: MergeFacts,
322 pub artwork: Vec<Artwork>,
323 pub playback: PlaybackState,
324}
325
326#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
334#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
335pub struct CastMember {
336 pub id: PersonId,
339 pub name: String,
340 pub role: PersonRole,
341 #[serde(deserialize_with = "crate::required::option")]
344 pub character: Option<String>,
345 #[serde(deserialize_with = "crate::required::option")]
348 pub photo: Option<ArtworkId>,
349}
350
351#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
352#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
353pub struct Artist {
354 pub id: MediaId,
355 pub name: String,
356 pub summary: Option<String>,
357 #[serde(default, skip_serializing_if = "MergeFacts::is_empty")]
361 pub merge: MergeFacts,
362 pub artwork: Vec<Artwork>,
363}
364
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
367pub struct Album {
368 pub id: MediaId,
369 pub artist_id: MediaId,
370 #[serde(deserialize_with = "crate::required::option")]
372 pub artist_name: Option<String>,
373 pub title: String,
374 pub year: Option<u16>,
375 pub track_count: Option<u32>,
379 #[serde(default, skip_serializing_if = "MergeFacts::is_empty")]
383 pub merge: MergeFacts,
384 pub artwork: Vec<Artwork>,
385}
386
387#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
388#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
389pub struct Track {
390 pub id: MediaId,
391 pub album_id: MediaId,
392 pub artist_id: MediaId,
393 pub artist_name: Option<String>,
397 pub album_title: Option<String>,
399 pub title: String,
400 pub track: Option<u32>,
402 pub disc: Option<u32>,
403 pub album_track_count: Option<u32>,
407 pub codec: Option<AudioCodec>,
409 pub bit_depth: Option<u32>,
413 pub sample_rate: Option<u32>,
416 #[serde(with = "serde_time::millis::option_required")]
417 pub duration: Option<Duration>,
418 #[serde(default, skip_serializing_if = "MergeFacts::is_empty")]
422 pub merge: MergeFacts,
423 pub artwork: Vec<Artwork>,
425 pub playback: PlaybackState,
426}
427
428#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
430#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
431#[serde(rename_all = "snake_case")]
432pub enum MarkerKind {
433 Intro,
434 Credits,
435 #[serde(other)]
438 Unknown,
439}
440
441#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
443#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
444pub struct Marker {
445 pub kind: MarkerKind,
446 #[serde(rename = "start_ms", with = "serde_time::millis")]
449 pub start: Duration,
450 #[serde(rename = "end_ms", with = "serde_time::millis")]
454 pub end: Duration,
455 pub to_end: bool,
458}
459
460#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
465#[serde(transparent)]
466pub struct Markers(Vec<Marker>);
467
468impl Markers {
469 pub fn into_vec(self) -> Vec<Marker> {
470 self.0
471 }
472}
473
474impl From<Vec<Marker>> for Markers {
475 fn from(mut markers: Vec<Marker>) -> Self {
476 markers.retain(|m| m.kind != MarkerKind::Unknown);
477 Self(markers)
478 }
479}
480
481impl<'de> Deserialize<'de> for Markers {
482 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
483 Vec::<Marker>::deserialize(d).map(Self::from)
484 }
485}
486
487impl std::ops::Deref for Markers {
488 type Target = [Marker];
489
490 fn deref(&self) -> &[Marker] {
491 &self.0
492 }
493}
494
495impl IntoIterator for Markers {
496 type Item = Marker;
497 type IntoIter = std::vec::IntoIter<Marker>;
498
499 fn into_iter(self) -> Self::IntoIter {
500 self.0.into_iter()
501 }
502}
503
504impl<'a> IntoIterator for &'a Markers {
505 type Item = &'a Marker;
506 type IntoIter = std::slice::Iter<'a, Marker>;
507
508 fn into_iter(self) -> Self::IntoIter {
509 self.0.iter()
510 }
511}
512
513#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
516#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
517#[serde(tag = "kind", rename_all = "snake_case")]
518pub enum Item {
519 Movie(Movie),
520 Show(Show),
521 Season(Season),
522 Episode(Episode),
523 Artist(Artist),
524 Album(Album),
525 Track(Track),
526}
527
528#[derive(Debug, Clone, Copy, PartialEq, Eq)]
530#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
531pub enum YearsAired {
532 One(u16),
534 Running(u16),
536 Between(u16, u16),
538}
539
540impl std::fmt::Display for YearsAired {
542 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
543 match self {
544 YearsAired::One(year) => write!(f, "{year}"),
545 YearsAired::Running(first) => write!(f, "{first}\u{2013}"),
546 YearsAired::Between(first, last) => write!(f, "{first}\u{2013}{last}"),
547 }
548 }
549}
550
551impl Show {
552 pub fn year_range(&self, today: CalendarDate) -> Option<YearsAired> {
558 let Some(last) = self.last_aired else {
559 return self.year.map(YearsAired::One);
560 };
561 let Some(first) = self.year else {
562 return Some(YearsAired::One(last.year()));
563 };
564 if last.year() <= first {
565 return Some(YearsAired::One(first));
566 }
567 let year_ago = (today.year() - 1, today.month(), today.day());
570 if (last.year(), last.month(), last.day()) >= year_ago {
571 Some(YearsAired::Running(first))
572 } else {
573 Some(YearsAired::Between(first, last.year()))
574 }
575 }
576
577 pub fn years_label(&self, today: CalendarDate) -> Option<String> {
579 self.year_range(today).map(|years| years.to_string())
580 }
581}
582
583#[derive(Debug, Clone, PartialEq, Eq)]
585#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
586pub enum Caption {
587 Year(u16),
589 Years(YearsAired),
591 Show(String),
593 Episode {
595 show: Option<String>,
596 season: u32,
597 episode: u32,
598 },
599 Album {
601 artist: Option<String>,
602 year: Option<u16>,
603 },
604 Length(Duration),
606}
607
608impl Item {
609 pub fn duration(&self) -> Option<Duration> {
611 match self {
612 Item::Movie(m) => m.duration,
613 Item::Episode(e) => e.duration,
614 Item::Track(t) => t.duration,
615 _ => None,
616 }
617 }
618
619 pub fn merge(&self) -> Option<&MergeFacts> {
622 match self {
623 Item::Movie(m) => Some(&m.merge),
624 Item::Show(s) => Some(&s.merge),
625 Item::Episode(e) => Some(&e.merge),
626 Item::Artist(a) => Some(&a.merge),
627 Item::Album(a) => Some(&a.merge),
628 Item::Track(t) => Some(&t.merge),
629 Item::Season(_) => None,
630 }
631 }
632
633 pub fn merge_mut(&mut self) -> Option<&mut MergeFacts> {
635 match self {
636 Item::Movie(m) => Some(&mut m.merge),
637 Item::Show(s) => Some(&mut s.merge),
638 Item::Episode(e) => Some(&mut e.merge),
639 Item::Artist(a) => Some(&mut a.merge),
640 Item::Album(a) => Some(&mut a.merge),
641 Item::Track(t) => Some(&mut t.merge),
642 Item::Season(_) => None,
643 }
644 }
645}
646
647impl Item {
648 pub fn caption_parts(&self, today: CalendarDate) -> Option<Caption> {
651 match self {
652 Item::Movie(m) => m.year.map(Caption::Year),
653 Item::Show(s) => s.year_range(today).map(Caption::Years),
654 Item::Season(s) => s.show_title.clone().map(Caption::Show),
655 Item::Episode(e) => Some(Caption::Episode {
656 show: e.show_title.clone(),
657 season: e.season,
658 episode: e.episode,
659 }),
660 Item::Album(a) => {
661 (a.artist_name.is_some() || a.year.is_some()).then(|| Caption::Album {
662 artist: a.artist_name.clone(),
663 year: a.year,
664 })
665 }
666 Item::Track(t) => t.duration.map(Caption::Length),
667 Item::Artist(_) => None,
668 }
669 }
670
671 pub fn id(&self) -> &MediaId {
672 match self {
673 Item::Movie(m) => &m.id,
674 Item::Show(s) => &s.id,
675 Item::Season(s) => &s.id,
676 Item::Episode(e) => &e.id,
677 Item::Artist(a) => &a.id,
678 Item::Album(a) => &a.id,
679 Item::Track(t) => &t.id,
680 }
681 }
682
683 pub fn title(&self) -> &str {
686 match self {
687 Item::Movie(m) => &m.title,
688 Item::Show(s) => &s.title,
689 Item::Season(s) => &s.title,
690 Item::Episode(e) => &e.title,
691 Item::Artist(a) => &a.name,
692 Item::Album(a) => &a.title,
693 Item::Track(t) => &t.title,
694 }
695 }
696
697 pub fn artwork(&self) -> &[Artwork] {
699 match self {
700 Item::Movie(m) => &m.artwork,
701 Item::Show(s) => &s.artwork,
702 Item::Season(s) => &s.artwork,
703 Item::Episode(e) => &e.artwork,
704 Item::Artist(a) => &a.artwork,
705 Item::Album(a) => &a.artwork,
706 Item::Track(t) => &t.artwork,
707 }
708 }
709
710 pub fn artwork_of(&self, kind: ArtworkKind) -> Option<&Artwork> {
712 self.artwork().iter().find(|a| a.kind == kind)
713 }
714
715 pub fn playback(&self) -> Option<&PlaybackState> {
718 match self {
719 Item::Movie(m) => Some(&m.playback),
720 Item::Episode(e) => Some(&e.playback),
721 Item::Track(t) => Some(&t.playback),
722 _ => None,
723 }
724 }
725
726 pub fn is_watched(&self) -> bool {
728 self.playback().is_some_and(|p| p.watched)
729 }
730
731 pub fn resume_position(&self) -> Option<Duration> {
733 self.playback().and_then(|p| p.position)
734 }
735
736 pub fn resume_from(&self) -> Option<Duration> {
738 self.playback().and_then(PlaybackState::resume_from)
739 }
740
741 pub fn progress(&self) -> Option<Progress> {
744 Some(self.playback()?.progress(self.duration()))
745 }
746}
747
748#[cfg(test)]
749mod tests {
750 use std::fmt::Debug;
751 use std::time::UNIX_EPOCH;
752
753 use serde::de::DeserializeOwned;
754
755 use super::*;
756 use crate::id::{MediaKind, Namespace};
757
758 fn round_trip<T: Serialize + DeserializeOwned + PartialEq + Debug>(value: T) {
759 let json = serde_json::to_string(&value).unwrap();
760 assert_eq!(serde_json::from_str::<T>(&json).unwrap(), value, "{json}");
761 }
762
763 fn media(kind: MediaKind, key: &str) -> MediaId {
764 MediaId::new(Namespace::Plex, kind, key).unwrap()
765 }
766
767 fn poster() -> Vec<Artwork> {
768 vec![Artwork {
769 id: ArtworkId::new(Namespace::Plex, "/library/metadata/1/thumb/9").unwrap(),
770 kind: ArtworkKind::Poster,
771 }]
772 }
773
774 fn halfway() -> PlaybackState {
775 PlaybackState {
776 position: Some(Duration::from_millis(2_220_500)),
777 watched: false,
778 last_viewed_at: None,
779 play_count: 0,
780 last_played_at: None,
781 }
782 }
783
784 fn ripley() -> CastMember {
785 CastMember {
786 id: PersonId::new(Namespace::Plex, "actor-13").unwrap(),
787 name: "Sigourney Weaver".into(),
788 role: PersonRole::Actor,
789 character: Some("Ellen Ripley".into()),
790 photo: Some(ArtworkId::new(Namespace::Plex, "/people/1/a/b.jpg").unwrap()),
791 }
792 }
793
794 fn scott() -> CastMember {
795 CastMember {
796 id: PersonId::new(Namespace::Plex, "director-7").unwrap(),
797 name: "Ridley Scott".into(),
798 role: PersonRole::Director,
799 character: None,
800 photo: None,
801 }
802 }
803
804 #[test]
805 fn a_cast_member_is_their_person_id_role_and_photo_on_the_wire() {
806 assert_eq!(
807 serde_json::to_value(ripley()).unwrap(),
808 serde_json::json!({
809 "id": "plex:actor-13",
810 "name": "Sigourney Weaver",
811 "role": "actor",
812 "character": "Ellen Ripley",
813 "photo": "plex:/people/1/a/b.jpg",
814 })
815 );
816 round_trip(ripley());
817 round_trip(scott());
818 }
819
820 #[test]
822 fn a_cast_member_s_character_and_photo_are_required() {
823 crate::test_support::assert_each_required(&scott(), &["character", "photo"]);
824 }
825
826 #[test]
829 fn items_from_a_server_without_cast_or_dates_still_decode() {
830 let movie = Movie {
831 merge: Default::default(),
832 id: media(MediaKind::Movie, "10"),
833 title: "Alien".into(),
834 year: Some(1979),
835 release_date: CalendarDate::new(1979, 5, 25),
836 summary: None,
837 content_rating: None,
838 duration: None,
839 cast: vec![ripley()],
840 artwork: Vec::new(),
841 playback: PlaybackState::default(),
842 };
843 let mut json = serde_json::to_value(&movie).unwrap();
844 assert_eq!(json["release_date"], "1979-05-25");
845 let object = json.as_object_mut().unwrap();
846 object.remove("release_date");
847 object.remove("cast");
848 let older: Movie = serde_json::from_value(json).unwrap();
849 assert_eq!((older.release_date, older.cast), (None, Vec::new()));
850
851 let show = Show {
852 merge: Default::default(),
853 id: media(MediaKind::Show, "20"),
854 title: "The Expanse".into(),
855 year: Some(2015),
856 summary: None,
857 content_rating: None,
858 season_count: None,
859 genres: Vec::new(),
860 last_aired: CalendarDate::new(2022, 4, 8),
861 cast: vec![ripley()],
862 artwork: Vec::new(),
863 };
864 let mut json = serde_json::to_value(&show).unwrap();
865 assert_eq!(json["last_aired"], "2022-04-08");
866 let object = json.as_object_mut().unwrap();
867 object.remove("last_aired");
868 object.remove("cast");
869 let older: Show = serde_json::from_value(json).unwrap();
870 assert_eq!((older.last_aired, older.cast), (None, Vec::new()));
871
872 let episode = Episode {
873 merge: Default::default(),
874 id: media(MediaKind::Episode, "22"),
875 show_id: media(MediaKind::Show, "20"),
876 show_title: None,
877 season_id: media(MediaKind::Season, "21"),
878 season: 1,
879 episode: 1,
880 title: "Dulcinea".into(),
881 summary: None,
882 content_rating: None,
883 year: None,
884 air_date: None,
885 duration: None,
886 cast: vec![scott()],
887 artwork: Vec::new(),
888 playback: PlaybackState::default(),
889 };
890 let mut json = serde_json::to_value(&episode).unwrap();
891 json.as_object_mut().unwrap().remove("cast");
892 let older: Episode = serde_json::from_value(json).unwrap();
893 assert_eq!(older.cast, Vec::new());
894 }
895
896 #[test]
897 fn a_track_s_format_is_plain_numbers_on_the_wire() {
898 let track = Track {
899 merge: Default::default(),
900 id: media(MediaKind::Track, "224630"),
901 album_id: media(MediaKind::Album, "224629"),
902 artist_id: media(MediaKind::Artist, "224303"),
903 artist_name: None,
904 album_title: None,
905 title: "Catch".into(),
906 track: Some(1),
907 disc: Some(1),
908 album_track_count: Some(3),
909 codec: Some(AudioCodec::Flac),
910 bit_depth: Some(24),
911 sample_rate: Some(96_000),
912 duration: None,
913 artwork: Vec::new(),
914 playback: PlaybackState::default(),
915 };
916 let json = serde_json::to_value(&track).unwrap();
917 assert_eq!(
918 (
919 &json["codec"],
920 &json["bit_depth"],
921 &json["sample_rate"],
922 &json["album_track_count"]
923 ),
924 (
925 &serde_json::json!("flac"),
926 &serde_json::json!(24),
927 &serde_json::json!(96_000),
928 &serde_json::json!(3)
929 )
930 );
931 }
932
933 #[test]
934 fn library_kinds_are_snake_case_on_the_wire() {
935 assert_eq!(
936 serde_json::to_string(&LibraryKind::Movies).unwrap(),
937 r#""movies""#
938 );
939 }
940
941 #[test]
942 fn an_item_carries_its_kind_on_the_wire() {
943 let item = Item::Show(Show {
944 merge: Default::default(),
945 id: media(MediaKind::Show, "20"),
946 title: "The Expanse".into(),
947 year: None,
948 summary: None,
949 content_rating: None,
950 season_count: None,
951 genres: Vec::new(),
952 last_aired: None,
953 cast: Vec::new(),
954 artwork: Vec::new(),
955 });
956 let json = serde_json::to_value(&item).unwrap();
957 assert_eq!(json["kind"], "show");
958 assert_eq!(json["id"], "plex:show:20");
959 round_trip(item);
960 }
961
962 #[test]
965 fn a_parent_s_name_left_out_is_refused() {
966 let season = Season {
967 id: media(MediaKind::Season, "21"),
968 show_id: media(MediaKind::Show, "20"),
969 show_title: None,
970 season: 1,
971 title: "Season 1".into(),
972 artwork: Vec::new(),
973 };
974 crate::test_support::assert_each_required(&season, &["show_title"]);
975 let episode = Episode {
976 merge: Default::default(),
977 id: media(MediaKind::Episode, "22"),
978 show_id: media(MediaKind::Show, "20"),
979 show_title: None,
980 season_id: media(MediaKind::Season, "21"),
981 season: 1,
982 episode: 1,
983 title: "Dulcinea".into(),
984 summary: None,
985 content_rating: None,
986 year: None,
987 air_date: None,
988 duration: None,
989 cast: Vec::new(),
990 artwork: Vec::new(),
991 playback: PlaybackState::default(),
992 };
993 crate::test_support::assert_each_required(&episode, &["show_title"]);
994 let album = Album {
995 merge: Default::default(),
996 id: media(MediaKind::Album, "30"),
997 artist_id: media(MediaKind::Artist, "31"),
998 artist_name: None,
999 title: "Moon Safari".into(),
1000 year: None,
1001 track_count: None,
1002 artwork: Vec::new(),
1003 };
1004 crate::test_support::assert_each_required(&album, &["artist_name"]);
1005 round_trip(album);
1007 }
1008
1009 #[test]
1010 fn an_episode_from_a_server_without_air_dates_still_decodes() {
1011 let episode = Episode {
1012 merge: Default::default(),
1013 id: media(MediaKind::Episode, "22"),
1014 show_id: media(MediaKind::Show, "20"),
1015 show_title: None,
1016 season_id: media(MediaKind::Season, "21"),
1017 season: 1,
1018 episode: 1,
1019 title: "Dulcinea".into(),
1020 summary: None,
1021 content_rating: None,
1022 year: Some(2015),
1023 air_date: CalendarDate::new(2015, 11, 23),
1024 duration: None,
1025 cast: Vec::new(),
1026 artwork: Vec::new(),
1027 playback: PlaybackState::default(),
1028 };
1029 let mut json = serde_json::to_value(&episode).unwrap();
1030 assert_eq!(json["air_date"], "2015-11-23");
1031 let object = json.as_object_mut().unwrap();
1032 object.remove("year");
1033 object.remove("air_date");
1034 let older: Episode = serde_json::from_value(json).unwrap();
1035 assert_eq!((older.year, older.air_date), (None, None));
1036 }
1037
1038 fn years(year: Option<u16>, last_aired: Option<(u16, u8, u8)>) -> Option<String> {
1040 let show = Show {
1041 merge: Default::default(),
1042 id: media(MediaKind::Show, "20"),
1043 title: "Andor".into(),
1044 year,
1045 summary: None,
1046 content_rating: None,
1047 season_count: None,
1048 genres: Vec::new(),
1049 last_aired: last_aired.and_then(|(y, m, d)| CalendarDate::new(y, m, d)),
1050 cast: Vec::new(),
1051 artwork: Vec::new(),
1052 };
1053 show.years_label(CalendarDate::new(2026, 10, 14).unwrap())
1054 }
1055
1056 #[test]
1057 fn a_show_s_years_come_in_parts() {
1058 let show = |last: (u16, u8, u8)| Show {
1059 merge: Default::default(),
1060 id: media(MediaKind::Show, "20"),
1061 title: "Andor".into(),
1062 year: Some(2022),
1063 summary: None,
1064 content_rating: None,
1065 season_count: None,
1066 genres: Vec::new(),
1067 last_aired: CalendarDate::new(last.0, last.1, last.2),
1068 cast: Vec::new(),
1069 artwork: Vec::new(),
1070 };
1071 let today = CalendarDate::new(2026, 10, 14).unwrap();
1072 assert_eq!(
1073 show((2025, 10, 14)).year_range(today),
1074 Some(YearsAired::Running(2022))
1075 );
1076 assert_eq!(
1077 show((2025, 10, 13)).year_range(today),
1078 Some(YearsAired::Between(2022, 2025))
1079 );
1080 assert_eq!(
1081 Item::Show(show((2022, 5, 1))).caption_parts(today),
1082 Some(Caption::Years(YearsAired::One(2022)))
1083 );
1084 }
1085
1086 #[test]
1087 fn a_show_with_no_air_date_shows_its_first_year() {
1088 assert_eq!(years(Some(2022), None), Some("2022".into()));
1089 assert_eq!(years(None, None), None);
1090 }
1091
1092 #[test]
1093 fn a_show_last_aired_in_its_first_year_shows_that_year() {
1094 assert_eq!(years(Some(2022), Some((2022, 12, 1))), Some("2022".into()));
1095 }
1096
1097 #[test]
1098 fn a_show_aired_in_the_last_twelve_months_is_an_open_range() {
1099 assert_eq!(
1100 years(Some(2022), Some((2025, 10, 14))),
1101 Some("2022\u{2013}".into())
1102 );
1103 }
1104
1105 #[test]
1106 fn a_show_last_aired_over_a_year_ago_shows_both_years() {
1107 assert_eq!(
1108 years(Some(2022), Some((2025, 10, 13))),
1109 Some("2022\u{2013}2025".into())
1110 );
1111 }
1112
1113 #[test]
1114 fn a_show_with_no_first_year_shows_when_it_last_aired() {
1115 assert_eq!(years(None, Some((2019, 3, 2))), Some("2019".into()));
1116 }
1117
1118 #[test]
1119 fn every_model_type_round_trips() {
1120 round_trip(Library {
1121 id: LibraryId::new(Namespace::Plex, "1").unwrap(),
1122 title: "Movies".into(),
1123 kind: LibraryKind::Movies,
1124 server: None,
1125 });
1126 round_trip(Movie {
1127 merge: Default::default(),
1128 id: media(MediaKind::Movie, "10"),
1129 title: "Alien".into(),
1130 year: Some(1979),
1131 release_date: CalendarDate::new(1979, 5, 25),
1132 summary: Some("In space no one can hear you scream.".into()),
1133 content_rating: Some("R".into()),
1134 duration: Some(Duration::from_secs(7020)),
1135 cast: vec![ripley(), scott()],
1136 artwork: poster(),
1137 playback: halfway(),
1138 });
1139 round_trip(Show {
1140 merge: Default::default(),
1141 id: media(MediaKind::Show, "20"),
1142 title: "The Expanse".into(),
1143 year: Some(2015),
1144 summary: None,
1145 content_rating: Some("TV-14".into()),
1146 season_count: Some(6),
1147 genres: vec!["Science Fiction".into(), "Drama".into()],
1148 last_aired: CalendarDate::new(2022, 4, 8),
1149 cast: vec![ripley()],
1150 artwork: poster(),
1151 });
1152 round_trip(Season {
1153 id: media(MediaKind::Season, "21"),
1154 show_id: media(MediaKind::Show, "20"),
1155 show_title: Some("The Expanse".into()),
1156 season: 1,
1157 title: "Season 1".into(),
1158 artwork: Vec::new(),
1159 });
1160 round_trip(Episode {
1161 merge: Default::default(),
1162 id: media(MediaKind::Episode, "22"),
1163 show_id: media(MediaKind::Show, "20"),
1164 show_title: Some("The Expanse".into()),
1165 season_id: media(MediaKind::Season, "21"),
1166 season: 1,
1167 episode: 1,
1168 title: "Dulcinea".into(),
1169 summary: None,
1170 content_rating: Some("TV-14".into()),
1171 year: Some(2015),
1172 air_date: CalendarDate::new(2015, 11, 23),
1173 duration: Some(Duration::from_secs(2640)),
1174 cast: vec![scott()],
1175 artwork: poster(),
1176 playback: PlaybackState::default(),
1177 });
1178 round_trip(Artist {
1179 merge: Default::default(),
1180 id: media(MediaKind::Artist, "30"),
1181 name: "Boards of Canada".into(),
1182 summary: None,
1183 artwork: poster(),
1184 });
1185 round_trip(Album {
1186 merge: Default::default(),
1187 id: media(MediaKind::Album, "31"),
1188 artist_id: media(MediaKind::Artist, "30"),
1189 artist_name: Some("Boards of Canada".into()),
1190 title: "Music Has the Right to Children".into(),
1191 year: Some(1998),
1192 track_count: Some(18),
1193 artwork: poster(),
1194 });
1195 round_trip(Track {
1196 merge: Default::default(),
1197 id: media(MediaKind::Track, "32"),
1198 album_id: media(MediaKind::Album, "31"),
1199 artist_id: media(MediaKind::Artist, "30"),
1200 artist_name: Some("Boards of Canada".into()),
1201 album_title: Some("Music Has the Right to Children".into()),
1202 title: "Roygbiv".into(),
1203 track: Some(10),
1204 disc: Some(1),
1205 album_track_count: Some(18),
1206 codec: Some(AudioCodec::Flac),
1207 bit_depth: Some(16),
1208 sample_rate: Some(44_100),
1209 duration: Some(Duration::from_secs(151)),
1210 artwork: poster(),
1211 playback: PlaybackState {
1212 position: None,
1213 watched: true,
1214 last_viewed_at: None,
1215 play_count: 0,
1216 last_played_at: None,
1217 },
1218 });
1219 }
1220
1221 fn alien(playback: PlaybackState, duration: Option<Duration>) -> Item {
1222 Item::Movie(Movie {
1223 merge: Default::default(),
1224 id: media(MediaKind::Movie, "10"),
1225 title: "Alien".into(),
1226 year: Some(1979),
1227 release_date: None,
1228 summary: None,
1229 content_rating: None,
1230 duration,
1231 cast: Vec::new(),
1232 artwork: Vec::new(),
1233 playback,
1234 })
1235 }
1236
1237 #[test]
1241 fn markers_and_watch_times_keep_their_wire_form() {
1242 let marker = Marker {
1243 kind: MarkerKind::Intro,
1244 start: Duration::from_millis(258_865),
1245 end: Duration::from_millis(319_865),
1246 to_end: false,
1247 };
1248 let state = PlaybackState {
1249 last_viewed_at: Some(UNIX_EPOCH + Duration::from_secs(1_761_700_000)),
1250 play_count: 2,
1251 last_played_at: Some(UNIX_EPOCH + Duration::from_secs(1_761_600_000)),
1252 ..PlaybackState::default()
1253 };
1254 assert_eq!(
1255 (
1256 serde_json::to_value(marker).unwrap(),
1257 serde_json::to_value(&state).unwrap(),
1258 serde_json::to_value(halfway()).unwrap()["position"].clone(),
1259 ),
1260 (
1261 serde_json::json!({
1262 "kind": "intro", "start_ms": 258_865, "end_ms": 319_865, "to_end": false
1263 }),
1264 serde_json::json!({
1265 "position": null, "watched": false, "last_viewed_at": 1_761_700_000,
1266 "play_count": 2, "last_played_at": 1_761_600_000
1267 }),
1268 serde_json::json!(2_220_500),
1269 )
1270 );
1271 round_trip(marker);
1272 round_trip(state);
1273 }
1274
1275 #[test]
1276 fn a_marker_list_leaves_out_kinds_this_build_does_not_know() {
1277 let listed: Markers = serde_json::from_value(serde_json::json!([
1278 { "kind": "recap", "start_ms": 0, "end_ms": 60_000, "to_end": false },
1279 { "kind": "intro", "start_ms": 60_000, "end_ms": 90_000, "to_end": false },
1280 ]))
1281 .unwrap();
1282 let intro = Marker {
1283 kind: MarkerKind::Intro,
1284 start: Duration::from_millis(60_000),
1285 end: Duration::from_millis(90_000),
1286 to_end: false,
1287 };
1288 assert_eq!(*listed, [intro]);
1289 assert_eq!(
1290 serde_json::to_value(&listed).unwrap()[0]["start_ms"],
1291 60_000
1292 );
1293 }
1294
1295 #[test]
1296 fn an_item_s_artwork_of_a_kind_is_its_first_one() {
1297 let art = |kind, path: &str| Artwork {
1298 id: ArtworkId::new(Namespace::Plex, path).unwrap(),
1299 kind,
1300 };
1301 let Item::Movie(mut movie) = alien(PlaybackState::default(), None) else {
1302 unreachable!()
1303 };
1304 movie.artwork = vec![
1305 art(ArtworkKind::Background, "/bg"),
1306 art(ArtworkKind::Poster, "/p1"),
1307 art(ArtworkKind::Poster, "/p2"),
1308 ];
1309 let item = Item::Movie(movie);
1310 assert_eq!(
1311 [
1312 ArtworkKind::Poster,
1313 ArtworkKind::Background,
1314 ArtworkKind::Thumb
1315 ]
1316 .map(|kind| item.artwork_of(kind).cloned()),
1317 [
1318 Some(art(ArtworkKind::Poster, "/p1")),
1319 Some(art(ArtworkKind::Background, "/bg")),
1320 None
1321 ]
1322 );
1323 }
1324
1325 fn at(secs: u64, watched: bool) -> PlaybackState {
1326 PlaybackState {
1327 position: Some(Duration::from_secs(secs)),
1328 watched,
1329 ..PlaybackState::default()
1330 }
1331 }
1332
1333 #[test]
1334 fn a_film_stopped_part_way_resumes_where_it_stopped() {
1335 assert_eq!(at(600, false).resume_from(), Some(Duration::from_secs(600)));
1336 }
1337
1338 #[test]
1339 fn a_watched_film_plays_from_the_start() {
1340 assert_eq!(at(600, true).resume_from(), None);
1341 }
1342
1343 #[test]
1344 fn a_film_never_begun_plays_from_the_start() {
1345 assert_eq!(PlaybackState::default().resume_from(), None);
1346 assert_eq!(at(0, false).resume_from(), None);
1347 }
1348
1349 #[test]
1350 fn progress_is_the_fraction_watched_and_the_time_left() {
1351 let progress = at(1_500, false).progress(Some(Duration::from_secs(6_000)));
1352 assert_eq!(
1353 progress,
1354 Progress {
1355 position: Duration::from_secs(1_500),
1356 remaining: Some(Duration::from_secs(4_500)),
1357 fraction: Some(0.25),
1358 watched: false,
1359 }
1360 );
1361 }
1362
1363 #[test]
1364 fn progress_past_the_length_is_whole_with_nothing_left() {
1365 let progress = at(7_000, true).progress(Some(Duration::from_secs(6_000)));
1366 assert_eq!(
1367 (progress.fraction, progress.remaining, progress.watched),
1368 (Some(1.0), Some(Duration::ZERO), true)
1369 );
1370 }
1371
1372 #[test]
1373 fn progress_with_no_length_has_no_fraction() {
1374 for length in [None, Some(Duration::ZERO)] {
1375 let progress = at(60, false).progress(length);
1376 assert_eq!((progress.fraction, progress.remaining), (None, None));
1377 }
1378 }
1379
1380 #[test]
1381 fn an_item_answers_from_its_own_playback() {
1382 let item = alien(at(600, false), Some(Duration::from_secs(1_200)));
1383 assert_eq!(item.title(), "Alien");
1384 assert!(!item.is_watched());
1385 assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
1386 assert_eq!(item.resume_from(), Some(Duration::from_secs(600)));
1387 assert_eq!(item.progress().and_then(|p| p.fraction), Some(0.5));
1388 }
1389
1390 #[test]
1391 fn a_watched_item_keeps_its_position_but_resumes_from_the_start() {
1392 let item = alien(at(600, true), None);
1393 assert!(item.is_watched());
1394 assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
1395 assert_eq!(item.resume_from(), None);
1396 }
1397
1398 #[test]
1399 fn an_artist_has_a_title_but_no_progress() {
1400 let show = Item::Artist(Artist {
1401 merge: Default::default(),
1402 id: media(MediaKind::Artist, "30"),
1403 name: "Daft Punk".into(),
1404 summary: None,
1405 artwork: Vec::new(),
1406 });
1407 assert_eq!(show.title(), "Daft Punk");
1408 assert_eq!(show.progress(), None);
1409 assert!(!show.is_watched());
1410 assert_eq!(show.resume_from(), None);
1411 }
1412}