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#[serde(rename_all = "snake_case")]
20pub enum LibraryKind {
21 Movies,
22 Shows,
23 Music,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct Library {
29 pub id: LibraryId,
30 pub title: String,
31 pub kind: LibraryKind,
32 #[serde(default, skip_serializing_if = "Option::is_none")]
37 pub server: Option<LibraryServer>,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
43pub struct LibraryServer {
44 pub server_id: String,
46 pub name: String,
48 pub online: bool,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
55#[serde(rename_all = "snake_case")]
56pub enum ArtworkKind {
57 Poster,
58 Background,
59 Thumb,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65pub struct Artwork {
66 pub id: ArtworkId,
67 pub kind: ArtworkKind,
68}
69
70#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
72pub struct PlaybackState {
73 #[serde(with = "duration_ms::option")]
75 pub position: Option<Duration>,
76 pub watched: bool,
77 #[serde(default)]
86 pub last_viewed_at: Option<i64>,
87 #[serde(default)]
91 pub play_count: u32,
92 #[serde(default)]
96 pub last_played_at: Option<i64>,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
100pub struct Movie {
101 pub id: MediaId,
102 pub title: String,
103 pub year: Option<u16>,
105 pub release_date: Option<CalendarDate>,
111 pub summary: Option<String>,
112 pub content_rating: Option<String>,
115 #[serde(with = "duration_ms::option")]
116 pub duration: Option<Duration>,
117 #[serde(default)]
119 pub cast: Vec<CastMember>,
120 pub artwork: Vec<Artwork>,
121 pub playback: PlaybackState,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125pub struct Show {
126 pub id: MediaId,
127 pub title: String,
128 pub year: Option<u16>,
129 pub summary: Option<String>,
130 pub content_rating: Option<String>,
133 pub season_count: Option<u32>,
136 pub genres: Vec<String>,
140 pub last_aired: Option<CalendarDate>,
151 #[serde(default)]
153 pub cast: Vec<CastMember>,
154 pub artwork: Vec<Artwork>,
155}
156
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158pub struct Season {
159 pub id: MediaId,
160 pub show_id: MediaId,
161 #[serde(deserialize_with = "crate::required::option")]
163 pub show_title: Option<String>,
164 pub season: u32,
166 pub title: String,
167 pub artwork: Vec<Artwork>,
168}
169
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
171pub struct Episode {
172 pub id: MediaId,
173 pub show_id: MediaId,
174 #[serde(deserialize_with = "crate::required::option")]
177 pub show_title: Option<String>,
178 pub season_id: MediaId,
179 pub season: u32,
180 pub episode: u32,
181 pub title: String,
182 pub summary: Option<String>,
183 pub content_rating: Option<String>,
186 pub year: Option<u16>,
192 pub air_date: Option<CalendarDate>,
194 #[serde(with = "duration_ms::option")]
195 pub duration: Option<Duration>,
196 #[serde(default)]
200 pub cast: Vec<CastMember>,
201 pub artwork: Vec<Artwork>,
202 pub playback: PlaybackState,
203}
204
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
213pub struct CastMember {
214 pub id: PersonId,
217 pub name: String,
218 pub role: PersonRole,
219 #[serde(deserialize_with = "crate::required::option")]
222 pub character: Option<String>,
223 #[serde(deserialize_with = "crate::required::option")]
226 pub photo: Option<ArtworkId>,
227}
228
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230pub struct Artist {
231 pub id: MediaId,
232 pub name: String,
233 pub summary: Option<String>,
234 pub artwork: Vec<Artwork>,
235}
236
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
238pub struct Album {
239 pub id: MediaId,
240 pub artist_id: MediaId,
241 #[serde(deserialize_with = "crate::required::option")]
243 pub artist_name: Option<String>,
244 pub title: String,
245 pub year: Option<u16>,
246 pub track_count: Option<u32>,
250 pub artwork: Vec<Artwork>,
251}
252
253#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
254pub struct Track {
255 pub id: MediaId,
256 pub album_id: MediaId,
257 pub artist_id: MediaId,
258 pub artist_name: Option<String>,
262 pub album_title: Option<String>,
264 pub title: String,
265 pub track: Option<u32>,
267 pub disc: Option<u32>,
268 pub album_track_count: Option<u32>,
272 pub codec: Option<AudioCodec>,
274 pub bit_depth: Option<u32>,
278 pub sample_rate: Option<u32>,
281 #[serde(with = "duration_ms::option")]
282 pub duration: Option<Duration>,
283 pub artwork: Vec<Artwork>,
285 pub playback: PlaybackState,
286}
287
288#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
290#[serde(rename_all = "snake_case")]
291pub enum MarkerKind {
292 Intro,
293 Credits,
294 #[serde(other)]
297 Unknown,
298}
299
300#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
302pub struct Marker {
303 pub kind: MarkerKind,
304 pub start_ms: u64,
306 pub end_ms: u64,
309 pub to_end: bool,
312}
313
314#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
317#[serde(tag = "kind", rename_all = "snake_case")]
318pub enum Item {
319 Movie(Movie),
320 Show(Show),
321 Season(Season),
322 Episode(Episode),
323 Artist(Artist),
324 Album(Album),
325 Track(Track),
326}
327
328impl Item {
329 pub fn id(&self) -> &MediaId {
330 match self {
331 Item::Movie(m) => &m.id,
332 Item::Show(s) => &s.id,
333 Item::Season(s) => &s.id,
334 Item::Episode(e) => &e.id,
335 Item::Artist(a) => &a.id,
336 Item::Album(a) => &a.id,
337 Item::Track(t) => &t.id,
338 }
339 }
340}
341
342#[cfg(test)]
343mod tests {
344 use std::fmt::Debug;
345
346 use serde::de::DeserializeOwned;
347
348 use super::*;
349 use crate::id::{MediaKind, Namespace};
350
351 fn round_trip<T: Serialize + DeserializeOwned + PartialEq + Debug>(value: T) {
352 let json = serde_json::to_string(&value).unwrap();
353 assert_eq!(serde_json::from_str::<T>(&json).unwrap(), value, "{json}");
354 }
355
356 fn media(kind: MediaKind, key: &str) -> MediaId {
357 MediaId::new(Namespace::Plex, kind, key).unwrap()
358 }
359
360 fn poster() -> Vec<Artwork> {
361 vec![Artwork {
362 id: ArtworkId::new(Namespace::Plex, "/library/metadata/1/thumb/9").unwrap(),
363 kind: ArtworkKind::Poster,
364 }]
365 }
366
367 fn halfway() -> PlaybackState {
368 PlaybackState {
369 position: Some(Duration::from_millis(2_220_500)),
370 watched: false,
371 last_viewed_at: None,
372 play_count: 0,
373 last_played_at: None,
374 }
375 }
376
377 fn ripley() -> CastMember {
378 CastMember {
379 id: PersonId::new(Namespace::Plex, "actor-13").unwrap(),
380 name: "Sigourney Weaver".into(),
381 role: PersonRole::Actor,
382 character: Some("Ellen Ripley".into()),
383 photo: Some(ArtworkId::new(Namespace::Plex, "/people/1/a/b.jpg").unwrap()),
384 }
385 }
386
387 fn scott() -> CastMember {
388 CastMember {
389 id: PersonId::new(Namespace::Plex, "director-7").unwrap(),
390 name: "Ridley Scott".into(),
391 role: PersonRole::Director,
392 character: None,
393 photo: None,
394 }
395 }
396
397 #[test]
398 fn a_cast_member_is_their_person_id_role_and_photo_on_the_wire() {
399 assert_eq!(
400 serde_json::to_value(ripley()).unwrap(),
401 serde_json::json!({
402 "id": "plex:actor-13",
403 "name": "Sigourney Weaver",
404 "role": "actor",
405 "character": "Ellen Ripley",
406 "photo": "plex:/people/1/a/b.jpg",
407 })
408 );
409 round_trip(ripley());
410 round_trip(scott());
411 }
412
413 #[test]
415 fn a_cast_member_s_character_and_photo_are_required() {
416 crate::test_support::assert_each_required(&scott(), &["character", "photo"]);
417 }
418
419 #[test]
422 fn items_from_a_server_without_cast_or_dates_still_decode() {
423 let movie = Movie {
424 id: media(MediaKind::Movie, "10"),
425 title: "Alien".into(),
426 year: Some(1979),
427 release_date: CalendarDate::new(1979, 5, 25),
428 summary: None,
429 content_rating: None,
430 duration: None,
431 cast: vec![ripley()],
432 artwork: Vec::new(),
433 playback: PlaybackState::default(),
434 };
435 let mut json = serde_json::to_value(&movie).unwrap();
436 assert_eq!(json["release_date"], "1979-05-25");
437 let object = json.as_object_mut().unwrap();
438 object.remove("release_date");
439 object.remove("cast");
440 let older: Movie = serde_json::from_value(json).unwrap();
441 assert_eq!((older.release_date, older.cast), (None, Vec::new()));
442
443 let show = Show {
444 id: media(MediaKind::Show, "20"),
445 title: "The Expanse".into(),
446 year: Some(2015),
447 summary: None,
448 content_rating: None,
449 season_count: None,
450 genres: Vec::new(),
451 last_aired: CalendarDate::new(2022, 4, 8),
452 cast: vec![ripley()],
453 artwork: Vec::new(),
454 };
455 let mut json = serde_json::to_value(&show).unwrap();
456 assert_eq!(json["last_aired"], "2022-04-08");
457 let object = json.as_object_mut().unwrap();
458 object.remove("last_aired");
459 object.remove("cast");
460 let older: Show = serde_json::from_value(json).unwrap();
461 assert_eq!((older.last_aired, older.cast), (None, Vec::new()));
462
463 let episode = Episode {
464 id: media(MediaKind::Episode, "22"),
465 show_id: media(MediaKind::Show, "20"),
466 show_title: None,
467 season_id: media(MediaKind::Season, "21"),
468 season: 1,
469 episode: 1,
470 title: "Dulcinea".into(),
471 summary: None,
472 content_rating: None,
473 year: None,
474 air_date: None,
475 duration: None,
476 cast: vec![scott()],
477 artwork: Vec::new(),
478 playback: PlaybackState::default(),
479 };
480 let mut json = serde_json::to_value(&episode).unwrap();
481 json.as_object_mut().unwrap().remove("cast");
482 let older: Episode = serde_json::from_value(json).unwrap();
483 assert_eq!(older.cast, Vec::new());
484 }
485
486 #[test]
487 fn durations_are_whole_milliseconds_on_the_wire() {
488 let json = serde_json::to_value(halfway()).unwrap();
489 assert_eq!(json["position"], 2_220_500);
490 }
491
492 #[test]
493 fn an_unstarted_item_has_a_null_position() {
494 let json = serde_json::to_value(PlaybackState::default()).unwrap();
495 assert!(json["position"].is_null());
496 }
497
498 #[test]
499 fn a_track_s_format_is_plain_numbers_on_the_wire() {
500 let track = Track {
501 id: media(MediaKind::Track, "224630"),
502 album_id: media(MediaKind::Album, "224629"),
503 artist_id: media(MediaKind::Artist, "224303"),
504 artist_name: None,
505 album_title: None,
506 title: "Catch".into(),
507 track: Some(1),
508 disc: Some(1),
509 album_track_count: Some(3),
510 codec: Some(AudioCodec::Flac),
511 bit_depth: Some(24),
512 sample_rate: Some(96_000),
513 duration: None,
514 artwork: Vec::new(),
515 playback: PlaybackState::default(),
516 };
517 let json = serde_json::to_value(&track).unwrap();
518 assert_eq!(
519 (
520 &json["codec"],
521 &json["bit_depth"],
522 &json["sample_rate"],
523 &json["album_track_count"]
524 ),
525 (
526 &serde_json::json!("flac"),
527 &serde_json::json!(24),
528 &serde_json::json!(96_000),
529 &serde_json::json!(3)
530 )
531 );
532 }
533
534 #[test]
535 fn library_kinds_are_snake_case_on_the_wire() {
536 assert_eq!(
537 serde_json::to_string(&LibraryKind::Movies).unwrap(),
538 r#""movies""#
539 );
540 }
541
542 #[test]
543 fn a_marker_is_milliseconds_and_a_snake_case_kind_on_the_wire() {
544 let marker = Marker {
545 kind: MarkerKind::Credits,
546 start_ms: 2_662_962,
547 end_ms: 2_709_958,
548 to_end: true,
549 };
550 assert_eq!(
551 serde_json::to_value(marker).unwrap(),
552 serde_json::json!({
553 "kind": "credits",
554 "start_ms": 2_662_962,
555 "end_ms": 2_709_958,
556 "to_end": true,
557 })
558 );
559 round_trip(marker);
560 }
561
562 #[test]
563 fn a_marker_kind_from_a_newer_server_is_unknown() {
564 let marker: Marker = serde_json::from_str(
565 r#"{"kind": "recap", "start_ms": 0, "end_ms": 30000, "to_end": false}"#,
566 )
567 .unwrap();
568 assert_eq!(marker.kind, MarkerKind::Unknown);
569 }
570
571 #[test]
572 fn an_item_carries_its_kind_on_the_wire() {
573 let item = Item::Show(Show {
574 id: media(MediaKind::Show, "20"),
575 title: "The Expanse".into(),
576 year: None,
577 summary: None,
578 content_rating: None,
579 season_count: None,
580 genres: Vec::new(),
581 last_aired: None,
582 cast: Vec::new(),
583 artwork: Vec::new(),
584 });
585 let json = serde_json::to_value(&item).unwrap();
586 assert_eq!(json["kind"], "show");
587 assert_eq!(json["id"], "plex:show:20");
588 round_trip(item);
589 }
590
591 #[test]
594 fn a_parent_s_name_left_out_is_refused() {
595 let season = Season {
596 id: media(MediaKind::Season, "21"),
597 show_id: media(MediaKind::Show, "20"),
598 show_title: None,
599 season: 1,
600 title: "Season 1".into(),
601 artwork: Vec::new(),
602 };
603 crate::test_support::assert_each_required(&season, &["show_title"]);
604 let episode = Episode {
605 id: media(MediaKind::Episode, "22"),
606 show_id: media(MediaKind::Show, "20"),
607 show_title: None,
608 season_id: media(MediaKind::Season, "21"),
609 season: 1,
610 episode: 1,
611 title: "Dulcinea".into(),
612 summary: None,
613 content_rating: None,
614 year: None,
615 air_date: None,
616 duration: None,
617 cast: Vec::new(),
618 artwork: Vec::new(),
619 playback: PlaybackState::default(),
620 };
621 crate::test_support::assert_each_required(&episode, &["show_title"]);
622 let album = Album {
623 id: media(MediaKind::Album, "30"),
624 artist_id: media(MediaKind::Artist, "31"),
625 artist_name: None,
626 title: "Moon Safari".into(),
627 year: None,
628 track_count: None,
629 artwork: Vec::new(),
630 };
631 crate::test_support::assert_each_required(&album, &["artist_name"]);
632 round_trip(album);
634 }
635
636 #[test]
637 fn an_episode_from_a_server_without_air_dates_still_decodes() {
638 let episode = Episode {
639 id: media(MediaKind::Episode, "22"),
640 show_id: media(MediaKind::Show, "20"),
641 show_title: None,
642 season_id: media(MediaKind::Season, "21"),
643 season: 1,
644 episode: 1,
645 title: "Dulcinea".into(),
646 summary: None,
647 content_rating: None,
648 year: Some(2015),
649 air_date: CalendarDate::new(2015, 11, 23),
650 duration: None,
651 cast: Vec::new(),
652 artwork: Vec::new(),
653 playback: PlaybackState::default(),
654 };
655 let mut json = serde_json::to_value(&episode).unwrap();
656 assert_eq!(json["air_date"], "2015-11-23");
657 let object = json.as_object_mut().unwrap();
658 object.remove("year");
659 object.remove("air_date");
660 let older: Episode = serde_json::from_value(json).unwrap();
661 assert_eq!((older.year, older.air_date), (None, None));
662 }
663
664 #[test]
665 fn every_model_type_round_trips() {
666 round_trip(Library {
667 id: LibraryId::new(Namespace::Plex, "1").unwrap(),
668 title: "Movies".into(),
669 kind: LibraryKind::Movies,
670 server: None,
671 });
672 round_trip(Movie {
673 id: media(MediaKind::Movie, "10"),
674 title: "Alien".into(),
675 year: Some(1979),
676 release_date: CalendarDate::new(1979, 5, 25),
677 summary: Some("In space no one can hear you scream.".into()),
678 content_rating: Some("R".into()),
679 duration: Some(Duration::from_secs(7020)),
680 cast: vec![ripley(), scott()],
681 artwork: poster(),
682 playback: halfway(),
683 });
684 round_trip(Show {
685 id: media(MediaKind::Show, "20"),
686 title: "The Expanse".into(),
687 year: Some(2015),
688 summary: None,
689 content_rating: Some("TV-14".into()),
690 season_count: Some(6),
691 genres: vec!["Science Fiction".into(), "Drama".into()],
692 last_aired: CalendarDate::new(2022, 4, 8),
693 cast: vec![ripley()],
694 artwork: poster(),
695 });
696 round_trip(Season {
697 id: media(MediaKind::Season, "21"),
698 show_id: media(MediaKind::Show, "20"),
699 show_title: Some("The Expanse".into()),
700 season: 1,
701 title: "Season 1".into(),
702 artwork: Vec::new(),
703 });
704 round_trip(Episode {
705 id: media(MediaKind::Episode, "22"),
706 show_id: media(MediaKind::Show, "20"),
707 show_title: Some("The Expanse".into()),
708 season_id: media(MediaKind::Season, "21"),
709 season: 1,
710 episode: 1,
711 title: "Dulcinea".into(),
712 summary: None,
713 content_rating: Some("TV-14".into()),
714 year: Some(2015),
715 air_date: CalendarDate::new(2015, 11, 23),
716 duration: Some(Duration::from_secs(2640)),
717 cast: vec![scott()],
718 artwork: poster(),
719 playback: PlaybackState::default(),
720 });
721 round_trip(Artist {
722 id: media(MediaKind::Artist, "30"),
723 name: "Boards of Canada".into(),
724 summary: None,
725 artwork: poster(),
726 });
727 round_trip(Album {
728 id: media(MediaKind::Album, "31"),
729 artist_id: media(MediaKind::Artist, "30"),
730 artist_name: Some("Boards of Canada".into()),
731 title: "Music Has the Right to Children".into(),
732 year: Some(1998),
733 track_count: Some(18),
734 artwork: poster(),
735 });
736 round_trip(Track {
737 id: media(MediaKind::Track, "32"),
738 album_id: media(MediaKind::Album, "31"),
739 artist_id: media(MediaKind::Artist, "30"),
740 artist_name: Some("Boards of Canada".into()),
741 album_title: Some("Music Has the Right to Children".into()),
742 title: "Roygbiv".into(),
743 track: Some(10),
744 disc: Some(1),
745 album_track_count: Some(18),
746 codec: Some(AudioCodec::Flac),
747 bit_depth: Some(16),
748 sample_rate: Some(44_100),
749 duration: Some(Duration::from_secs(151)),
750 artwork: poster(),
751 playback: PlaybackState {
752 position: None,
753 watched: true,
754 last_viewed_at: None,
755 play_count: 0,
756 last_played_at: None,
757 },
758 });
759 }
760}