1use std::time::Duration;
8
9use serde::{Deserialize, Serialize};
10
11use crate::codec::AudioCodec;
12use crate::date::CalendarDate;
13use crate::duration_ms;
14use crate::id::{ArtworkId, LibraryId, MediaId, PersonId};
15use crate::search::PersonRole;
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 = "duration_ms::option")]
81 pub position: Option<Duration>,
82 pub watched: bool,
83 #[serde(default)]
92 pub last_viewed_at: Option<i64>,
93 #[serde(default)]
97 pub play_count: u32,
98 #[serde(default)]
102 pub last_played_at: Option<i64>,
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 = "duration_ms::option")]
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 = "duration_ms::option")]
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 = "duration_ms::option")]
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 pub start_ms: u64,
360 pub end_ms: u64,
363 pub to_end: bool,
366}
367
368#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
371#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
372#[serde(tag = "kind", rename_all = "snake_case")]
373pub enum Item {
374 Movie(Movie),
375 Show(Show),
376 Season(Season),
377 Episode(Episode),
378 Artist(Artist),
379 Album(Album),
380 Track(Track),
381}
382
383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
385#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
386pub enum YearsAired {
387 One(u16),
389 Running(u16),
391 Between(u16, u16),
393}
394
395impl std::fmt::Display for YearsAired {
397 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
398 match self {
399 YearsAired::One(year) => write!(f, "{year}"),
400 YearsAired::Running(first) => write!(f, "{first}\u{2013}"),
401 YearsAired::Between(first, last) => write!(f, "{first}\u{2013}{last}"),
402 }
403 }
404}
405
406impl Show {
407 pub fn year_range(&self, today: CalendarDate) -> Option<YearsAired> {
413 let Some(last) = self.last_aired else {
414 return self.year.map(YearsAired::One);
415 };
416 let Some(first) = self.year else {
417 return Some(YearsAired::One(last.year()));
418 };
419 if last.year() <= first {
420 return Some(YearsAired::One(first));
421 }
422 let year_ago = (today.year() - 1, today.month(), today.day());
425 if (last.year(), last.month(), last.day()) >= year_ago {
426 Some(YearsAired::Running(first))
427 } else {
428 Some(YearsAired::Between(first, last.year()))
429 }
430 }
431
432 pub fn years_label(&self, today: CalendarDate) -> Option<String> {
434 self.year_range(today).map(|years| years.to_string())
435 }
436}
437
438#[derive(Debug, Clone, PartialEq, Eq)]
440#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
441pub enum Caption {
442 Year(u16),
444 Years(YearsAired),
446 Show(String),
448 Episode {
450 show: Option<String>,
451 season: u32,
452 episode: u32,
453 },
454 Album {
456 artist: Option<String>,
457 year: Option<u16>,
458 },
459 Length(Duration),
461}
462
463impl Item {
464 pub fn caption_parts(&self, today: CalendarDate) -> Option<Caption> {
467 match self {
468 Item::Movie(m) => m.year.map(Caption::Year),
469 Item::Show(s) => s.year_range(today).map(Caption::Years),
470 Item::Season(s) => s.show_title.clone().map(Caption::Show),
471 Item::Episode(e) => Some(Caption::Episode {
472 show: e.show_title.clone(),
473 season: e.season,
474 episode: e.episode,
475 }),
476 Item::Album(a) => {
477 (a.artist_name.is_some() || a.year.is_some()).then(|| Caption::Album {
478 artist: a.artist_name.clone(),
479 year: a.year,
480 })
481 }
482 Item::Track(t) => t.duration.map(Caption::Length),
483 Item::Artist(_) => None,
484 }
485 }
486
487 pub fn id(&self) -> &MediaId {
488 match self {
489 Item::Movie(m) => &m.id,
490 Item::Show(s) => &s.id,
491 Item::Season(s) => &s.id,
492 Item::Episode(e) => &e.id,
493 Item::Artist(a) => &a.id,
494 Item::Album(a) => &a.id,
495 Item::Track(t) => &t.id,
496 }
497 }
498
499 pub fn title(&self) -> &str {
502 match self {
503 Item::Movie(m) => &m.title,
504 Item::Show(s) => &s.title,
505 Item::Season(s) => &s.title,
506 Item::Episode(e) => &e.title,
507 Item::Artist(a) => &a.name,
508 Item::Album(a) => &a.title,
509 Item::Track(t) => &t.title,
510 }
511 }
512
513 pub fn playback(&self) -> Option<&PlaybackState> {
516 match self {
517 Item::Movie(m) => Some(&m.playback),
518 Item::Episode(e) => Some(&e.playback),
519 Item::Track(t) => Some(&t.playback),
520 _ => None,
521 }
522 }
523
524 pub fn duration(&self) -> Option<Duration> {
526 match self {
527 Item::Movie(m) => m.duration,
528 Item::Episode(e) => e.duration,
529 Item::Track(t) => t.duration,
530 _ => None,
531 }
532 }
533
534 pub fn is_watched(&self) -> bool {
536 self.playback().is_some_and(|p| p.watched)
537 }
538
539 pub fn resume_position(&self) -> Option<Duration> {
541 self.playback().and_then(|p| p.position)
542 }
543
544 pub fn resume_from(&self) -> Option<Duration> {
546 self.playback().and_then(PlaybackState::resume_from)
547 }
548
549 pub fn progress(&self) -> Option<Progress> {
552 Some(self.playback()?.progress(self.duration()))
553 }
554}
555
556#[cfg(test)]
557mod tests {
558 use std::fmt::Debug;
559
560 use serde::de::DeserializeOwned;
561
562 use super::*;
563 use crate::id::{MediaKind, Namespace};
564
565 fn round_trip<T: Serialize + DeserializeOwned + PartialEq + Debug>(value: T) {
566 let json = serde_json::to_string(&value).unwrap();
567 assert_eq!(serde_json::from_str::<T>(&json).unwrap(), value, "{json}");
568 }
569
570 fn media(kind: MediaKind, key: &str) -> MediaId {
571 MediaId::new(Namespace::Plex, kind, key).unwrap()
572 }
573
574 fn poster() -> Vec<Artwork> {
575 vec![Artwork {
576 id: ArtworkId::new(Namespace::Plex, "/library/metadata/1/thumb/9").unwrap(),
577 kind: ArtworkKind::Poster,
578 }]
579 }
580
581 fn halfway() -> PlaybackState {
582 PlaybackState {
583 position: Some(Duration::from_millis(2_220_500)),
584 watched: false,
585 last_viewed_at: None,
586 play_count: 0,
587 last_played_at: None,
588 }
589 }
590
591 fn ripley() -> CastMember {
592 CastMember {
593 id: PersonId::new(Namespace::Plex, "actor-13").unwrap(),
594 name: "Sigourney Weaver".into(),
595 role: PersonRole::Actor,
596 character: Some("Ellen Ripley".into()),
597 photo: Some(ArtworkId::new(Namespace::Plex, "/people/1/a/b.jpg").unwrap()),
598 }
599 }
600
601 fn scott() -> CastMember {
602 CastMember {
603 id: PersonId::new(Namespace::Plex, "director-7").unwrap(),
604 name: "Ridley Scott".into(),
605 role: PersonRole::Director,
606 character: None,
607 photo: None,
608 }
609 }
610
611 #[test]
612 fn a_cast_member_is_their_person_id_role_and_photo_on_the_wire() {
613 assert_eq!(
614 serde_json::to_value(ripley()).unwrap(),
615 serde_json::json!({
616 "id": "plex:actor-13",
617 "name": "Sigourney Weaver",
618 "role": "actor",
619 "character": "Ellen Ripley",
620 "photo": "plex:/people/1/a/b.jpg",
621 })
622 );
623 round_trip(ripley());
624 round_trip(scott());
625 }
626
627 #[test]
629 fn a_cast_member_s_character_and_photo_are_required() {
630 crate::test_support::assert_each_required(&scott(), &["character", "photo"]);
631 }
632
633 #[test]
636 fn items_from_a_server_without_cast_or_dates_still_decode() {
637 let movie = Movie {
638 id: media(MediaKind::Movie, "10"),
639 title: "Alien".into(),
640 year: Some(1979),
641 release_date: CalendarDate::new(1979, 5, 25),
642 summary: None,
643 content_rating: None,
644 duration: None,
645 cast: vec![ripley()],
646 artwork: Vec::new(),
647 playback: PlaybackState::default(),
648 };
649 let mut json = serde_json::to_value(&movie).unwrap();
650 assert_eq!(json["release_date"], "1979-05-25");
651 let object = json.as_object_mut().unwrap();
652 object.remove("release_date");
653 object.remove("cast");
654 let older: Movie = serde_json::from_value(json).unwrap();
655 assert_eq!((older.release_date, older.cast), (None, Vec::new()));
656
657 let show = Show {
658 id: media(MediaKind::Show, "20"),
659 title: "The Expanse".into(),
660 year: Some(2015),
661 summary: None,
662 content_rating: None,
663 season_count: None,
664 genres: Vec::new(),
665 last_aired: CalendarDate::new(2022, 4, 8),
666 cast: vec![ripley()],
667 artwork: Vec::new(),
668 };
669 let mut json = serde_json::to_value(&show).unwrap();
670 assert_eq!(json["last_aired"], "2022-04-08");
671 let object = json.as_object_mut().unwrap();
672 object.remove("last_aired");
673 object.remove("cast");
674 let older: Show = serde_json::from_value(json).unwrap();
675 assert_eq!((older.last_aired, older.cast), (None, Vec::new()));
676
677 let episode = Episode {
678 id: media(MediaKind::Episode, "22"),
679 show_id: media(MediaKind::Show, "20"),
680 show_title: None,
681 season_id: media(MediaKind::Season, "21"),
682 season: 1,
683 episode: 1,
684 title: "Dulcinea".into(),
685 summary: None,
686 content_rating: None,
687 year: None,
688 air_date: None,
689 duration: None,
690 cast: vec![scott()],
691 artwork: Vec::new(),
692 playback: PlaybackState::default(),
693 };
694 let mut json = serde_json::to_value(&episode).unwrap();
695 json.as_object_mut().unwrap().remove("cast");
696 let older: Episode = serde_json::from_value(json).unwrap();
697 assert_eq!(older.cast, Vec::new());
698 }
699
700 #[test]
701 fn durations_are_whole_milliseconds_on_the_wire() {
702 let json = serde_json::to_value(halfway()).unwrap();
703 assert_eq!(json["position"], 2_220_500);
704 }
705
706 #[test]
707 fn an_unstarted_item_has_a_null_position() {
708 let json = serde_json::to_value(PlaybackState::default()).unwrap();
709 assert!(json["position"].is_null());
710 }
711
712 #[test]
713 fn a_track_s_format_is_plain_numbers_on_the_wire() {
714 let track = Track {
715 id: media(MediaKind::Track, "224630"),
716 album_id: media(MediaKind::Album, "224629"),
717 artist_id: media(MediaKind::Artist, "224303"),
718 artist_name: None,
719 album_title: None,
720 title: "Catch".into(),
721 track: Some(1),
722 disc: Some(1),
723 album_track_count: Some(3),
724 codec: Some(AudioCodec::Flac),
725 bit_depth: Some(24),
726 sample_rate: Some(96_000),
727 duration: None,
728 artwork: Vec::new(),
729 playback: PlaybackState::default(),
730 };
731 let json = serde_json::to_value(&track).unwrap();
732 assert_eq!(
733 (
734 &json["codec"],
735 &json["bit_depth"],
736 &json["sample_rate"],
737 &json["album_track_count"]
738 ),
739 (
740 &serde_json::json!("flac"),
741 &serde_json::json!(24),
742 &serde_json::json!(96_000),
743 &serde_json::json!(3)
744 )
745 );
746 }
747
748 #[test]
749 fn library_kinds_are_snake_case_on_the_wire() {
750 assert_eq!(
751 serde_json::to_string(&LibraryKind::Movies).unwrap(),
752 r#""movies""#
753 );
754 }
755
756 #[test]
757 fn a_marker_is_milliseconds_and_a_snake_case_kind_on_the_wire() {
758 let marker = Marker {
759 kind: MarkerKind::Credits,
760 start_ms: 2_662_962,
761 end_ms: 2_709_958,
762 to_end: true,
763 };
764 assert_eq!(
765 serde_json::to_value(marker).unwrap(),
766 serde_json::json!({
767 "kind": "credits",
768 "start_ms": 2_662_962,
769 "end_ms": 2_709_958,
770 "to_end": true,
771 })
772 );
773 round_trip(marker);
774 }
775
776 #[test]
777 fn a_marker_kind_from_a_newer_server_is_unknown() {
778 let marker: Marker = serde_json::from_str(
779 r#"{"kind": "recap", "start_ms": 0, "end_ms": 30000, "to_end": false}"#,
780 )
781 .unwrap();
782 assert_eq!(marker.kind, MarkerKind::Unknown);
783 }
784
785 #[test]
786 fn an_item_carries_its_kind_on_the_wire() {
787 let item = Item::Show(Show {
788 id: media(MediaKind::Show, "20"),
789 title: "The Expanse".into(),
790 year: None,
791 summary: None,
792 content_rating: None,
793 season_count: None,
794 genres: Vec::new(),
795 last_aired: None,
796 cast: Vec::new(),
797 artwork: Vec::new(),
798 });
799 let json = serde_json::to_value(&item).unwrap();
800 assert_eq!(json["kind"], "show");
801 assert_eq!(json["id"], "plex:show:20");
802 round_trip(item);
803 }
804
805 #[test]
808 fn a_parent_s_name_left_out_is_refused() {
809 let season = Season {
810 id: media(MediaKind::Season, "21"),
811 show_id: media(MediaKind::Show, "20"),
812 show_title: None,
813 season: 1,
814 title: "Season 1".into(),
815 artwork: Vec::new(),
816 };
817 crate::test_support::assert_each_required(&season, &["show_title"]);
818 let episode = Episode {
819 id: media(MediaKind::Episode, "22"),
820 show_id: media(MediaKind::Show, "20"),
821 show_title: None,
822 season_id: media(MediaKind::Season, "21"),
823 season: 1,
824 episode: 1,
825 title: "Dulcinea".into(),
826 summary: None,
827 content_rating: None,
828 year: None,
829 air_date: None,
830 duration: None,
831 cast: Vec::new(),
832 artwork: Vec::new(),
833 playback: PlaybackState::default(),
834 };
835 crate::test_support::assert_each_required(&episode, &["show_title"]);
836 let album = Album {
837 id: media(MediaKind::Album, "30"),
838 artist_id: media(MediaKind::Artist, "31"),
839 artist_name: None,
840 title: "Moon Safari".into(),
841 year: None,
842 track_count: None,
843 artwork: Vec::new(),
844 };
845 crate::test_support::assert_each_required(&album, &["artist_name"]);
846 round_trip(album);
848 }
849
850 #[test]
851 fn an_episode_from_a_server_without_air_dates_still_decodes() {
852 let episode = Episode {
853 id: media(MediaKind::Episode, "22"),
854 show_id: media(MediaKind::Show, "20"),
855 show_title: None,
856 season_id: media(MediaKind::Season, "21"),
857 season: 1,
858 episode: 1,
859 title: "Dulcinea".into(),
860 summary: None,
861 content_rating: None,
862 year: Some(2015),
863 air_date: CalendarDate::new(2015, 11, 23),
864 duration: None,
865 cast: Vec::new(),
866 artwork: Vec::new(),
867 playback: PlaybackState::default(),
868 };
869 let mut json = serde_json::to_value(&episode).unwrap();
870 assert_eq!(json["air_date"], "2015-11-23");
871 let object = json.as_object_mut().unwrap();
872 object.remove("year");
873 object.remove("air_date");
874 let older: Episode = serde_json::from_value(json).unwrap();
875 assert_eq!((older.year, older.air_date), (None, None));
876 }
877
878 fn years(year: Option<u16>, last_aired: Option<(u16, u8, u8)>) -> Option<String> {
880 let show = Show {
881 id: media(MediaKind::Show, "20"),
882 title: "Andor".into(),
883 year,
884 summary: None,
885 content_rating: None,
886 season_count: None,
887 genres: Vec::new(),
888 last_aired: last_aired.and_then(|(y, m, d)| CalendarDate::new(y, m, d)),
889 cast: Vec::new(),
890 artwork: Vec::new(),
891 };
892 show.years_label(CalendarDate::new(2026, 10, 14).unwrap())
893 }
894
895 #[test]
896 fn a_show_s_years_come_in_parts() {
897 let show = |last: (u16, u8, u8)| Show {
898 id: media(MediaKind::Show, "20"),
899 title: "Andor".into(),
900 year: Some(2022),
901 summary: None,
902 content_rating: None,
903 season_count: None,
904 genres: Vec::new(),
905 last_aired: CalendarDate::new(last.0, last.1, last.2),
906 cast: Vec::new(),
907 artwork: Vec::new(),
908 };
909 let today = CalendarDate::new(2026, 10, 14).unwrap();
910 assert_eq!(
911 show((2025, 10, 14)).year_range(today),
912 Some(YearsAired::Running(2022))
913 );
914 assert_eq!(
915 show((2025, 10, 13)).year_range(today),
916 Some(YearsAired::Between(2022, 2025))
917 );
918 assert_eq!(
919 Item::Show(show((2022, 5, 1))).caption_parts(today),
920 Some(Caption::Years(YearsAired::One(2022)))
921 );
922 }
923
924 #[test]
925 fn a_show_with_no_air_date_shows_its_first_year() {
926 assert_eq!(years(Some(2022), None), Some("2022".into()));
927 assert_eq!(years(None, None), None);
928 }
929
930 #[test]
931 fn a_show_last_aired_in_its_first_year_shows_that_year() {
932 assert_eq!(years(Some(2022), Some((2022, 12, 1))), Some("2022".into()));
933 }
934
935 #[test]
936 fn a_show_aired_in_the_last_twelve_months_is_an_open_range() {
937 assert_eq!(
938 years(Some(2022), Some((2025, 10, 14))),
939 Some("2022\u{2013}".into())
940 );
941 }
942
943 #[test]
944 fn a_show_last_aired_over_a_year_ago_shows_both_years() {
945 assert_eq!(
946 years(Some(2022), Some((2025, 10, 13))),
947 Some("2022\u{2013}2025".into())
948 );
949 }
950
951 #[test]
952 fn a_show_with_no_first_year_shows_when_it_last_aired() {
953 assert_eq!(years(None, Some((2019, 3, 2))), Some("2019".into()));
954 }
955
956 #[test]
957 fn every_model_type_round_trips() {
958 round_trip(Library {
959 id: LibraryId::new(Namespace::Plex, "1").unwrap(),
960 title: "Movies".into(),
961 kind: LibraryKind::Movies,
962 server: None,
963 });
964 round_trip(Movie {
965 id: media(MediaKind::Movie, "10"),
966 title: "Alien".into(),
967 year: Some(1979),
968 release_date: CalendarDate::new(1979, 5, 25),
969 summary: Some("In space no one can hear you scream.".into()),
970 content_rating: Some("R".into()),
971 duration: Some(Duration::from_secs(7020)),
972 cast: vec![ripley(), scott()],
973 artwork: poster(),
974 playback: halfway(),
975 });
976 round_trip(Show {
977 id: media(MediaKind::Show, "20"),
978 title: "The Expanse".into(),
979 year: Some(2015),
980 summary: None,
981 content_rating: Some("TV-14".into()),
982 season_count: Some(6),
983 genres: vec!["Science Fiction".into(), "Drama".into()],
984 last_aired: CalendarDate::new(2022, 4, 8),
985 cast: vec![ripley()],
986 artwork: poster(),
987 });
988 round_trip(Season {
989 id: media(MediaKind::Season, "21"),
990 show_id: media(MediaKind::Show, "20"),
991 show_title: Some("The Expanse".into()),
992 season: 1,
993 title: "Season 1".into(),
994 artwork: Vec::new(),
995 });
996 round_trip(Episode {
997 id: media(MediaKind::Episode, "22"),
998 show_id: media(MediaKind::Show, "20"),
999 show_title: Some("The Expanse".into()),
1000 season_id: media(MediaKind::Season, "21"),
1001 season: 1,
1002 episode: 1,
1003 title: "Dulcinea".into(),
1004 summary: None,
1005 content_rating: Some("TV-14".into()),
1006 year: Some(2015),
1007 air_date: CalendarDate::new(2015, 11, 23),
1008 duration: Some(Duration::from_secs(2640)),
1009 cast: vec![scott()],
1010 artwork: poster(),
1011 playback: PlaybackState::default(),
1012 });
1013 round_trip(Artist {
1014 id: media(MediaKind::Artist, "30"),
1015 name: "Boards of Canada".into(),
1016 summary: None,
1017 artwork: poster(),
1018 });
1019 round_trip(Album {
1020 id: media(MediaKind::Album, "31"),
1021 artist_id: media(MediaKind::Artist, "30"),
1022 artist_name: Some("Boards of Canada".into()),
1023 title: "Music Has the Right to Children".into(),
1024 year: Some(1998),
1025 track_count: Some(18),
1026 artwork: poster(),
1027 });
1028 round_trip(Track {
1029 id: media(MediaKind::Track, "32"),
1030 album_id: media(MediaKind::Album, "31"),
1031 artist_id: media(MediaKind::Artist, "30"),
1032 artist_name: Some("Boards of Canada".into()),
1033 album_title: Some("Music Has the Right to Children".into()),
1034 title: "Roygbiv".into(),
1035 track: Some(10),
1036 disc: Some(1),
1037 album_track_count: Some(18),
1038 codec: Some(AudioCodec::Flac),
1039 bit_depth: Some(16),
1040 sample_rate: Some(44_100),
1041 duration: Some(Duration::from_secs(151)),
1042 artwork: poster(),
1043 playback: PlaybackState {
1044 position: None,
1045 watched: true,
1046 last_viewed_at: None,
1047 play_count: 0,
1048 last_played_at: None,
1049 },
1050 });
1051 }
1052
1053 fn alien(playback: PlaybackState, duration: Option<Duration>) -> Item {
1054 Item::Movie(Movie {
1055 id: media(MediaKind::Movie, "10"),
1056 title: "Alien".into(),
1057 year: Some(1979),
1058 release_date: None,
1059 summary: None,
1060 content_rating: None,
1061 duration,
1062 cast: Vec::new(),
1063 artwork: Vec::new(),
1064 playback,
1065 })
1066 }
1067
1068 fn at(secs: u64, watched: bool) -> PlaybackState {
1069 PlaybackState {
1070 position: Some(Duration::from_secs(secs)),
1071 watched,
1072 ..PlaybackState::default()
1073 }
1074 }
1075
1076 #[test]
1077 fn a_film_stopped_part_way_resumes_where_it_stopped() {
1078 assert_eq!(at(600, false).resume_from(), Some(Duration::from_secs(600)));
1079 }
1080
1081 #[test]
1082 fn a_watched_film_plays_from_the_start() {
1083 assert_eq!(at(600, true).resume_from(), None);
1084 }
1085
1086 #[test]
1087 fn a_film_never_begun_plays_from_the_start() {
1088 assert_eq!(PlaybackState::default().resume_from(), None);
1089 assert_eq!(at(0, false).resume_from(), None);
1090 }
1091
1092 #[test]
1093 fn progress_is_the_fraction_watched_and_the_time_left() {
1094 let progress = at(1_500, false).progress(Some(Duration::from_secs(6_000)));
1095 assert_eq!(
1096 progress,
1097 Progress {
1098 position: Duration::from_secs(1_500),
1099 remaining: Some(Duration::from_secs(4_500)),
1100 fraction: Some(0.25),
1101 watched: false,
1102 }
1103 );
1104 }
1105
1106 #[test]
1107 fn progress_past_the_length_is_whole_with_nothing_left() {
1108 let progress = at(7_000, true).progress(Some(Duration::from_secs(6_000)));
1109 assert_eq!(
1110 (progress.fraction, progress.remaining, progress.watched),
1111 (Some(1.0), Some(Duration::ZERO), true)
1112 );
1113 }
1114
1115 #[test]
1116 fn progress_with_no_length_has_no_fraction() {
1117 for length in [None, Some(Duration::ZERO)] {
1118 let progress = at(60, false).progress(length);
1119 assert_eq!((progress.fraction, progress.remaining), (None, None));
1120 }
1121 }
1122
1123 #[test]
1124 fn an_item_answers_from_its_own_playback() {
1125 let item = alien(at(600, false), Some(Duration::from_secs(1_200)));
1126 assert_eq!(item.title(), "Alien");
1127 assert!(!item.is_watched());
1128 assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
1129 assert_eq!(item.resume_from(), Some(Duration::from_secs(600)));
1130 assert_eq!(item.progress().and_then(|p| p.fraction), Some(0.5));
1131 }
1132
1133 #[test]
1134 fn a_watched_item_keeps_its_position_but_resumes_from_the_start() {
1135 let item = alien(at(600, true), None);
1136 assert!(item.is_watched());
1137 assert_eq!(item.resume_position(), Some(Duration::from_secs(600)));
1138 assert_eq!(item.resume_from(), None);
1139 }
1140
1141 #[test]
1142 fn an_artist_has_a_title_but_no_progress() {
1143 let show = Item::Artist(Artist {
1144 id: media(MediaKind::Artist, "30"),
1145 name: "Daft Punk".into(),
1146 summary: None,
1147 artwork: Vec::new(),
1148 });
1149 assert_eq!(show.title(), "Daft Punk");
1150 assert_eq!(show.progress(), None);
1151 assert!(!show.is_watched());
1152 assert_eq!(show.resume_from(), None);
1153 }
1154}