heos 0.3.1

Rust bindings for HEOS ecosystem API
Documentation
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
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
//! Data types representing various media items.
//!
//! These types provide information about e.g. songs, artist, albums, stations, etc.
//!
//! There are three categories of types in this module:
//!  * Base traits
//!  * Individual media item types
//!  * Composite media item enums
//!
//! Base traits are implemented by both individual and composite media item types, and can be used
//! as trait bounds for logic that wants to accept a broad category of types. The [MediaItemBase]
//! trait is implemented by _all_ media item types, and can be used as a bound to accept any media
//! item type. The [MediaContainerBase] trait is implemented by all media items that are considered
//! "containers", and have a `container_id`.
//!
//! Individual media item types are exactly what they sound like, and represent a specific type of
//! media item, such as an [Artist] or a [Song].
//!
//! Composite media item enums are enumerations that cover all possible individual types that match
//! that enum. These can be used instead of trait bounds for boundless logic. [MediaItem] covers
//! _all_ media item types, and [MediaContainer] covers all types that are considered "containers".
//!
//! In addition to [MediaItem] and [MediaContainer], there are also [MediaItemRef] and
//! [MediaContainerRef], which are enumerations that cover references to individual types.

use educe::Educe;
use qstring::QString;
use serde::Deserialize;
use std::fmt::Debug;
use strum::{EnumDiscriminants, IntoDiscriminant};
use url::Url;

use crate::command::CommandError;
use crate::data::impl_try_from_response_payload;
use crate::data::option::impl_has_options;
use crate::data::player::PlayerId;
use crate::data::queue::QueuedTrackInfo;
use crate::data::response::RawResponse;

/// Trait shared by all media item types.
///
/// This represents shared logic, and allows specifying trait bounds for media items.
pub trait MediaItemBase: Debug {
    /// Get the primary name of this media item.
    ///
    /// For example, for an Album media item, the primary name would be the album name.
    fn name(&self) -> &str;

    /// Get the name of the album this media item belongs to.
    ///
    /// If this media item does not belong to an album, yields `None`.
    ///
    /// Note that this yields `None` if the media item is an Album itself.
    fn album(&self) -> Option<&str> {
        None
    }

    /// Get the name of the artist of this media item.
    ///
    /// If this media item does not have an artist (e.g. if it's a Station or Genre), yields `None`.
    ///
    /// Note that this yields `None` if the media item is an Artist itself.
    fn artist(&self) -> Option<&str> {
        None
    }

    /// Get the image URL for this media item, if it exists.
    fn image_url(&self) -> Option<&Url>;

    /// Whether this media item is directly playable.
    fn playable(&self) -> bool;

    /// Get the Media ID of this media item.
    ///
    /// If this media item does not have a Media ID (e.g. if it's a Station or Genre, or a
    /// non-playable container), yields `None`.
    fn media_id(&self) -> Option<&str>;

    /// Convert this specific media item into the [MediaItem] enumeration.
    fn into_media_item(self) -> MediaItem where Self: Sized;

    /// Retrieve a reference to this media item as a [MediaItemRef].
    fn as_media_item_ref(&self) -> MediaItemRef<'_>;

    /// Attempt to convert this specific media item into the [MediaContainer] enumeration.
    ///
    /// If this specific media item isn't a container, yields itself as a `Result::Err()`.
    fn try_into_media_container(self) -> Result<MediaContainer, Self> where Self: Sized {
        Err(self)
    }

    /// Attempt to retrieve a reference to this media item as a [MediaContainerRef].
    ///
    /// If this specific media item isn't a container, yields `None`.
    fn try_as_media_container_ref(&self) -> Option<MediaContainerRef<'_>> {
        None
    }
}

/// Trait shared by all media item types that are considered "containers".
pub trait MediaContainerBase: MediaItemBase {
    /// Get the container ID of this media item.
    fn container_id(&self) -> &str;

    /// Convert this specific media container into the [MediaContainer] enumeration.
    fn into_media_container(self) -> MediaContainer where Self: Sized;

    /// Retrieve a reference to this media item as a [MediaContainerRef].
    fn as_media_container_ref(&self) -> MediaContainerRef<'_>;
}

/// Error that can occur when attempting to convert a [MediaItem]/[MediaContainer] to a specific
/// media item type via `TryFrom`.
#[derive(thiserror::Error, Debug)]
#[error("invalid MediaItem type; expected: {expected:?}, actual: {actual:?}")]
pub struct TryFromMediaItemError {
    /// The media item type that was attempted to convert to.
    pub expected: MediaItemType,
    /// The actual media item type of the [MediaItem]/[MediaContainer].
    pub actual: MediaItemType,
}

macro_rules! impl_media_item_conversions {
    ($name:ident) => {
        impl From<$name> for MediaItem {
            #[inline]
            fn from(value: $name) -> Self {
                value.into_media_item()
            }
        }

        impl TryFrom<MediaItem> for $name {
            type Error = TryFromMediaItemError;

            fn try_from(item: MediaItem) -> Result<Self, Self::Error> {
                if let MediaItem::$name(inner) = item {
                    Ok(inner)
                } else {
                    Err(TryFromMediaItemError {
                        expected: MediaItemType::$name,
                        actual: item.discriminant(),
                    })
                }
            }
        }
    };
}

macro_rules! impl_media_container_conversions {
    ($name:ident) => {
        impl TryFrom<$name> for MediaContainer {
            type Error = $name;

            #[inline]
            fn try_from(value: $name) -> Result<Self, Self::Error> {
                value.try_into_media_container()
            }
        }

        impl TryFrom<MediaContainer> for $name {
            type Error = TryFromMediaItemError;

            fn try_from(container: MediaContainer) -> Result<Self, Self::Error> {
                if let MediaContainer::$name(inner) = container {
                    Ok(inner)
                } else {
                    Err(TryFromMediaItemError {
                        expected: MediaItemType::$name,
                        actual: container.discriminant(),
                    })
                }
            }
        }
    };
}

/// Information about a media item retrieved for HEOS services.
///
/// This usually represents an input source where actual track/artist/album metadata can't be
/// determined, such as from an aux input.
#[derive(Deserialize, Educe, Clone)]
#[educe(Debug)]
pub struct HeosService {
    /// Name of the service.
    pub name: String,
    /// URL to an image representing the service, if it exists.
    #[educe(Debug(method(super::maybe_url::fmt)))]
    #[serde(deserialize_with = "super::maybe_url::deserialize")]
    pub image_url: Option<Url>,
    /// ID of the player the service is from.
    #[serde(rename = "sid")]
    pub src_player_id: PlayerId,
}

impl MediaItemBase for HeosService {
    #[inline]
    fn name(&self) -> &str {
        &self.name
    }

    #[inline]
    fn image_url(&self) -> Option<&Url> {
        self.image_url.as_ref()
    }

    #[inline]
    fn playable(&self) -> bool {
        true
    }

    #[inline]
    fn media_id(&self) -> Option<&str> {
        None
    }

    #[inline]
    fn into_media_item(self) -> MediaItem where Self: Sized {
        MediaItem::HeosService(self)
    }

    #[inline]
    fn as_media_item_ref(&self) -> MediaItemRef<'_> {
        MediaItemRef::HeosService(self)
    }
}

impl_media_item_conversions!(HeosService);

/// Information about a media item retrieved for HEOS servers.
#[derive(Deserialize, Educe, Clone)]
#[educe(Debug)]
pub struct HeosServer {
    /// Name of the server.
    pub name: String,
    /// URL to an image representing the server, if it exists.
    #[educe(Debug(method(super::maybe_url::fmt)))]
    #[serde(deserialize_with = "super::maybe_url::deserialize")]
    pub image_url: Option<Url>,
    /// ID of the player the server is from.
    #[serde(rename = "sid")]
    pub src_player_id: PlayerId,
}

impl MediaItemBase for HeosServer {
    #[inline]
    fn name(&self) -> &str {
        &self.name
    }

    #[inline]
    fn image_url(&self) -> Option<&Url> {
        self.image_url.as_ref()
    }

    #[inline]
    fn playable(&self) -> bool {
        true
    }

    #[inline]
    fn media_id(&self) -> Option<&str> {
        None
    }

    #[inline]
    fn into_media_item(self) -> MediaItem where Self: Sized {
        MediaItem::HeosServer(self)
    }

    #[inline]
    fn as_media_item_ref(&self) -> MediaItemRef<'_> {
        MediaItemRef::HeosServer(self)
    }
}

impl_media_item_conversions!(HeosServer);

/// Information about an artist.
#[derive(Deserialize, Educe, Clone)]
#[educe(Debug)]
pub struct Artist {
    /// Name of the artist.
    pub name: String,
    /// ID representing the artist's "container" (all music by said artist).
    #[serde(rename = "cid")]
    pub container_id: String,
    /// Is the artist directly playable?
    #[serde(deserialize_with = "super::yes_no::deserialize")]
    pub playable: bool,
    /// URL to an image representing the artist, if it exists.
    ///
    /// If this is `None`, it may be able to be retrieved via the
    /// [GetAlbumMetadata](crate::command::browse::GetAlbumMetadata) command.
    #[educe(Debug(method(super::maybe_url::fmt)))]
    #[serde(deserialize_with = "super::maybe_url::deserialize")]
    pub image_url: Option<Url>,
    /// Media ID of this artist, if it's playable.
    #[serde(rename = "mid")]
    pub media_id: Option<String>,
}

impl MediaItemBase for Artist {
    #[inline]
    fn name(&self) -> &str {
        &self.name
    }

    #[inline]
    fn image_url(&self) -> Option<&Url> {
        self.image_url.as_ref()
    }

    #[inline]
    fn playable(&self) -> bool {
        self.playable
    }

    #[inline]
    fn media_id(&self) -> Option<&str> {
        self.media_id.as_deref()
    }

    #[inline]
    fn into_media_item(self) -> MediaItem where Self: Sized {
        MediaItem::Artist(self)
    }

    #[inline]
    fn as_media_item_ref(&self) -> MediaItemRef<'_> {
        MediaItemRef::Artist(self)
    }

    #[inline]
    fn try_into_media_container(self) -> Result<MediaContainer, Self> where Self: Sized {
        Ok(MediaContainer::Artist(self))
    }

    #[inline]
    fn try_as_media_container_ref(&self) -> Option<MediaContainerRef<'_>> {
        Some(MediaContainerRef::Artist(self))
    }
}

impl MediaContainerBase for Artist {
    #[inline]
    fn container_id(&self) -> &str {
        &self.container_id
    }

    #[inline]
    fn into_media_container(self) -> MediaContainer where Self: Sized {
        MediaContainer::Artist(self)
    }

    #[inline]
    fn as_media_container_ref(&self) -> MediaContainerRef<'_> {
        MediaContainerRef::Artist(self)
    }
}

impl_media_item_conversions!(Artist);
impl_media_container_conversions!(Artist);

/// Information about an album.
#[derive(Deserialize, Educe, Clone)]
#[educe(Debug)]
pub struct Album {
    /// Name of the album.
    pub name: String,
    /// Name of the album's artist.
    pub artist: String,
    /// ID representing the album.
    #[serde(rename = "cid")]
    pub container_id: String,
    /// Is the album directly playable?
    #[serde(deserialize_with = "super::yes_no::deserialize")]
    pub playable: bool,
    /// URL to an image representing the album, if it exists.
    ///
    /// If this is `None`, it may be able to be retrieved via the
    /// [GetAlbumMetadata](crate::command::browse::GetAlbumMetadata) command.
    #[educe(Debug(method(super::maybe_url::fmt)))]
    #[serde(deserialize_with = "super::maybe_url::deserialize")]
    pub image_url: Option<Url>,
    /// Media ID of this album, if it's playable.
    #[serde(rename = "mid")]
    pub media_id: Option<String>,
}

impl MediaItemBase for Album {
    #[inline]
    fn name(&self) -> &str {
        &self.name
    }

    #[inline]
    fn artist(&self) -> Option<&str> {
        Some(&self.artist)
    }

    #[inline]
    fn image_url(&self) -> Option<&Url> {
        self.image_url.as_ref()
    }

    #[inline]
    fn playable(&self) -> bool {
        self.playable
    }

    #[inline]
    fn media_id(&self) -> Option<&str> {
        self.media_id.as_deref()
    }

    #[inline]
    fn into_media_item(self) -> MediaItem where Self: Sized {
        MediaItem::Album(self)
    }

    #[inline]
    fn as_media_item_ref(&self) -> MediaItemRef<'_> {
        MediaItemRef::Album(self)
    }

    #[inline]
    fn try_into_media_container(self) -> Result<MediaContainer, Self> where Self: Sized {
        Ok(MediaContainer::Album(self))
    }

    #[inline]
    fn try_as_media_container_ref(&self) -> Option<MediaContainerRef<'_>> {
        Some(MediaContainerRef::Album(self))
    }
}

impl MediaContainerBase for Album {
    #[inline]
    fn container_id(&self) -> &str {
        &self.container_id
    }

    #[inline]
    fn into_media_container(self) -> MediaContainer where Self: Sized {
        MediaContainer::Album(self)
    }

    #[inline]
    fn as_media_container_ref(&self) -> MediaContainerRef<'_> {
        MediaContainerRef::Album(self)
    }
}

impl_media_item_conversions!(Album);
impl_media_container_conversions!(Album);

/// Information about a song.
#[derive(Deserialize, Educe, Clone)]
#[educe(Debug)]
pub struct Song {
    /// Name of the song.
    pub name: String,
    /// Name of the song's artist.
    pub artist: String,
    /// Name of the album the song is from.
    ///
    /// This may be blank if the song doesn't belong to an album.
    pub album: String,
    #[serde(rename = "playable", deserialize_with = "super::yes_no::deserialize_assert_yes")]
    _playable: bool,
    /// URL to an image representing the song, if it exists.
    ///
    /// If this is `None`, it may be able to be retrieved via the
    /// [GetAlbumMetadata](crate::command::browse::GetAlbumMetadata) command.
    #[educe(Debug(method(super::maybe_url::fmt)))]
    #[serde(deserialize_with = "super::maybe_url::deserialize")]
    pub image_url: Option<Url>,
    /// ID representing this media item.
    #[serde(rename = "mid")]
    pub media_id: String,
}

impl MediaItemBase for Song {
    #[inline]
    fn name(&self) -> &str {
        &self.name
    }

    #[inline]
    fn artist(&self) -> Option<&str> {
        Some(&self.artist)
    }

    #[inline]
    fn album(&self) -> Option<&str> {
        Some(&self.album)
    }

    #[inline]
    fn image_url(&self) -> Option<&Url> {
        self.image_url.as_ref()
    }

    #[inline]
    fn playable(&self) -> bool {
        true
    }

    #[inline]
    fn media_id(&self) -> Option<&str> {
        Some(&self.media_id)
    }

    #[inline]
    fn into_media_item(self) -> MediaItem where Self: Sized {
        MediaItem::Song(self)
    }

    #[inline]
    fn as_media_item_ref(&self) -> MediaItemRef<'_> {
        MediaItemRef::Song(self)
    }
}

impl From<QueuedTrackInfo> for Song {
    #[inline]
    fn from(value: QueuedTrackInfo) -> Self {
        Song {
            name: value.song,
            artist: value.artist,
            album: value.album,
            _playable: true,
            image_url: value.image_url,
            media_id: value.media_id,
        }
    }
}

impl_media_item_conversions!(Song);

/// Information about a generic music container.
#[derive(Deserialize, Educe, Clone)]
#[educe(Debug)]
pub struct Container {
    /// Name of the container.
    pub name: String,
    /// ID of the container.
    #[serde(rename = "cid")]
    pub container_id: String,
    /// Is the container directly playable?
    #[serde(deserialize_with = "super::yes_no::deserialize")]
    pub playable: bool,
    /// URL to an image representing the container, if it exists.
    ///
    /// If this is `None`, it may be able to be retrieved via the
    /// [GetAlbumMetadata](crate::command::browse::GetAlbumMetadata) command.
    #[educe(Debug(method(super::maybe_url::fmt)))]
    #[serde(deserialize_with = "super::maybe_url::deserialize")]
    pub image_url: Option<Url>,
    /// Media ID of this container, if it's playable.
    #[serde(rename = "mid")]
    pub media_id: Option<String>,
}

impl MediaItemBase for Container {
    #[inline]
    fn name(&self) -> &str {
        &self.name
    }

    #[inline]
    fn image_url(&self) -> Option<&Url> {
        self.image_url.as_ref()
    }

    #[inline]
    fn playable(&self) -> bool {
        self.playable
    }

    #[inline]
    fn media_id(&self) -> Option<&str> {
        self.media_id.as_deref()
    }

    #[inline]
    fn into_media_item(self) -> MediaItem where Self: Sized {
        MediaItem::Container(self)
    }

    #[inline]
    fn as_media_item_ref(&self) -> MediaItemRef<'_> {
        MediaItemRef::Container(self)
    }

    #[inline]
    fn try_into_media_container(self) -> Result<MediaContainer, Self> where Self: Sized {
        Ok(MediaContainer::Container(self))
    }

    #[inline]
    fn try_as_media_container_ref(&self) -> Option<MediaContainerRef<'_>> {
        Some(MediaContainerRef::Container(self))
    }
}

impl MediaContainerBase for Container {
    #[inline]
    fn container_id(&self) -> &str {
        &self.container_id
    }

    #[inline]
    fn into_media_container(self) -> MediaContainer where Self: Sized {
        MediaContainer::Container(self)
    }

    #[inline]
    fn as_media_container_ref(&self) -> MediaContainerRef<'_> {
        MediaContainerRef::Container(self)
    }
}

impl_media_item_conversions!(Container);
impl_media_container_conversions!(Container);

/// Information about a music station.
#[derive(Deserialize, Educe, Clone)]
#[educe(Debug)]
pub struct Station {
    /// Name of the station.
    pub name: String,
    #[serde(rename = "playable", deserialize_with = "super::yes_no::deserialize_assert_yes")]
    _playable: bool,
    /// URL to an image representing the station, if it exists.
    #[educe(Debug(method(super::maybe_url::fmt)))]
    #[serde(deserialize_with = "super::maybe_url::deserialize")]
    pub image_url: Option<Url>,
    /// Media ID of this station.
    #[serde(rename = "mid")]
    pub media_id: String,
}

impl MediaItemBase for Station {
    #[inline]
    fn name(&self) -> &str {
        &self.name
    }

    #[inline]
    fn image_url(&self) -> Option<&Url> {
        self.image_url.as_ref()
    }

    #[inline]
    fn playable(&self) -> bool {
        true
    }

    #[inline]
    fn media_id(&self) -> Option<&str> {
        Some(&self.media_id)
    }

    #[inline]
    fn into_media_item(self) -> MediaItem where Self: Sized {
        MediaItem::Station(self)
    }

    #[inline]
    fn as_media_item_ref(&self) -> MediaItemRef<'_> {
        MediaItemRef::Station(self)
    }
}

impl_media_item_conversions!(Station);

/// Information about a music genre, used as a container.
#[derive(Deserialize, Educe, Clone)]
#[educe(Debug)]
pub struct Genre {
    /// Name of the genre.
    pub name: String,
    #[serde(rename = "playable", deserialize_with = "super::yes_no::deserialize_assert_yes")]
    _playable: bool,
    /// URL to an image representing the genre, if it exists.
    #[educe(Debug(method(super::maybe_url::fmt)))]
    #[serde(deserialize_with = "super::maybe_url::deserialize")]
    pub image_url: Option<Url>,
    /// Media ID of this genre.
    #[serde(rename = "mid")]
    pub media_id: String,
}

impl MediaItemBase for Genre {
    #[inline]
    fn name(&self) -> &str {
        &self.name
    }

    #[inline]
    fn image_url(&self) -> Option<&Url> {
        self.image_url.as_ref()
    }

    #[inline]
    fn playable(&self) -> bool {
        true
    }

    #[inline]
    fn media_id(&self) -> Option<&str> {
        Some(&self.media_id)
    }

    #[inline]
    fn into_media_item(self) -> MediaItem where Self: Sized {
        MediaItem::Genre(self)
    }

    #[inline]
    fn as_media_item_ref(&self) -> MediaItemRef<'_> {
        MediaItemRef::Genre(self)
    }
}

impl_media_item_conversions!(Genre);

macro_rules! delegate_media_item {
    (
        $(#[$attr:meta])*
        $v:vis fn $fn_name:ident(&self) -> $ret_type:ty;
    ) => {
        $(#[$attr])*
        $v fn $fn_name(&self) -> $ret_type {
            match self {
                Self::HeosService(heos_service) => heos_service.$fn_name(),
                Self::HeosServer(heos_server) => heos_server.$fn_name(),
                Self::Artist(artist) => artist.$fn_name(),
                Self::Album(album) => album.$fn_name(),
                Self::Song(song) => song.$fn_name(),
                Self::Container(container) => container.$fn_name(),
                Self::Station(station) => station.$fn_name(),
                Self::Genre(genre) => genre.$fn_name(),
            }
        }
    };
    (
        $(#[$attr:meta])*
        $v:vis fn $fn_name:ident(self) -> $ret_type:ty;
    ) => {
        $(#[$attr])*
        $v fn $fn_name(self) -> $ret_type where Self: Sized {
            match self {
                Self::HeosService(heos_service) => heos_service.$fn_name(),
                Self::HeosServer(heos_server) => heos_server.$fn_name(),
                Self::Artist(artist) => artist.$fn_name(),
                Self::Album(album) => album.$fn_name(),
                Self::Song(song) => song.$fn_name(),
                Self::Container(container) => container.$fn_name(),
                Self::Station(station) => station.$fn_name(),
                Self::Genre(genre) => genre.$fn_name(),
            }
        }
    };
}

/// A single item yielded from a [Browse](crate::command::browse::Browse) or
/// [Search](crate::command::browse::Search) command.
#[derive(Deserialize, EnumDiscriminants, Debug, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
#[strum_discriminants(name(MediaItemType))]
pub enum MediaItem {
    /// Items yielded by [HEOS services](SourceType::HeosService).
    HeosService(HeosService),
    /// Items yielded by [HEOS servers](SourceType::HeosServer).
    HeosServer(HeosServer),
    /// A music artist.
    Artist(Artist),
    /// An album of tracks.
    Album(Album),
    /// A single track.
    Song(Song),
    /// A generic container of music.
    ///
    /// Could be e.g. a folder in a Windows Media Share.
    Container(Container),
    /// A music station.
    Station(Station),
    /// A genre of music being used as a container.
    Genre(Genre),
}
impl_has_options!(Vec<MediaItem>, "browse");
impl_try_from_response_payload!(Vec<MediaItem>);

impl From<QueuedTrackInfo> for MediaItem {
    #[inline]
    fn from(value: QueuedTrackInfo) -> Self {
        Self::Song(Song::from(value))
    }
}

impl MediaItemBase for MediaItem {
    delegate_media_item! {
        #[inline]
        fn name(&self) -> &str;
    }

    delegate_media_item! {
        #[inline]
        fn image_url(&self) -> Option<&Url>;
    }

    delegate_media_item! {
        #[inline]
        fn playable(&self) -> bool;
    }

    delegate_media_item! {
        #[inline]
        fn media_id(&self) -> Option<&str>;
    }

    #[inline]
    fn into_media_item(self) -> MediaItem where Self: Sized {
        self
    }

    #[inline]
    fn as_media_item_ref(&self) -> MediaItemRef<'_> {
        match self {
            Self::HeosService(heos_service) => MediaItemRef::HeosService(heos_service),
            Self::HeosServer(heos_server) => MediaItemRef::HeosServer(heos_server),
            Self::Artist(artist) => MediaItemRef::Artist(artist),
            Self::Album(album) => MediaItemRef::Album(album),
            Self::Song(song) => MediaItemRef::Song(song),
            Self::Container(container) => MediaItemRef::Container(container),
            Self::Station(station) => MediaItemRef::Station(station),
            Self::Genre(genre) => MediaItemRef::Genre(genre),
        }
    }

    #[inline]
    fn try_into_media_container(self) -> Result<MediaContainer, Self> where Self: Sized {
        match self {
            Self::Artist(artist) => Ok(MediaContainer::Artist(artist)),
            Self::Album(album) => Ok(MediaContainer::Album(album)),
            Self::Container(container) => Ok(MediaContainer::Container(container)),
            other => Err(other),
        }
    }

    #[inline]
    fn try_as_media_container_ref(&self) -> Option<MediaContainerRef<'_>> {
        match self {
            Self::Artist(artist) => Some(MediaContainerRef::Artist(artist)),
            Self::Album(album) => Some(MediaContainerRef::Album(album)),
            Self::Container(container) => Some(MediaContainerRef::Container(container)),
            _ => None,
        }
    }
}

/// A single item yielded from a [Browse](crate::command::browse::Browse) or
/// [Search](crate::command::browse::Search) command.
///
/// This type is a reference to a media item. It is to [MediaItem] what `&str` is to `String`.
#[derive(Debug, Clone)]
pub enum MediaItemRef<'a> {
    /// Items yielded by [HEOS services](SourceType::HeosService).
    HeosService(&'a HeosService),
    /// Items yielded by [HEOS servers](SourceType::HeosServer).
    HeosServer(&'a HeosServer),
    /// A music artist.
    Artist(&'a Artist),
    /// An album of tracks.
    Album(&'a Album),
    /// A single track.
    Song(&'a Song),
    /// A generic container of music.
    ///
    /// Could be e.g. a folder in a Windows Media Share.
    Container(&'a Container),
    /// A music station.
    Station(&'a Station),
    /// A genre of music being used as a container.
    Genre(&'a Genre),
}

impl<'a> IntoDiscriminant for MediaItemRef<'a> {
    type Discriminant = MediaItemType;

    fn discriminant(&self) -> Self::Discriminant {
        match self {
            Self::HeosService(_) => MediaItemType::HeosService,
            Self::HeosServer(_) => MediaItemType::HeosServer,
            Self::Artist(_) => MediaItemType::Artist,
            Self::Album(_) => MediaItemType::Album,
            Self::Song(_) => MediaItemType::Song,
            Self::Container(_) => MediaItemType::Container,
            Self::Station(_) => MediaItemType::Station,
            Self::Genre(_) => MediaItemType::Genre,
        }
    }
}

impl<'a> MediaItemBase for MediaItemRef<'a> {
    delegate_media_item! {
        #[inline]
        fn name(&self) -> &str;
    }

    delegate_media_item! {
        #[inline]
        fn image_url(&self) -> Option<&Url>;
    }

    delegate_media_item! {
        #[inline]
        fn playable(&self) -> bool;
    }

    delegate_media_item! {
        #[inline]
        fn media_id(&self) -> Option<&str>;
    }

    #[inline]
    fn into_media_item(self) -> MediaItem where Self: Sized {
        match self {
            Self::HeosService(heos_service) => MediaItem::HeosService(heos_service.clone()),
            Self::HeosServer(heos_server) => MediaItem::HeosServer(heos_server.clone()),
            Self::Artist(artist) => MediaItem::Artist(artist.clone()),
            Self::Album(album) => MediaItem::Album(album.clone()),
            Self::Song(song) => MediaItem::Song(song.clone()),
            Self::Container(container) => MediaItem::Container(container.clone()),
            Self::Station(station) => MediaItem::Station(station.clone()),
            Self::Genre(genre) => MediaItem::Genre(genre.clone()),
        }
    }

    #[inline]
    fn as_media_item_ref(&self) -> MediaItemRef<'_> {
        self.clone()
    }

    #[inline]
    fn try_into_media_container(self) -> Result<MediaContainer, Self> where Self: Sized {
        match self {
            Self::Artist(artist) => Ok(MediaContainer::Artist(artist.clone())),
            Self::Album(album) => Ok(MediaContainer::Album(album.clone())),
            Self::Container(container) => Ok(MediaContainer::Container(container.clone())),
            other => Err(other),
        }
    }

    #[inline]
    fn try_as_media_container_ref(&self) -> Option<MediaContainerRef<'_>> {
        match self {
            Self::Artist(artist) => Some(MediaContainerRef::Artist(artist)),
            Self::Album(album) => Some(MediaContainerRef::Album(album)),
            Self::Container(container) => Some(MediaContainerRef::Container(container)),
            _ => None,
        }
    }
}

impl<'a> From<MediaItemRef<'a>> for MediaItem {
    #[inline]
    fn from(item_ref: MediaItemRef<'a>) -> Self {
        item_ref.into_media_item()
    }
}

impl<'a> TryFrom<MediaItemRef<'a>> for MediaContainer {
    type Error = MediaItemRef<'a>;

    #[inline]
    fn try_from(value: MediaItemRef<'a>) -> Result<Self, Self::Error> {
        value.try_into_media_container()
    }
}

macro_rules! delegate_media_container {
    (
        $(#[$attr:meta])*
        $v:vis fn $fn_name:ident(&self) -> $ret_type:ty;
    ) => {
        $(#[$attr])*
        $v fn $fn_name(&self) -> $ret_type {
            match self {
                Self::Artist(artist) => artist.$fn_name(),
                Self::Album(album) => album.$fn_name(),
                Self::Container(container) => container.$fn_name(),
            }
        }
    };
    (
        $(#[$attr:meta])*
        $v:vis fn $fn_name:ident(self) -> $ret_type:ty;
    ) => {
        $(#[$attr])*
        $v fn $fn_name(self) -> $ret_type where Self: Sized {
            match self {
                Self::Artist(artist) => artist.$fn_name(),
                Self::Album(album) => album.$fn_name(),
                Self::Container(container) => container.$fn_name(),
            }
        }
    };
}

/// A single item yielded from a [Browse](crate::command::browse::Browse) or
/// [Search](crate::command::browse::Search) command, that is a container.
///
/// This type isn't yielded directly from commands, but can be retrieved via
/// [`MediaContainer::try_from()`] from a [MediaItem].
#[derive(Debug, Clone)]
pub enum MediaContainer {
    /// A music artist.
    Artist(Artist),
    /// An album of tracks.
    Album(Album),
    /// A generic container of music.
    ///
    /// Could be e.g. a folder in a Windows Media Share.
    Container(Container),
}

impl IntoDiscriminant for MediaContainer {
    type Discriminant = MediaItemType;

    fn discriminant(&self) -> Self::Discriminant {
        match self {
            Self::Artist(_) => Self::Discriminant::Artist,
            Self::Album(_) => Self::Discriminant::Album,
            Self::Container(_) => Self::Discriminant::Container,
        }
    }
}

impl MediaItemBase for MediaContainer {
    delegate_media_container! {
        #[inline]
        fn name(&self) -> &str;
    }

    delegate_media_container! {
        #[inline]
        fn image_url(&self) -> Option<&Url>;
    }

    delegate_media_container! {
        #[inline]
        fn playable(&self) -> bool;
    }

    delegate_media_container! {
        #[inline]
        fn media_id(&self) -> Option<&str>;
    }

    #[inline]
    fn into_media_item(self) -> MediaItem where Self: Sized {
        match self {
            Self::Artist(artist) => MediaItem::Artist(artist),
            Self::Album(album) => MediaItem::Album(album),
            Self::Container(container) => MediaItem::Container(container),
        }
    }

    #[inline]
    fn as_media_item_ref(&self) -> MediaItemRef<'_> {
        match self {
            Self::Artist(artist) => MediaItemRef::Artist(artist),
            Self::Album(album) => MediaItemRef::Album(album),
            Self::Container(container) => MediaItemRef::Container(container),
        }
    }

    #[inline]
    fn try_into_media_container(self) -> Result<MediaContainer, Self> where Self: Sized {
        Ok(self)
    }

    #[inline]
    fn try_as_media_container_ref(&self) -> Option<MediaContainerRef<'_>> {
        Some(match self {
            Self::Artist(artist) => MediaContainerRef::Artist(artist),
            Self::Album(album) => MediaContainerRef::Album(album),
            Self::Container(container) => MediaContainerRef::Container(container),
        })
    }
}

impl MediaContainerBase for MediaContainer {
    delegate_media_container! {
        #[inline]
        fn container_id(&self) -> &str;
    }

    #[inline]
    fn into_media_container(self) -> MediaContainer where Self: Sized {
        self
    }

    #[inline]
    fn as_media_container_ref(&self) -> MediaContainerRef<'_> {
        match self {
            Self::Artist(artist) => MediaContainerRef::Artist(artist),
            Self::Album(album) => MediaContainerRef::Album(album),
            Self::Container(container) => MediaContainerRef::Container(container),
        }
    }
}

impl From<MediaContainer> for MediaItem {
    fn from(container: MediaContainer) -> Self {
        container.into_media_item()
    }
}

impl TryFrom<MediaItem> for MediaContainer {
    type Error = MediaItem;

    fn try_from(item: MediaItem) -> Result<Self, Self::Error> {
        item.try_into_media_container()
    }
}

/// A single item yielded from a [Browse](crate::command::browse::Browse) or
/// [Search](crate::command::browse::Search) command, that is a container.
///
/// This type is a reference to a container type. It is to [MediaContainer] what `&str` is to
/// `String`.
#[derive(Debug, Clone, Copy)]
pub enum MediaContainerRef<'a> {
    /// A music artist.
    Artist(&'a Artist),
    /// An album of tracks.
    Album(&'a Album),
    /// A generic container of music.
    ///
    /// Could be e.g. a folder in a Windows Media Share.
    Container(&'a Container),
}

impl<'a> IntoDiscriminant for MediaContainerRef<'a> {
    type Discriminant = MediaItemType;

    fn discriminant(&self) -> Self::Discriminant {
        match self {
            Self::Artist(_) => Self::Discriminant::Artist,
            Self::Album(_) => Self::Discriminant::Album,
            Self::Container(_) => Self::Discriminant::Container,
        }
    }
}

impl<'a> MediaItemBase for MediaContainerRef<'a> {
    delegate_media_container! {
        #[inline]
        fn name(&self) -> &str;
    }

    delegate_media_container! {
        #[inline]
        fn image_url(&self) -> Option<&Url>;
    }

    delegate_media_container! {
        #[inline]
        fn playable(&self) -> bool;
    }

    delegate_media_container! {
        #[inline]
        fn media_id(&self) -> Option<&str>;
    }

    #[inline]
    fn into_media_item(self) -> MediaItem where Self: Sized {
        match self {
            Self::Artist(artist) => MediaItem::Artist(artist.clone()),
            Self::Album(album) => MediaItem::Album(album.clone()),
            Self::Container(container) => MediaItem::Container(container.clone()),
        }
    }

    #[inline]
    fn as_media_item_ref(&self) -> MediaItemRef<'_> {
        match self {
            Self::Artist(artist) => MediaItemRef::Artist(artist),
            Self::Album(album) => MediaItemRef::Album(album),
            Self::Container(container) => MediaItemRef::Container(container),
        }
    }

    #[inline]
    fn try_into_media_container(self) -> Result<MediaContainer, Self> where Self: Sized {
        Ok(match self {
            Self::Artist(artist) => MediaContainer::Artist(artist.clone()),
            Self::Album(album) => MediaContainer::Album(album.clone()),
            Self::Container(container) => MediaContainer::Container(container.clone()),
        })
    }

    #[inline]
    fn try_as_media_container_ref(&self) -> Option<MediaContainerRef<'_>> {
        Some(self.clone())
    }
}

impl<'a> MediaContainerBase for MediaContainerRef<'a> {
    delegate_media_container! {
        #[inline]
        fn container_id(&self) -> &str;
    }

    #[inline]
    fn into_media_container(self) -> MediaContainer where Self: Sized {
        match self {
            Self::Artist(artist) => MediaContainer::Artist(artist.clone()),
            Self::Album(album) => MediaContainer::Album(album.clone()),
            Self::Container(container) => MediaContainer::Container(container.clone()),
        }
    }

    #[inline]
    fn as_media_container_ref(&self) -> MediaContainerRef<'_> {
        self.clone()
    }
}

impl<'a> From<MediaContainerRef<'a>> for MediaItem {
    #[inline]
    fn from(container_ref: MediaContainerRef) -> Self {
        container_ref.into_media_item()
    }
}

impl<'a> From<MediaContainerRef<'a>> for MediaContainer {
    #[inline]
    fn from(container_ref: MediaContainerRef<'a>) -> Self {
        container_ref.into_media_container()
    }
}

/// Results of using a [Browse](crate::command::browse::Browse) or
/// [Search](crate::command::browse::Search) command.
#[derive(Debug, Clone)]
pub struct MediaItemsResponse {
    /// How many total items are available in the container being browsed/searched.
    ///
    /// If this is larger than the size of `items`, the command needs to be repeated until all
    /// results are retrieved.
    pub count: usize,
    /// Collection of search results.
    ///
    /// This will not be larger than the maximum range specified in the
    /// [Browse](crate::command::browse::Browse) or [Search](crate::command::browse::Search)
    /// command, or the default maximum if a range is not specified.
    pub items: Vec<MediaItem>,
}
impl_has_options!(MediaItemsResponse, "browse");

impl TryFrom<RawResponse> for MediaItemsResponse {
    type Error = CommandError;

    fn try_from(response: RawResponse) -> Result<Self, Self::Error> {
        let qs = QString::from(response.heos.message.as_str());
        let count: usize = qs.get("count")
            .ok_or(CommandError::response_missing_field("message.count"))?
            .parse()
            .map_err(|err| CommandError::MalformedResponse(format!(
                "could not parse 'count': {err:?}"
            )))?;
        let items = Vec::<MediaItem>::try_from(response)?;
        Ok(Self {
            count,
            items,
        })
    }
}

/// Metadata about a particular album's art.
///
/// This contains e.g. the album art URL for an album.
#[derive(Deserialize, Educe)]
#[educe(Debug)]
pub struct AlbumImageMetadata {
    /// URL to the album's art.
    #[educe(Debug(method(std::fmt::Display::fmt)))]
    pub image_url: Url,
    /// Image width.
    pub width: usize,
}

/// Metadata about a particular album.
#[derive(Deserialize, Debug)]
pub struct AlbumMetadata {
    /// ID of the album.
    pub album_id: String,
    /// One or more album art images associated with the album.
    ///
    /// These may be the same image at multiple sizes, so the image with the most optimum size
    /// should be chosen.
    pub images: Vec<AlbumImageMetadata>,
}
impl_try_from_response_payload!(Vec<AlbumMetadata>);