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