1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
mod guid;
mod metadata_type;

use crate::media_container::{
    helpers::deserialize_option_string_from_number,
    helpers::{deserialize_option_datetime_from_timestamp, optional_boolish},
    preferences::Preferences,
    MediaContainer,
};
pub use guid::Guid;
pub use metadata_type::*;
use monostate::MustBe;
use serde::{Deserialize, Deserializer, Serialize};
use serde_aux::prelude::{
    deserialize_number_from_string, deserialize_option_number_from_string,
    deserialize_string_from_number,
};
use serde_json::Value;
use serde_plain::{derive_display_from_serialize, derive_fromstr_from_deserialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
use serde_with::{formats::CommaSeparator, serde_as, StringWithSeparator};
use time::{Date, OffsetDateTime};

#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Decision {
    Copy,
    Transcode,
    Ignore,
    DirectPlay,
    Burn,
    #[cfg(not(feature = "tests_deny_unknown_fields"))]
    #[serde(other)]
    Unknown,
}

derive_display_from_serialize!(Decision);

#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Protocol {
    /// HTTP file download
    Http,
    /// HTTP Live Streaming
    Hls,
    /// Dynamic Adaptive Streaming over HTTP
    Dash,
    /// ??? Used in extras; can't be used for transcoding
    Mp4,
    #[cfg(not(feature = "tests_deny_unknown_fields"))]
    #[serde(other)]
    Unknown,
}

derive_display_from_serialize!(Protocol);

#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ChapterSource {
    Media,
    Mixed,
    Agent,
    #[cfg(not(feature = "tests_deny_unknown_fields"))]
    #[serde(other)]
    Unknown,
}

derive_fromstr_from_deserialize!(ChapterSource);

#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "kebab-case")]
pub enum AudioCodec {
    Aac,
    Ac3,
    Dca,
    DcaMa,
    Eac3,
    Mp2,
    Mp3,
    Opus,
    Pcm,
    Vorbis,
    Flac,
    #[serde(rename = "truehd")]
    TrueHd,
    #[cfg(not(feature = "tests_deny_unknown_fields"))]
    #[serde(other)]
    Unknown,
}

derive_fromstr_from_deserialize!(AudioCodec);
derive_display_from_serialize!(AudioCodec);

#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "kebab-case")]
pub enum VideoCodec {
    H264,
    Hevc,
    Mpeg1Video,
    Mpeg2Video,
    Mpeg4,
    Msmpeg4v3,
    Vc1,
    Vp8,
    Vp9,
    #[cfg(not(feature = "tests_deny_unknown_fields"))]
    #[serde(other)]
    Unknown,
}

derive_fromstr_from_deserialize!(VideoCodec);
derive_display_from_serialize!(VideoCodec);

#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "kebab-case")]
pub enum LyricCodec {
    Lrc,
    Txt,
    #[cfg(not(feature = "tests_deny_unknown_fields"))]
    #[serde(other)]
    Unknown,
}

derive_fromstr_from_deserialize!(LyricCodec);
derive_display_from_serialize!(LyricCodec);

#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SubtitleCodec {
    Ass,
    Pgs,
    Subrip,
    Srt,
    DvdSubtitle,
    MovText,
    Vtt,
    DvbSubtitle,
    #[cfg(not(feature = "tests_deny_unknown_fields"))]
    #[serde(other)]
    Unknown,
}

derive_fromstr_from_deserialize!(SubtitleCodec);
derive_display_from_serialize!(SubtitleCodec);

#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ContainerFormat {
    Aac,
    Avi,
    Jpeg,
    M4v,
    Mkv,
    Mp3,
    Mp4,
    Mpeg,
    MpegTs,
    Ogg,
    Wav,
    Ac3,
    Eac3,
    #[cfg(not(feature = "tests_deny_unknown_fields"))]
    #[serde(other)]
    Unknown,
}

derive_fromstr_from_deserialize!(ContainerFormat);
derive_display_from_serialize!(ContainerFormat);

#[serde_as]
#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
pub struct VideoStream {
    #[serde(default, deserialize_with = "deserialize_string_from_number")]
    pub id: String,
    pub stream_type: MustBe!(1),
    pub index: Option<u32>,
    pub codec: VideoCodec,
    pub default: Option<bool>,
    pub selected: Option<bool>,
    pub title: Option<String>,
    pub display_title: String,
    pub extended_display_title: Option<String>,

    #[serde_as(as = "Option<StringWithSeparator::<CommaSeparator, u32>>")]
    pub required_bandwidths: Option<Vec<u32>>,
    pub decision: Option<Decision>,
    pub location: Option<String>,

    pub height: u32,
    pub width: u32,
    pub bit_depth: Option<u8>,
    pub bitrate: Option<u32>,
    pub chroma_location: Option<String>,
    pub chroma_subsampling: Option<String>,
    pub coded_height: Option<u32>,
    pub coded_width: Option<u32>,
    pub color_primaries: Option<String>,
    pub color_range: Option<String>,
    pub color_space: Option<String>,
    pub color_trc: Option<String>,
    pub frame_rate: Option<f32>,
    pub has_scaling_matrix: Option<bool>,
    pub level: Option<u32>,
    pub profile: Option<String>,
    pub ref_frames: Option<u32>,
    pub scan_type: Option<String>,
    #[serde(rename = "codecID")]
    pub codec_id: Option<String>,
    pub stream_identifier: Option<String>,
    pub language: Option<String>,
    pub language_code: Option<String>,
    pub language_tag: Option<String>,
    pub anamorphic: Option<bool>,
    pub pixel_aspect_ratio: Option<String>,
}

#[serde_as]
#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
pub struct AudioStream {
    #[serde(default, deserialize_with = "deserialize_string_from_number")]
    pub id: String,
    pub stream_type: MustBe!(2),
    pub index: Option<u32>,
    pub codec: AudioCodec,
    pub default: Option<bool>,
    pub selected: Option<bool>,
    pub title: Option<String>,
    pub display_title: String,
    pub extended_display_title: Option<String>,

    #[serde_as(as = "Option<StringWithSeparator::<CommaSeparator, u32>>")]
    pub required_bandwidths: Option<Vec<u32>>,
    pub decision: Option<Decision>,
    pub location: Option<String>,

    pub channels: u32,
    pub audio_channel_layout: Option<String>,
    pub profile: Option<String>,
    pub sampling_rate: Option<u32>,
    pub bitrate: Option<u32>,
    pub bitrate_mode: Option<String>,
    pub language: Option<String>,
    pub language_code: Option<String>,
    pub language_tag: Option<String>,
    pub peak: Option<String>,
    pub gain: Option<String>,
    pub album_peak: Option<String>,
    pub album_gain: Option<String>,
    pub album_range: Option<String>,
    pub lra: Option<String>,
    pub loudness: Option<String>,
    pub stream_identifier: Option<String>,
}

#[serde_as]
#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
pub struct SubtitleStream {
    #[serde(default, deserialize_with = "deserialize_string_from_number")]
    pub id: String,
    pub stream_type: MustBe!(3),
    pub index: Option<u32>,
    pub codec: SubtitleCodec,
    pub default: Option<bool>,
    pub selected: Option<bool>,
    pub title: Option<String>,
    pub display_title: String,
    pub extended_display_title: Option<String>,
    pub forced: Option<bool>,

    #[serde_as(as = "Option<StringWithSeparator::<CommaSeparator, u32>>")]
    pub required_bandwidths: Option<Vec<u32>>,
    pub decision: Option<Decision>,
    pub location: Option<String>,

    pub key: Option<String>,
    pub format: Option<String>,
    pub file: Option<String>,
    pub bitrate: Option<u32>,
    pub hearing_impaired: Option<bool>,
    pub language: Option<String>,
    pub language_code: Option<String>,
    pub language_tag: Option<String>,
    pub ignore: Option<String>,
    pub burn: Option<String>,
}

#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
pub struct LyricStream {
    #[serde(default, deserialize_with = "deserialize_string_from_number")]
    pub id: String,
    pub stream_type: MustBe!(4),
    pub index: Option<u32>,
    pub codec: LyricCodec,
    pub default: Option<bool>,
    pub selected: Option<bool>,
    pub title: Option<String>,
    pub display_title: String,
    pub extended_display_title: Option<String>,

    pub key: Option<String>,
    pub format: Option<String>,
    pub timed: Option<String>,
    pub min_lines: Option<String>,
    pub provider: Option<String>,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(not(feature = "tests_deny_unknown_fields"), serde(untagged))]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(try_from = "Value"))]
pub enum Stream {
    Video(VideoStream),
    Audio(AudioStream),
    Subtitle(SubtitleStream),
    Lyric(LyricStream),
    Unknown(Value),
}

// This generates much saner errors in tests than an untagged enum.
#[cfg(feature = "tests_deny_unknown_fields")]
impl TryFrom<Value> for Stream {
    type Error = String;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        let stream_type = match &value {
            Value::Object(o) => {
                if let Some(Value::Number(n)) = o.get("streamType") {
                    if let Some(v) = n.as_u64() {
                        v
                    } else {
                        return Err(format!(
                            "Failed to decode Stream. Unexpected streamType `{n}`"
                        ));
                    }
                } else {
                    return Err("Failed to decode Stream. Missing streamType property.".to_string());
                }
            }
            _ => return Err("Failed to decode Stream. Data was not an object.".to_string()),
        };

        if stream_type == 1 {
            let s: VideoStream = serde_json::from_value(value)
                .map_err(|e| format!("Failed to decode video stream: {e}"))?;
            Ok(Self::Video(s))
        } else if stream_type == 2 {
            let s: AudioStream = serde_json::from_value(value)
                .map_err(|e| format!("Failed to decode audio stream: {e}"))?;
            Ok(Self::Audio(s))
        } else if stream_type == 3 {
            let s: SubtitleStream = serde_json::from_value(value)
                .map_err(|e| format!("Failed to decode subtitle stream: {e}"))?;
            Ok(Self::Subtitle(s))
        } else if stream_type == 4 {
            let s: LyricStream = serde_json::from_value(value)
                .map_err(|e| format!("Failed to decode lyric stream: {e}"))?;
            Ok(Self::Lyric(s))
        } else if !cfg!(feature = "tests_deny_unknown_fields") {
            Ok(Self::Unknown(value))
        } else {
            Err(format!(
                "Failed to decode Stream. Unexpected streamType `{stream_type}`"
            ))
        }
    }
}

#[serde_as]
#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct Part {
    #[serde(default, deserialize_with = "deserialize_option_string_from_number")]
    pub id: Option<String>,
    pub key: Option<String>,
    pub duration: Option<u64>,
    pub file: Option<String>,
    pub size: Option<u64>,
    pub container: Option<ContainerFormat>,
    pub indexes: Option<String>,
    pub audio_profile: Option<String>,
    pub video_profile: Option<String>,
    pub protocol: Option<Protocol>,
    pub selected: Option<bool>,
    pub decision: Option<Decision>,
    pub width: Option<u32>,
    pub height: Option<u32>,
    pub packet_length: Option<u64>,
    pub has_thumbnail: Option<String>,
    #[serde(rename = "has64bitOffsets")]
    pub has_64bit_offsets: Option<bool>,
    #[serde(default, deserialize_with = "optional_boolish")]
    pub optimized_for_streaming: Option<bool>,
    pub has_chapter_text_stream: Option<bool>,
    pub has_chapter_video_stream: Option<bool>,
    pub deep_analysis_version: Option<String>,
    #[serde_as(as = "Option<StringWithSeparator::<CommaSeparator, u32>>")]
    pub required_bandwidths: Option<Vec<u32>>,
    pub bitrate: Option<u32>,
    #[serde(rename = "Stream")]
    pub streams: Option<Vec<Stream>>,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct Media {
    #[serde(default, deserialize_with = "deserialize_option_string_from_number")]
    pub id: Option<String>,
    pub duration: Option<u64>,
    pub bitrate: Option<u32>,
    pub width: Option<u32>,
    pub height: Option<u32>,
    #[serde(default, deserialize_with = "deserialize_option_number_from_string")]
    pub aspect_ratio: Option<f32>,
    pub audio_channels: Option<u8>,
    pub protocol: Option<Protocol>,
    pub audio_codec: Option<AudioCodec>,
    pub video_codec: Option<VideoCodec>,
    pub video_resolution: Option<String>,
    pub container: Option<ContainerFormat>,
    pub extension: Option<String>,
    pub video_frame_rate: Option<String>,
    pub audio_profile: Option<String>,
    pub video_profile: Option<String>,
    pub selected: Option<bool>,
    #[serde(rename = "Part")]
    pub parts: Vec<Part>,
    #[serde(rename = "has64bitOffsets")]
    pub has_64bit_offsets: Option<bool>,
    #[serde(default, deserialize_with = "optional_boolish")]
    pub optimized_for_streaming: Option<bool>,
    pub display_offset: Option<u64>,
    pub premium: Option<bool>,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
pub struct Field {
    pub locked: bool,
    pub name: String,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
pub struct Location {
    pub path: String,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
pub struct Tag {
    #[serde(default, deserialize_with = "deserialize_option_string_from_number")]
    pub id: Option<String>,
    pub tag: String,
    pub filter: Option<String>,
    pub directory: Option<bool>,
    #[serde(rename = "ratingKey")]
    pub rating_key: Option<String>,
    pub context: Option<String>,
    pub slug: Option<String>,
    #[serde(default, deserialize_with = "deserialize_option_number_from_string")]
    pub count: Option<u32>,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
pub struct Collection {
    #[serde(default, deserialize_with = "deserialize_option_string_from_number")]
    pub id: Option<String>,
    pub art: Option<String>,
    pub key: Option<String>,
    pub thumb: Option<String>,
    pub tag: String,
    pub filter: Option<String>,
    #[serde(default, deserialize_with = "deserialize_option_number_from_string")]
    pub count: Option<u32>,
    pub guid: Option<Guid>,
    pub summary: Option<String>,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
pub struct Review {
    #[serde(default, deserialize_with = "deserialize_option_string_from_number")]
    pub id: Option<String>,
    pub tag: String,
    pub filter: Option<String>,
    pub text: String,
    pub image: String,
    pub link: Option<String>,
    pub source: String,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct Rating {
    #[serde(default, deserialize_with = "deserialize_number_from_string")]
    pub count: u32,
    pub image: String,
    #[serde(rename = "type")]
    pub rating_type: String,
    #[serde(default, deserialize_with = "deserialize_number_from_string")]
    pub value: f32,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct Role {
    #[serde(default, deserialize_with = "deserialize_option_string_from_number")]
    pub id: Option<String>,
    pub tag: String,
    pub key: Option<String>,
    pub slug: Option<String>,
    pub tag_key: Option<String>,
    pub filter: Option<String>,
    pub role: Option<String>,
    pub thumb: Option<String>,
    #[serde(rename = "type")]
    pub role_type: Option<String>,
    pub directory: Option<bool>,
    #[serde(default, deserialize_with = "deserialize_option_number_from_string")]
    pub count: Option<u32>,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct ParentMetadata {
    pub parent_key: Option<String>,
    #[serde(default, deserialize_with = "deserialize_option_string_from_number")]
    pub parent_rating_key: Option<String>,
    pub parent_guid: Option<Guid>,

    pub parent_title: Option<String>,
    pub parent_studio: Option<String>,
    pub parent_year: Option<u32>,
    pub parent_content_rating: Option<String>,
    pub parent_index: Option<u32>,

    pub parent_thumb: Option<String>,
    pub parent_art: Option<String>,
    pub parent_theme: Option<String>,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct GrandParentMetadata {
    pub grandparent_key: Option<String>,
    #[serde(default, deserialize_with = "deserialize_option_string_from_number")]
    pub grandparent_rating_key: Option<String>,
    pub grandparent_guid: Option<Guid>,

    pub grandparent_title: Option<String>,
    pub grandparent_studio: Option<String>,
    pub grandparent_year: Option<u32>,
    pub grandparent_content_rating: Option<String>,
    pub grandparent_index: Option<u32>,

    pub grandparent_thumb: Option<String>,
    pub grandparent_art: Option<String>,
    pub grandparent_theme: Option<String>,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct Extras {
    pub size: u32,
    pub key: Option<String>,
    #[serde(default, rename = "Metadata")]
    pub metadata: Vec<Box<Metadata>>,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct OnDeck {
    #[serde(rename = "Metadata")]
    pub metadata: Metadata,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct Chapter {
    pub id: u32,
    pub filter: Option<String>,
    pub index: u32,
    pub start_time_offset: u64,
    pub end_time_offset: u64,
    pub tag: Option<String>,
    pub thumb: Option<String>,
}

pub(crate) fn deserialize_marker_type<'de, D>(deserializer: D) -> Result<MarkerType, D::Error>
where
    D: Deserializer<'de>,
{
    #[derive(Debug, Deserialize)]
    #[serde(rename_all = "camelCase")]
    struct Helper {
        r#type: String,
        r#final: Option<bool>,
    }

    let m = Helper::deserialize(deserializer)?;

    match m.r#type.as_str() {
        "intro" => Ok(MarkerType::Intro),
        "credits" => Ok(MarkerType::Credits(m.r#final.unwrap_or_default())),
        #[cfg(not(feature = "tests_deny_unknown_fields"))]
        _ => Ok(MarkerType::Unknown(m.r#type)),
        #[cfg(feature = "tests_deny_unknown_fields")]
        _ => {
            return Err(serde::de::Error::unknown_variant(
                m.r#type.as_str(),
                &["credits", "intro"],
            ))
        }
    }
}

#[derive(Debug, Clone)]
pub enum MarkerType {
    /// Credits marker. If the inner value is `true` then it's the latest credits sequence in the media.
    Credits(bool),
    Intro,
    #[cfg(not(feature = "tests_deny_unknown_fields"))]
    Unknown(String),
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct MarkerAttributes {
    pub id: u32,
    pub version: Option<u32>,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct Marker {
    pub id: u32,
    pub start_time_offset: u32,
    pub end_time_offset: u32,
    #[serde(flatten, deserialize_with = "deserialize_marker_type")]
    pub marker_type: MarkerType,
    #[serde(rename = "Attributes")]
    pub attributes: MarkerAttributes,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct Metadata {
    pub key: String,
    pub rating_key: String,
    pub guid: Option<Guid>,
    pub primary_guid: Option<Guid>,

    #[serde(flatten, deserialize_with = "deserialize_option_metadata_type")]
    pub metadata_type: Option<MetadataType>,
    #[serde(default, deserialize_with = "optional_boolish")]
    pub smart: Option<bool>,
    #[serde(default, deserialize_with = "optional_boolish")]
    pub allow_sync: Option<bool>,

    pub title: String,
    pub title_sort: Option<String>,
    pub original_title: Option<String>,
    pub studio: Option<String>,
    #[serde(default, deserialize_with = "deserialize_option_number_from_string")]
    pub year: Option<u32>,
    #[serde(default, deserialize_with = "deserialize_option_number_from_string")]
    pub min_year: Option<u32>,
    #[serde(default, deserialize_with = "deserialize_option_number_from_string")]
    pub max_year: Option<u32>,
    pub content_rating: Option<String>,
    pub summary: Option<String>,
    pub rating: Option<f32>,
    pub rating_count: Option<u32>,
    pub rating_image: Option<String>,
    pub audience_rating: Option<f32>,
    pub audience_rating_image: Option<String>,
    #[serde(default, deserialize_with = "deserialize_option_number_from_string")]
    pub user_rating: Option<f32>,
    #[serde(
        default,
        deserialize_with = "deserialize_option_datetime_from_timestamp"
    )]
    pub last_rated_at: Option<OffsetDateTime>,
    pub tagline: Option<String>,
    pub duration: Option<u64>,
    pub originally_available_at: Option<Date>,

    pub thumb: Option<String>,
    pub art: Option<String>,
    pub theme: Option<String>,
    pub composite: Option<String>,
    pub banner: Option<String>,
    pub icon: Option<String>,

    pub index: Option<u32>,
    #[serde(rename = "playlistItemID")]
    pub playlist_item_id: Option<u32>,
    #[serde(default, deserialize_with = "deserialize_option_number_from_string")]
    pub child_count: Option<u32>,
    pub season_count: Option<u32>,
    pub leaf_count: Option<u32>,
    pub viewed_leaf_count: Option<u32>,
    pub skip_children: Option<bool>,

    pub view_count: Option<u64>,
    pub skip_count: Option<u64>,
    #[serde(default, with = "time::serde::timestamp::option")]
    pub last_viewed_at: Option<OffsetDateTime>,

    #[serde(rename = "createdAtTZOffset")]
    pub created_at_tz_offset: Option<String>,
    pub created_at_accuracy: Option<String>,
    #[serde(default, with = "time::serde::timestamp::option")]
    pub added_at: Option<OffsetDateTime>,
    #[serde(default, with = "time::serde::timestamp::option")]
    pub deleted_at: Option<OffsetDateTime>,
    #[serde(default, with = "time::serde::timestamp::option")]
    pub updated_at: Option<OffsetDateTime>,
    #[serde(default, deserialize_with = "deserialize_option_number_from_string")]
    pub loudness_analysis_version: Option<u32>,
    #[serde(default, deserialize_with = "optional_boolish")]
    pub has_premium_extras: Option<bool>,
    #[serde(default, deserialize_with = "optional_boolish")]
    pub has_premium_primary_extra: Option<bool>,
    pub view_offset: Option<u64>,
    pub chapter_source: Option<ChapterSource>,
    pub primary_extra_key: Option<String>,
    #[serde(default, deserialize_with = "optional_boolish")]
    pub has_premium_lyrics: Option<bool>,
    pub music_analysis_version: Option<String>,

    #[serde(rename = "librarySectionID")]
    #[serde(default, deserialize_with = "deserialize_option_number_from_string")]
    pub library_section_id: Option<u32>,
    pub library_section_title: Option<String>,
    pub library_section_key: Option<String>,

    #[serde(flatten)]
    pub parent: Box<ParentMetadata>,
    #[serde(flatten)]
    pub grand_parent: Box<GrandParentMetadata>,

    #[serde(default, rename = "Guid")]
    pub guids: Vec<Guid>,
    #[serde(default, rename = "Collection")]
    pub collections: Vec<Collection>,
    #[serde(default, rename = "Similar")]
    pub similar: Vec<Tag>,
    #[serde(default, rename = "Genre")]
    pub genres: Vec<Tag>,
    #[serde(default, rename = "Director")]
    pub directors: Vec<Role>,
    #[serde(default, rename = "Producer")]
    pub producers: Vec<Role>,
    #[serde(default, rename = "Writer")]
    pub writers: Vec<Role>,
    #[serde(default, rename = "Country")]
    pub countries: Vec<Tag>,
    #[serde(default, rename = "Rating")]
    pub ratings: Vec<Rating>,
    #[serde(default, rename = "Role")]
    pub roles: Vec<Role>,
    #[serde(default, rename = "Location")]
    pub locations: Vec<Location>,
    #[serde(default, rename = "Field")]
    pub fields: Vec<Field>,
    #[serde(default, rename = "Mood")]
    pub moods: Vec<Tag>,
    #[serde(default, rename = "Format")]
    pub formats: Vec<Tag>,
    #[serde(default, rename = "Subformat")]
    pub sub_formats: Vec<Tag>,
    #[serde(default, rename = "Style")]
    pub styles: Vec<Tag>,
    #[serde(default, rename = "Review")]
    pub reviews: Vec<Review>,
    #[serde(default, rename = "Chapter")]
    pub chapters: Vec<Chapter>,
    #[serde(default, rename = "Label")]
    pub labels: Vec<Tag>,

    #[serde(rename = "Preferences")]
    pub preferences: Option<Box<Preferences>>,

    #[serde(rename = "Extras")]
    pub extras: Option<Extras>,

    #[serde(rename = "OnDeck")]
    pub on_deck: Option<Box<OnDeck>>,

    #[serde(default, rename = "Marker")]
    pub markers: Vec<Marker>,

    #[serde(rename = "Media")]
    pub media: Option<Vec<Media>>,

    #[serde(rename = "Vast")]
    pub vast: Option<Vec<Link>>,

    #[serde(rename = "publicPagesURL")]
    pub public_pages_url: Option<String>,
    pub slug: Option<String>,
    pub user_state: Option<bool>,
    pub imdb_rating_count: Option<u64>,
    pub source: Option<String>,
    #[serde(rename = "Image")]
    pub image: Option<Vec<Image>>,
    #[serde(rename = "Studio")]
    pub studios: Option<Vec<Tag>>,

    pub language_override: Option<String>,
    pub content: Option<String>,
    pub collection_sort: Option<String>,
    pub skip_parent: Option<bool>,
}

#[derive(Deserialize, Debug, Clone)]
pub struct Image {
    pub url: String,
    #[serde(rename = "type")]
    pub image_type: String,
    pub alt: String,
}

#[derive(Deserialize, Debug, Clone)]
pub struct Link {
    pub url: String,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct MetadataMediaContainer {
    pub key: Option<String>,
    #[serde(default, deserialize_with = "deserialize_option_string_from_number")]
    pub rating_key: Option<String>,
    pub augmentation_key: Option<String>,

    pub title: Option<String>,
    pub title1: Option<String>,
    pub title2: Option<String>,
    pub summary: Option<String>,
    pub duration: Option<u64>,

    #[serde(default, deserialize_with = "optional_boolish")]
    pub allow_sync: Option<bool>,
    #[serde(rename = "nocache")]
    pub no_cache: Option<bool>,
    pub sort_asc: Option<bool>,
    pub smart: Option<bool>,

    pub thumb: Option<String>,
    pub art: Option<String>,
    pub theme: Option<String>,
    pub composite: Option<String>,
    pub banner: Option<String>,

    #[serde(rename = "librarySectionID")]
    pub library_section_id: Option<u32>,
    pub library_section_title: Option<String>,
    #[serde(rename = "librarySectionUUID")]
    pub library_section_uuid: Option<String>,

    #[serde(flatten)]
    pub parent: ParentMetadata,
    #[serde(flatten)]
    pub grand_parent: GrandParentMetadata,
    #[serde(flatten)]
    pub media_container: MediaContainer,

    pub media_tag_prefix: Option<String>,
    #[serde(default, with = "time::serde::timestamp::option")]
    pub media_tag_version: Option<OffsetDateTime>,
    pub mixed_parents: Option<bool>,
    pub view_group: Option<String>,
    pub view_mode: Option<u32>,
    pub leaf_count: Option<u32>,
    pub playlist_type: Option<PlaylistMetadataType>,

    #[serde(default, rename = "Directory")]
    pub directories: Vec<Value>,
    #[serde(default, rename = "Metadata")]
    pub metadata: Vec<Metadata>,
}

#[derive(Debug, Deserialize, Clone, Copy)]
#[serde(rename_all = "lowercase")]
pub enum PivotType {
    Hub,
    List,
    View,
    #[cfg(not(feature = "tests_deny_unknown_fields"))]
    #[serde(other)]
    Unknown,
}

derive_fromstr_from_deserialize!(PivotType);

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct Pivot {
    pub context: String,
    pub id: String,
    pub key: String,
    pub symbol: String,
    pub title: String,
    pub requires: Option<String>,
    #[serde(rename = "type")]
    pub pivot_type: PivotType,
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[serde(rename_all = "lowercase")]
pub enum LibraryType {
    Movie,
    Show,
    Artist,
    Photo,
    Mixed,
    Clip,
    #[cfg(not(feature = "tests_deny_unknown_fields"))]
    #[serde(other)]
    Unknown,
}

derive_fromstr_from_deserialize!(LibraryType);
derive_display_from_serialize!(LibraryType);

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct ServerLibrary {
    #[serde(rename = "type")]
    pub library_type: LibraryType,
    #[serde(rename = "Pivot")]
    pub pivots: Vec<Pivot>,
    pub agent: String,
    pub hub_key: String,
    pub id: String,
    pub key: String,
    pub subtype: Option<String>,
    pub language: String,
    pub refreshing: bool,
    #[serde(with = "time::serde::timestamp")]
    pub scanned_at: OffsetDateTime,
    pub scanner: String,
    pub title: String,
    #[serde(with = "time::serde::timestamp")]
    pub updated_at: OffsetDateTime,
    pub uuid: String,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct ServerPlaylists {
    #[serde(rename = "type")]
    _type: MustBe!("playlist"),
    #[serde(rename = "Pivot")]
    pub pivots: Vec<Pivot>,
    pub id: String,
    pub key: String,
    pub title: String,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct ServerHome {
    pub hub_key: String,
    pub title: String,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct DvrLibrary {
    #[serde(rename = "type")]
    pub library_type: LibraryType,
    pub key: Option<String>,
    pub title: String,
    pub icon: String,
    #[serde(default, with = "time::serde::timestamp::option")]
    pub updated_at: Option<OffsetDateTime>,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct LiveTv {
    #[serde(rename = "Pivot")]
    pub pivots: Vec<Pivot>,
    pub id: String,
    pub title: String,
    pub hub_key: String,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(deny_unknown_fields))]
#[serde(rename_all = "camelCase")]
pub struct OnlineLibrary {
    #[serde(rename = "type")]
    pub library_type: LibraryType,
    pub key: Option<String>,
    pub title: String,
    pub icon: String,
    pub id: String,
    pub context: Option<String>,
    pub hub_key: Option<String>,
    #[serde(rename = "Pivot")]
    pub pivots: Vec<Pivot>,
    #[serde(default, with = "time::serde::timestamp::option")]
    pub updated_at: Option<OffsetDateTime>,
}

#[derive(Debug, Deserialize, Clone)]
#[cfg_attr(not(feature = "tests_deny_unknown_fields"), serde(untagged))]
#[cfg_attr(feature = "tests_deny_unknown_fields", serde(try_from = "Value"))]
pub enum ContentDirectory {
    Playlists(ServerPlaylists),
    #[serde(rename_all = "camelCase")]
    Media(Box<ServerLibrary>),
    #[serde(rename_all = "camelCase")]
    Home(ServerHome),
    #[serde(rename_all = "camelCase")]
    LiveTv(LiveTv),
    #[serde(rename_all = "camelCase")]
    Online(OnlineLibrary),
    #[serde(rename_all = "camelCase")]
    Dvr(DvrLibrary),
    #[cfg(not(feature = "tests_deny_unknown_fields"))]
    Unknown(Value),
}

// This generates much saner errors in tests than an untagged enum at the cost
// of some manual work.
#[cfg(feature = "tests_deny_unknown_fields")]
impl TryFrom<Value> for ContentDirectory {
    type Error = String;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        let obj = if let Value::Object(o) = &value {
            o
        } else {
            return Err("Failed to decode Directory. Data was not an object.".to_string());
        };

        let directory_type = match obj.get("type") {
            Some(Value::String(n)) => n,
            Some(_) => {
                return Err("Failed to decode Directory. Unexpected type property.".to_string())
            }
            None => {
                if obj.contains_key("Pivot") {
                    let live_tv: LiveTv = serde_json::from_value(value)
                        .map_err(|e| format!("Failed to decode Live TV directory: {e}"))?;
                    return Ok(Self::LiveTv(live_tv));
                }

                let home: ServerHome = serde_json::from_value(value)
                    .map_err(|e| format!("Failed to decode Home directory: {e}"))?;
                return Ok(Self::Home(home));
            }
        };

        if directory_type.as_str() == "playlist" {
            let p: ServerPlaylists = serde_json::from_value(value)
                .map_err(|e| format!("Failed to decode playlist directory: {e}"))?;
            Ok(Self::Playlists(p))
        } else {
            // We're left with ServerLibrary, OnlineLibrary or DvrLibrary.

            // It seems unlikely OnlineLibrary will ever use a scanned_at field.
            if obj.contains_key("scannedAt") {
                let l: ServerLibrary = serde_json::from_value(value)
                    .map_err(|e| format!("Failed to decode server library directory: {e}"))?;
                Ok(Self::Media(Box::new(l)))
            } else if obj.contains_key("id") {
                let l: OnlineLibrary = serde_json::from_value(value)
                    .map_err(|e| format!("Failed to decode online library directory: {e}"))?;
                Ok(Self::Online(l))
            } else {
                let l: DvrLibrary = serde_json::from_value(value)
                    .map_err(|e| format!("Failed to decode dvr library directory: {e}"))?;
                Ok(Self::Dvr(l))
            }
        }
    }
}

#[derive(Debug, Deserialize_repr, Clone, Copy, Serialize_repr)]
#[repr(u16)]
pub enum SearchType {
    Movie = 1,
    Show = 2,
    Season = 3,
    Episode = 4,
    Trailer = 5,
    Comic = 6,
    Person = 7,
    Artist = 8,
    Album = 9,
    Track = 10,
    Picture = 11,
    Clip = 12,
    Photo = 13,
    PhotoAlbum = 14,
    Playlist = 15,
    PlaylistFolder = 16,
    Collection = 18,
    OptimizedVersion = 42,
    UserPlaylistItem = 1001,
    #[cfg(not(feature = "tests_deny_unknown_fields"))]
    #[serde(other)]
    Unknown,
}

derive_display_from_serialize!(SearchType);