mecomp_daemon/
controller.rs

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
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
//----------------------------------------------------------------------------------------- std lib
use std::{ops::Range, sync::Arc, time::Duration};
//--------------------------------------------------------------------------------- other libraries
use ::tarpc::context::Context;
use log::{debug, error, info, warn};
use rand::seq::SliceRandom;
use surrealdb::{engine::local::Db, Surreal};
use tap::TapFallible;
use tracing::instrument;
//-------------------------------------------------------------------------------- MECOMP libraries
use mecomp_core::{
    audio::{
        commands::{AudioCommand, QueueCommand, VolumeCommand},
        AudioKernelSender,
    },
    errors::SerializableLibraryError,
    rpc::{AlbumId, ArtistId, CollectionId, MusicPlayer, PlaylistId, SearchResult, SongId},
    state::{
        library::{LibraryBrief, LibraryFull, LibraryHealth},
        RepeatMode, SeekType, StateAudio, StateRuntime,
    },
};
use mecomp_storage::{
    db::schemas::{
        self,
        album::{Album, AlbumBrief},
        artist::{Artist, ArtistBrief},
        collection::{Collection, CollectionBrief},
        playlist::{Playlist, PlaylistBrief},
        song::{Song, SongBrief},
    },
    errors::Error::{self, NotFound},
};
use one_or_many::OneOrMany;

use crate::{
    config::Settings,
    services::{self, get_songs_from_things},
};

mod locks {
    use tokio::sync::Mutex;

    pub static LIBRARY_RESCAN_LOCK: Mutex<()> = Mutex::const_new(());
    pub static LIBRARY_ANALYZE_LOCK: Mutex<()> = Mutex::const_new(());
    pub static COLLECTION_RECLUSTER_LOCK: Mutex<()> = Mutex::const_new(());
}

#[derive(Clone, Debug)]
pub struct MusicPlayerServer {
    db: Arc<Surreal<Db>>,
    settings: Arc<Settings>,
    audio_kernel: Arc<AudioKernelSender>,
}

impl MusicPlayerServer {
    #[must_use]
    pub const fn new(
        db: Arc<Surreal<Db>>,
        settings: Arc<Settings>,
        audio_kernel: Arc<AudioKernelSender>,
    ) -> Self {
        Self {
            db,
            settings,
            audio_kernel,
        }
    }
}

impl MusicPlayer for MusicPlayerServer {
    #[instrument]
    async fn ping(self, context: Context) -> String {
        "pong".to_string()
    }

    /// Rescans the music library, only error is if a rescan is already in progress.
    #[instrument]
    async fn library_rescan(self, context: Context) -> Result<(), SerializableLibraryError> {
        info!("Rescanning library");

        if locks::LIBRARY_RESCAN_LOCK.try_lock().is_err() {
            warn!("Library rescan already in progress");
            return Err(SerializableLibraryError::RescanInProgress);
        }

        std::thread::Builder::new()
            .name(String::from("Library Rescan"))
            .spawn(move || {
                futures::executor::block_on(async {
                    let _guard = locks::LIBRARY_RESCAN_LOCK.lock().await;
                    match services::library::rescan(
                        &self.db,
                        &self.settings.daemon.library_paths,
                        &self.settings.daemon.artist_separator,
                        self.settings.daemon.genre_separator.as_deref(),
                        self.settings.daemon.conflict_resolution,
                    )
                    .await
                    {
                        Ok(()) => info!("Library rescan complete"),
                        Err(e) => error!("Error in library_rescan: {e}"),
                    }
                });
            })?;

        Ok(())
    }
    /// Check if a rescan is in progress.
    #[instrument]
    async fn library_rescan_in_progress(self, context: Context) -> bool {
        locks::LIBRARY_RESCAN_LOCK.try_lock().is_err()
    }
    /// Analyze the music library, only error is if an analysis is already in progress.
    #[instrument]
    async fn library_analyze(self, context: Context) -> Result<(), SerializableLibraryError> {
        #[cfg(not(feature = "analysis"))]
        {
            warn!("Analysis is not enabled");
            return Err(SerializableLibraryError::AnalysisNotEnabled);
        }

        #[cfg(feature = "analysis")]
        {
            info!("Analyzing library");

            if locks::LIBRARY_ANALYZE_LOCK.try_lock().is_err() {
                warn!("Library analysis already in progress");
                return Err(SerializableLibraryError::AnalysisInProgress);
            }

            std::thread::Builder::new()
                .name(String::from("Library Analysis"))
                .spawn(move || {
                    futures::executor::block_on(async {
                        let _guard = locks::LIBRARY_ANALYZE_LOCK.lock().await;
                        match services::library::analyze(&self.db).await {
                            Ok(()) => info!("Library analysis complete"),
                            Err(e) => error!("Error in library_analyze: {e}"),
                        }
                    });
                })?;

            Ok(())
        }
    }
    /// Check if an analysis is in progress.
    #[instrument]
    async fn library_analyze_in_progress(self, context: Context) -> bool {
        locks::LIBRARY_ANALYZE_LOCK.try_lock().is_err()
    }
    /// Recluster the music library, only error is if a recluster is already in progress.
    #[instrument]
    async fn library_recluster(self, context: Context) -> Result<(), SerializableLibraryError> {
        #[cfg(not(feature = "analysis"))]
        {
            warn!("Analysis is not enabled");
            return Err(SerializableLibraryError::AnalysisNotEnabled);
        }

        #[cfg(feature = "analysis")]
        {
            info!("Reclustering collections");

            if locks::COLLECTION_RECLUSTER_LOCK.try_lock().is_err() {
                warn!("Collection reclustering already in progress");
                return Err(SerializableLibraryError::ReclusterInProgress);
            }

            std::thread::Builder::new()
                .name(String::from("Collection Recluster"))
                .spawn(move || {
                    futures::executor::block_on(async {
                        let _guard = locks::COLLECTION_RECLUSTER_LOCK.lock().await;
                        match services::library::recluster(&self.db, &self.settings.reclustering)
                            .await
                        {
                            Ok(()) => info!("Collection reclustering complete"),
                            Err(e) => error!("Error in collection_recluster: {e}"),
                        }
                    });
                })?;

            Ok(())
        }
    }
    /// Check if a recluster is in progress.
    #[instrument]
    async fn library_recluster_in_progress(self, context: Context) -> bool {
        locks::COLLECTION_RECLUSTER_LOCK.try_lock().is_err()
    }
    /// Returns brief information about the music library.
    #[instrument]
    async fn library_brief(
        self,
        context: Context,
    ) -> Result<LibraryBrief, SerializableLibraryError> {
        info!("Creating library brief");
        Ok(services::library::brief(&self.db)
            .await
            .tap_err(|e| warn!("Error in library_brief: {e}"))?)
    }
    /// Returns full information about the music library. (all songs, artists, albums, etc.)
    #[instrument]
    async fn library_full(self, context: Context) -> Result<LibraryFull, SerializableLibraryError> {
        info!("Creating library full");
        Ok(services::library::full(&self.db)
            .await
            .tap_err(|e| warn!("Error in library_full: {e}"))?)
    }
    /// Returns brief information about the music library's artists.
    #[instrument]
    async fn library_artists_brief(
        self,
        context: Context,
    ) -> Result<Box<[ArtistBrief]>, SerializableLibraryError> {
        info!("Creating library artists brief");
        Ok(Artist::read_all(&self.db)
            .await
            .tap_err(|e| warn!("Error in library_artists_brief: {e}"))?
            .iter()
            .map(std::convert::Into::into)
            .collect())
    }
    /// Returns full information about the music library's artists.
    #[instrument]
    async fn library_artists_full(
        self,
        context: Context,
    ) -> Result<Box<[Artist]>, SerializableLibraryError> {
        info!("Creating library artists full");
        Ok(Artist::read_all(&self.db)
            .await
            .map(std::vec::Vec::into_boxed_slice)
            .tap_err(|e| warn!("Error in library_artists_brief: {e}"))?)
    }
    /// Returns brief information about the music library's albums.
    #[instrument]
    async fn library_albums_brief(
        self,
        context: Context,
    ) -> Result<Box<[AlbumBrief]>, SerializableLibraryError> {
        info!("Creating library albums brief");
        Ok(Album::read_all(&self.db)
            .await
            .tap_err(|e| warn!("Error in library_albums_brief: {e}"))?
            .iter()
            .map(std::convert::Into::into)
            .collect())
    }
    /// Returns full information about the music library's albums.
    #[instrument]
    async fn library_albums_full(
        self,
        context: Context,
    ) -> Result<Box<[Album]>, SerializableLibraryError> {
        info!("Creating library albums full");
        Ok(Album::read_all(&self.db)
            .await
            .map(std::vec::Vec::into_boxed_slice)
            .tap_err(|e| warn!("Error in library_albums_full: {e}"))?)
    }
    /// Returns brief information about the music library's songs.
    #[instrument]
    async fn library_songs_brief(
        self,
        context: Context,
    ) -> Result<Box<[SongBrief]>, SerializableLibraryError> {
        info!("Creating library songs brief");
        Ok(Song::read_all(&self.db)
            .await
            .tap_err(|e| warn!("Error in library_songs_brief: {e}"))?
            .iter()
            .map(std::convert::Into::into)
            .collect())
    }
    /// Returns full information about the music library's songs.
    #[instrument]
    async fn library_songs_full(
        self,
        context: Context,
    ) -> Result<Box<[Song]>, SerializableLibraryError> {
        info!("Creating library songs full");
        Ok(Song::read_all(&self.db)
            .await
            .map(std::vec::Vec::into_boxed_slice)
            .tap_err(|e| warn!("Error in library_songs_full: {e}"))?)
    }
    /// Returns information about the health of the music library (are there any missing files, etc.)
    #[instrument]
    async fn library_health(
        self,
        context: Context,
    ) -> Result<LibraryHealth, SerializableLibraryError> {
        info!("Creating library health");
        Ok(services::library::health(&self.db)
            .await
            .tap_err(|e| warn!("Error in library_health: {e}"))?)
    }
    /// Get a song by its ID.
    #[instrument]
    async fn library_song_get(self, context: Context, id: SongId) -> Option<Song> {
        let id = id.into();
        info!("Getting song by ID: {id}");
        Song::read(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in library_song_get: {e}"))
            .ok()
            .flatten()
    }
    /// Get the artists of a song.
    #[instrument]
    async fn library_song_get_artist(self, context: Context, id: SongId) -> OneOrMany<Artist> {
        let id = id.into();
        info!("Getting artist of: {id}");
        Song::read_artist(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in library_song_get_artist: {e}"))
            .ok()
            .into()
    }
    /// Get the album of a song.
    #[instrument]
    async fn library_song_get_album(self, context: Context, id: SongId) -> Option<Album> {
        let id = id.into();
        info!("Getting album of: {id}");
        Song::read_album(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in library_song_get_album: {e}"))
            .ok()
            .flatten()
    }
    /// Get the Playlists a song is in.
    #[instrument]
    async fn library_song_get_playlists(self, context: Context, id: SongId) -> Box<[Playlist]> {
        let id = id.into();
        info!("Getting playlists of: {id}");
        Song::read_playlists(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in library_song_get_playlists: {e}"))
            .ok()
            .unwrap_or_default()
            .into()
    }
    /// Get the Collections a song is in.
    #[instrument]
    async fn library_song_get_collections(self, context: Context, id: SongId) -> Box<[Collection]> {
        let id = id.into();
        info!("Getting collections of: {id}");
        Song::read_collections(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in library_song_get_collections: {e}"))
            .ok()
            .unwrap_or_default()
            .into()
    }

    /// Get an album by its ID.
    #[instrument]
    async fn library_album_get(self, context: Context, id: AlbumId) -> Option<Album> {
        let id = id.into();
        info!("Getting album by ID: {id}");
        Album::read(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in library_album_get: {e}"))
            .ok()
            .flatten()
    }
    /// Get the artists of an album
    #[instrument]
    async fn library_album_get_artist(self, context: Context, id: AlbumId) -> OneOrMany<Artist> {
        let id = id.into();
        info!("Getting artists of: {id}");
        Album::read_artist(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in library_album_get_artist: {e}"))
            .ok()
            .into()
    }
    /// Get the songs of an album
    #[instrument]
    async fn library_album_get_songs(self, context: Context, id: AlbumId) -> Option<Box<[Song]>> {
        let id = id.into();
        info!("Getting songs of: {id}");
        Album::read_songs(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in library_album_get_songs: {e}"))
            .ok()
            .map(Into::into)
    }
    /// Get an artist by its ID.
    #[instrument]
    async fn library_artist_get(self, context: Context, id: ArtistId) -> Option<Artist> {
        let id = id.into();
        info!("Getting artist by ID: {id}");
        Artist::read(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in library_artist_get: {e}"))
            .ok()
            .flatten()
    }
    /// Get the songs of an artist
    #[instrument]
    async fn library_artist_get_songs(self, context: Context, id: ArtistId) -> Option<Box<[Song]>> {
        let id = id.into();
        info!("Getting songs of: {id}");
        Artist::read_songs(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in library_artist_get_songs: {e}"))
            .ok()
            .map(Into::into)
    }
    /// Get the albums of an artist
    #[instrument]
    async fn library_artist_get_albums(
        self,
        context: Context,
        id: ArtistId,
    ) -> Option<Box<[Album]>> {
        let id = id.into();
        info!("Getting albums of: {id}");
        Artist::read_albums(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in library_artist_get_albums: {e}"))
            .ok()
            .map(Into::into)
    }

    /// tells the daemon to shutdown.
    #[instrument]
    async fn daemon_shutdown(self, context: Context) {
        let audio_kernel = self.audio_kernel.clone();
        std::thread::Builder::new()
            .name(String::from("Daemon Shutdown"))
            .spawn(move || {
                std::thread::sleep(std::time::Duration::from_secs(1));
                audio_kernel.send(AudioCommand::Exit);
                std::process::exit(0);
            })
            .unwrap();
        info!("Shutting down daemon in 1 second");
    }

    /// returns full information about the current state of the audio player (queue, current song, etc.)
    #[instrument]
    async fn state_audio(self, context: Context) -> Option<StateAudio> {
        debug!("Getting state of audio player");
        let (tx, rx) = tokio::sync::oneshot::channel();

        self.audio_kernel.send(AudioCommand::ReportStatus(tx));

        rx.await
            .tap_err(|e| warn!("Error in state_audio: {e}"))
            .ok()
    }
    /// returns information about the current queue.
    #[instrument]
    async fn state_queue(self, context: Context) -> Option<Box<[Song]>> {
        info!("Getting state of queue");
        let (tx, rx) = tokio::sync::oneshot::channel();

        self.audio_kernel.send(AudioCommand::ReportStatus(tx));

        rx.await
            .tap_err(|e| warn!("Error in state_queue: {e}"))
            .ok()
            .map(|state| state.queue)
    }
    /// returns the current queue position.
    #[instrument]
    async fn state_queue_position(self, context: Context) -> Option<usize> {
        info!("Getting state of queue position");
        let (tx, rx) = tokio::sync::oneshot::channel();

        self.audio_kernel.send(AudioCommand::ReportStatus(tx));

        rx.await
            .tap_err(|e| warn!("Error in state_queue_position: {e}"))
            .ok()
            .and_then(|state| state.queue_position)
    }
    /// is the player currently paused?
    #[instrument]
    async fn state_paused(self, context: Context) -> bool {
        info!("Getting state of playing");
        let (tx, rx) = tokio::sync::oneshot::channel();

        self.audio_kernel.send(AudioCommand::ReportStatus(tx));

        rx.await
            .tap_err(|e| warn!("Error in state_playing: {e}"))
            .ok()
            .is_some_and(|state| state.paused)
    }
    /// what repeat mode is the player in?
    #[instrument]
    async fn state_repeat(self, context: Context) -> Option<RepeatMode> {
        info!("Getting state of repeat");
        let (tx, rx) = tokio::sync::oneshot::channel();

        self.audio_kernel.send(AudioCommand::ReportStatus(tx));

        rx.await
            .tap_err(|e| warn!("Error in state_repeat: {e}"))
            .ok()
            .map(|state| state.repeat_mode)
    }
    /// returns the current volume.
    #[instrument]
    async fn state_volume(self, context: Context) -> Option<f32> {
        info!("Getting state of volume");
        let (tx, rx) = tokio::sync::oneshot::channel();

        self.audio_kernel.send(AudioCommand::ReportStatus(tx));

        rx.await
            .tap_err(|e| warn!("Error in state_volume: {e}"))
            .ok()
            .map(|state| state.volume)
    }
    /// returns the current volume mute state.
    #[instrument]
    async fn state_volume_muted(self, context: Context) -> bool {
        info!("Getting state of volume muted");
        let (tx, rx) = tokio::sync::oneshot::channel();

        self.audio_kernel.send(AudioCommand::ReportStatus(tx));

        rx.await
            .tap_err(|e| warn!("Error in state_volume_muted: {e}"))
            .ok()
            .is_some_and(|state| state.muted)
    }
    /// returns information about the runtime of the current song (seek position and duration)
    #[instrument]
    async fn state_runtime(self, context: Context) -> Option<StateRuntime> {
        info!("Getting state of runtime");
        let (tx, rx) = tokio::sync::oneshot::channel();

        self.audio_kernel.send(AudioCommand::ReportStatus(tx));

        rx.await
            .tap_err(|e| warn!("Error in state_runtime: {e}"))
            .ok()
            .and_then(|state| state.runtime)
    }

    /// returns the current artist.
    #[instrument]
    async fn current_artist(self, context: Context) -> OneOrMany<Artist> {
        info!("Getting current artist");
        let (tx, rx) = tokio::sync::oneshot::channel();

        self.audio_kernel.send(AudioCommand::ReportStatus(tx));

        if let Some(song) = rx
            .await
            .tap_err(|e| warn!("Error in current_artist: {e}"))
            .ok()
            .and_then(|state| state.current_song)
        {
            Song::read_artist(&self.db, song.id)
                .await
                .tap_err(|e| warn!("Error in current_album: {e}"))
                .ok()
                .into()
        } else {
            OneOrMany::None
        }
    }
    /// returns the current album.
    #[instrument]
    async fn current_album(self, context: Context) -> Option<Album> {
        info!("Getting current album");
        let (tx, rx) = tokio::sync::oneshot::channel();

        self.audio_kernel.send(AudioCommand::ReportStatus(tx));

        if let Some(song) = rx
            .await
            .tap_err(|e| warn!("Error in current_album: {e}"))
            .ok()
            .and_then(|state| state.current_song)
        {
            Song::read_album(&self.db, song.id)
                .await
                .tap_err(|e| warn!("Error in current_album: {e}"))
                .ok()
                .flatten()
        } else {
            None
        }
    }
    /// returns the current song.
    #[instrument]
    async fn current_song(self, context: Context) -> Option<Song> {
        info!("Getting current song");
        let (tx, rx) = tokio::sync::oneshot::channel();

        self.audio_kernel.send(AudioCommand::ReportStatus(tx));

        rx.await
            .tap_err(|e| warn!("Error in current_song: {e}"))
            .ok()
            .and_then(|state| state.current_song)
    }

    /// returns a random artist.
    #[instrument]
    async fn rand_artist(self, context: Context) -> Option<Artist> {
        info!("Getting random artist");
        Artist::read_all(&self.db)
            .await
            .tap_err(|e| warn!("Error in rand_artist: {e}"))
            .ok()
            .and_then(|artists| artists.choose(&mut rand::thread_rng()).cloned())
    }
    /// returns a random album.
    #[instrument]
    async fn rand_album(self, context: Context) -> Option<Album> {
        info!("Getting random album");
        Album::read_all(&self.db)
            .await
            .tap_err(|e| warn!("Error in rand_album: {e}"))
            .ok()
            .and_then(|albums| albums.choose(&mut rand::thread_rng()).cloned())
    }
    /// returns a random song.
    #[instrument]
    async fn rand_song(self, context: Context) -> Option<Song> {
        info!("Getting random song");
        Song::read_all(&self.db)
            .await
            .tap_err(|e| warn!("Error in rand_song: {e}"))
            .ok()
            .and_then(|songs| songs.choose(&mut rand::thread_rng()).cloned())
    }

    /// returns a list of artists, albums, and songs matching the given search query.
    #[instrument]
    #[allow(clippy::type_complexity)]
    async fn search(self, context: Context, query: String, limit: u32) -> SearchResult {
        info!("Searching for: {query}");
        // basic idea:
        // 1. search for songs
        // 2. search for albums
        // 3. search for artists
        // 4. return the results
        let songs = Song::search(&self.db, &query, i64::from(limit))
            .await
            .tap_err(|e| warn!("Error in search: {e}"))
            .unwrap_or_default()
            .into();

        let albums = Album::search(&self.db, &query, i64::from(limit))
            .await
            .tap_err(|e| warn!("Error in search: {e}"))
            .unwrap_or_default()
            .into();

        let artists = Artist::search(&self.db, &query, i64::from(limit))
            .await
            .tap_err(|e| warn!("Error in search: {e}"))
            .unwrap_or_default()
            .into();
        SearchResult {
            songs,
            albums,
            artists,
        }
    }
    /// returns a list of artists matching the given search query.
    #[instrument]
    async fn search_artist(self, context: Context, query: String, limit: u32) -> Box<[Artist]> {
        info!("Searching for artist: {query}");
        Artist::search(&self.db, &query, i64::from(limit))
            .await
            .tap_err(|e| {
                warn!("Error in search_artist: {e}");
            })
            .unwrap_or_default()
            .into()
    }
    /// returns a list of albums matching the given search query.
    #[instrument]
    async fn search_album(self, context: Context, query: String, limit: u32) -> Box<[Album]> {
        info!("Searching for album: {query}");
        Album::search(&self.db, &query, i64::from(limit))
            .await
            .tap_err(|e| {
                warn!("Error in search_album: {e}");
            })
            .unwrap_or_default()
            .into()
    }
    /// returns a list of songs matching the given search query.
    #[instrument]
    async fn search_song(self, context: Context, query: String, limit: u32) -> Box<[Song]> {
        info!("Searching for song: {query}");
        Song::search(&self.db, &query, i64::from(limit))
            .await
            .tap_err(|e| {
                warn!("Error in search_song: {e}");
            })
            .unwrap_or_default()
            .into()
    }

    /// toggles playback (play/pause).
    #[instrument]
    async fn playback_toggle(self, context: Context) {
        info!("Toggling playback");
        self.audio_kernel.send(AudioCommand::TogglePlayback);
    }
    /// start playback (unpause).
    #[instrument]
    async fn playback_play(self, context: Context) {
        info!("Starting playback");
        self.audio_kernel.send(AudioCommand::Play);
    }
    /// pause playback.
    #[instrument]
    async fn playback_pause(self, context: Context) {
        info!("Pausing playback");
        self.audio_kernel.send(AudioCommand::Pause);
    }
    /// set the current song to be the next song in the queue.
    #[instrument]
    async fn playback_next(self, context: Context) {
        info!("Playing next song");
        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::SkipForward(1)));
    }
    /// restart the current song.
    #[instrument]
    async fn playback_restart(self, context: Context) {
        info!("Restarting current song");
        self.audio_kernel.send(AudioCommand::RestartSong);
    }
    /// skip forward by the given amount of songs
    #[instrument]
    async fn playback_skip_forward(self, context: Context, amount: usize) {
        info!("Skipping forward by {amount} songs");
        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::SkipForward(amount)));
    }
    /// go backwards by the given amount of songs.
    #[instrument]
    async fn playback_skip_backward(self, context: Context, amount: usize) {
        info!("Going back by {amount} songs");
        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::SkipBackward(amount)));
    }
    /// stop playback.
    /// (clears the queue and stops playback)
    #[instrument]
    async fn playback_clear_player(self, context: Context) {
        info!("Stopping playback");
        self.audio_kernel.send(AudioCommand::ClearPlayer);
    }
    /// clear the queue.
    #[instrument]
    async fn playback_clear(self, context: Context) {
        info!("Clearing queue and stopping playback");
        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::Clear));
    }
    /// seek forwards, backwards, or to an absolute second in the current song.
    #[instrument]
    async fn playback_seek(self, context: Context, seek: SeekType, duration: Duration) {
        info!("Seeking {seek} by {:.2}s", duration.as_secs_f32());
        self.audio_kernel.send(AudioCommand::Seek(seek, duration));
    }
    /// set the repeat mode.
    #[instrument]
    async fn playback_repeat(self, context: Context, mode: RepeatMode) {
        info!("Setting repeat mode to: {}", mode);
        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::SetRepeatMode(mode)));
    }
    /// Shuffle the current queue, then start playing from the 1st Song in the queue.
    #[instrument]
    async fn playback_shuffle(self, context: Context) {
        info!("Shuffling queue");
        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::Shuffle));
    }
    /// set the volume to the given value
    /// The value `1.0` is the "normal" volume (unfiltered input). Any value other than `1.0` will multiply each sample by this value.
    #[instrument]
    async fn playback_volume(self, context: Context, volume: f32) {
        info!("Setting volume to: {volume}",);
        self.audio_kernel
            .send(AudioCommand::Volume(VolumeCommand::Set(volume)));
    }
    /// increase the volume by the given amount
    #[instrument]
    async fn playback_volume_up(self, context: Context, amount: f32) {
        info!("Increasing volume by: {amount}",);
        self.audio_kernel
            .send(AudioCommand::Volume(VolumeCommand::Up(amount)));
    }
    /// decrease the volume by the given amount
    #[instrument]
    async fn playback_volume_down(self, context: Context, amount: f32) {
        info!("Decreasing volume by: {amount}",);
        self.audio_kernel
            .send(AudioCommand::Volume(VolumeCommand::Down(amount)));
    }
    /// toggle the volume mute.
    #[instrument]
    async fn playback_volume_toggle_mute(self, context: Context) {
        info!("Toggling volume mute");
        self.audio_kernel
            .send(AudioCommand::Volume(VolumeCommand::ToggleMute));
    }
    /// mute the volume.
    #[instrument]
    async fn playback_mute(self, context: Context) {
        info!("Muting volume");
        self.audio_kernel
            .send(AudioCommand::Volume(VolumeCommand::Mute));
    }
    /// unmute the volume.
    #[instrument]
    async fn playback_unmute(self, context: Context) {
        info!("Unmuting volume");
        self.audio_kernel
            .send(AudioCommand::Volume(VolumeCommand::Unmute));
    }

    /// add a song to the queue.
    /// (if the queue is empty, it will start playing the song.)
    #[instrument]
    async fn queue_add_song(
        self,
        context: Context,
        song: SongId,
    ) -> Result<(), SerializableLibraryError> {
        let song = song.into();
        info!("Adding song to queue: {song}",);
        let Some(song) = Song::read(&self.db, song).await? else {
            return Err(Error::NotFound.into());
        };

        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::AddToQueue(Box::new(
                OneOrMany::One(song),
            ))));

        Ok(())
    }
    /// add a list of things to the queue.
    /// (if the queue is empty, it will start playing the first thing in the list.)
    #[instrument]
    async fn queue_add_list(
        self,
        context: Context,
        list: Vec<mecomp_storage::db::schemas::Thing>,
    ) -> Result<(), SerializableLibraryError> {
        info!(
            "Adding list to queue: ({})",
            list.iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
                .join(", ")
        );

        // go through the list, and get songs for each thing (depending on what it is)
        let songs: OneOrMany<Song> = get_songs_from_things(&self.db, list).await?;

        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::AddToQueue(Box::new(
                songs,
            ))));

        Ok(())
    }
    /// add an album to the queue.
    /// (if the queue is empty, it will start playing the album.)
    #[instrument]
    async fn queue_add_album(
        self,
        context: Context,
        album: AlbumId,
    ) -> Result<(), SerializableLibraryError> {
        let album = album.into();
        info!("Adding album to queue: {album}");

        let songs = Album::read_songs(&self.db, album).await?;

        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::AddToQueue(Box::new(
                songs.into(),
            ))));

        Ok(())
    }
    /// add an artist to the queue.
    /// (if the queue is empty, it will start playing the artist.)
    #[instrument]
    async fn queue_add_artist(
        self,
        context: Context,
        artist: ArtistId,
    ) -> Result<(), SerializableLibraryError> {
        let artist = artist.into();
        info!("Adding artist to queue: {artist}");

        let songs = Artist::read_songs(&self.db, artist).await?;

        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::AddToQueue(Box::new(
                songs.into(),
            ))));

        Ok(())
    }
    /// add a playlist to the queue.
    /// (if the queue is empty, it will start playing the playlist.)
    #[instrument]
    async fn queue_add_playlist(
        self,
        context: Context,
        playlist: PlaylistId,
    ) -> Result<(), SerializableLibraryError> {
        let playlist = playlist.into();
        info!("Adding playlist to queue: {playlist}");

        let songs = Playlist::read_songs(&self.db, playlist).await?;

        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::AddToQueue(Box::new(
                songs.into(),
            ))));

        Ok(())
    }
    /// add a collection to the queue.
    /// (if the queue is empty, it will start playing the collection.)
    #[instrument]
    async fn queue_add_collection(
        self,
        context: Context,
        collection: CollectionId,
    ) -> Result<(), SerializableLibraryError> {
        let collection = collection.into();
        info!("Adding collection to queue: {collection}");

        let songs = Collection::read_songs(&self.db, collection).await?;

        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::AddToQueue(Box::new(
                songs.into(),
            ))));

        Ok(())
    }
    /// add a random song to the queue.
    /// (if the queue is empty, it will start playing the song.)
    #[instrument]
    async fn queue_add_rand_song(self, context: Context) -> Result<(), SerializableLibraryError> {
        info!("Adding random song to queue");
        let song = Song::read_all(&self.db)
            .await
            .tap_err(|e| warn!("Error in rand_song: {e}"))
            .ok()
            .and_then(|songs| songs.choose(&mut rand::thread_rng()).cloned())
            .ok_or(NotFound)?;

        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::AddToQueue(Box::new(
                OneOrMany::One(song),
            ))));

        Ok(())
    }
    /// add a random album to the queue.
    /// (if the queue is empty, it will start playing the album.)
    #[instrument]
    async fn queue_add_rand_album(self, context: Context) -> Result<(), SerializableLibraryError> {
        info!("Adding random album to queue");

        let songs = Album::read_songs(
            &self.db,
            Album::read_all(&self.db)
                .await
                .tap_err(|e| warn!("Error in rand_album (reading albums): {e}"))
                .ok()
                .and_then(|albums| albums.choose(&mut rand::thread_rng()).cloned())
                .ok_or(NotFound)?
                .id,
        )
        .await
        .tap_err(|e| warn!("Error in rand_album (reading songs): {e}"))
        .map_err(|_| NotFound)?;

        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::AddToQueue(Box::new(
                OneOrMany::Many(songs),
            ))));

        Ok(())
    }
    /// add a random artist to the queue.
    /// (if the queue is empty, it will start playing the artist.)
    #[instrument]
    async fn queue_add_rand_artist(self, context: Context) -> Result<(), SerializableLibraryError> {
        info!("Adding random artist to queue");

        let songs = Artist::read_songs(
            &self.db,
            Artist::read_all(&self.db)
                .await
                .tap_err(|e| warn!("Error in rand_artist (reading artists): {e}"))
                .ok()
                .and_then(|artists| artists.choose(&mut rand::thread_rng()).cloned())
                .ok_or(NotFound)?
                .id,
        )
        .await
        .tap_err(|e| warn!("Error in rand_artist (reading songs): {e}"))
        .map_err(|_| NotFound)?;

        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::AddToQueue(Box::new(
                OneOrMany::Many(songs),
            ))));

        Ok(())
    }
    /// set the current song to a queue index.
    /// if the index is out of bounds, it will be clamped to the nearest valid index.
    #[instrument]
    async fn queue_set_index(self, context: Context, index: usize) {
        info!("Setting queue index to: {index}");

        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::SetPosition(index)));
    }
    /// remove a range of songs from the queue.
    /// if the range is out of bounds, it will be clamped to the nearest valid range.
    #[instrument]
    async fn queue_remove_range(self, context: Context, range: Range<usize>) {
        info!("Removing queue range: {range:?}");

        self.audio_kernel
            .send(AudioCommand::Queue(QueueCommand::RemoveRange(range)));
    }

    /// Returns brief information about the users playlists.
    #[instrument]
    async fn playlist_list(self, context: Context) -> Box<[PlaylistBrief]> {
        info!("Listing playlists");
        Playlist::read_all(&self.db)
            .await
            .tap_err(|e| warn!("Error in playlist_list: {e}"))
            .ok()
            .map(|playlists| playlists.iter().map(std::convert::Into::into).collect())
            .unwrap_or_default()
    }
    /// create a new playlist.
    /// if a playlist with the same name already exists, this will return that playlist's id in the error variant
    #[instrument]
    async fn playlist_new(
        self,
        context: Context,
        name: String,
    ) -> Result<Result<PlaylistId, PlaylistId>, SerializableLibraryError> {
        info!("Creating new playlist: {name}");

        // see if a playlist with that name already exists
        if let Some(playlist) = Playlist::read_by_name(&self.db, name.clone())
            .await
            .tap_err(|e| warn!("Error in playlist_new: {e}"))
            .ok()
            .flatten()
        {
            Ok(Ok(playlist.id.into()))
        } else {
            Ok(Err(Playlist::create(
                &self.db,
                Playlist {
                    id: Playlist::generate_id(),
                    name: name.into(),
                    runtime: Duration::from_secs(0),
                    song_count: 0,
                },
            )
            .await?
            .map(|playlist| playlist.id.into())
            .ok_or(NotFound)?))
        }
    }
    /// remove a playlist.
    #[instrument]
    async fn playlist_remove(
        self,
        context: Context,
        id: PlaylistId,
    ) -> Result<(), SerializableLibraryError> {
        let id = id.into();
        info!("Removing playlist with id: {id}");

        Playlist::delete(&self.db, id).await?.ok_or(NotFound)?;

        Ok(())
    }
    /// clone a playlist.
    /// (creates a new playlist with the same name (append "copy") and contents as the given playlist.)
    /// returns the id of the new playlist
    #[instrument]
    async fn playlist_clone(
        self,
        context: Context,
        id: PlaylistId,
    ) -> Result<PlaylistId, SerializableLibraryError> {
        let id = id.into();
        info!("Cloning playlist with id: {id}");

        let new_playlist = Playlist::create_copy(&self.db, id).await?.ok_or(NotFound)?;

        Ok(new_playlist.id.into())
    }
    /// get the id of a playlist.
    /// returns none if the playlist does not exist.
    #[instrument]
    async fn playlist_get_id(self, context: Context, name: String) -> Option<PlaylistId> {
        info!("Getting playlist ID: {name}");

        Playlist::read_by_name(&self.db, name)
            .await
            .tap_err(|e| warn!("Error in playlist_get_id: {e}"))
            .ok()
            .flatten()
            .map(|playlist| playlist.id.into())
    }
    /// remove a list of songs from a playlist.
    /// if the songs are not in the playlist, this will do nothing.
    #[instrument]
    async fn playlist_remove_songs(
        self,
        context: Context,
        playlist: PlaylistId,
        songs: Vec<SongId>,
    ) -> Result<(), SerializableLibraryError> {
        let playlist = playlist.into();
        let songs = songs.into_iter().map(Into::into).collect::<Vec<_>>();
        info!("Removing song from playlist: {playlist} ({songs:?})");

        Ok(Playlist::remove_songs(&self.db, playlist, songs).await?)
    }
    /// Add an artist to a playlist.
    #[instrument]
    async fn playlist_add_artist(
        self,
        context: Context,
        playlist: PlaylistId,
        artist: ArtistId,
    ) -> Result<(), SerializableLibraryError> {
        let playlist = playlist.into();
        let artist = artist.into();
        info!("Adding artist to playlist: {playlist} ({artist})");

        Ok(Playlist::add_songs(
            &self.db,
            playlist,
            Artist::read_songs(&self.db, artist)
                .await?
                .iter()
                .map(|song| song.id.clone())
                .collect::<Vec<_>>(),
        )
        .await?)
    }
    /// Add an album to a playlist.
    #[instrument]
    async fn playlist_add_album(
        self,
        context: Context,
        playlist: PlaylistId,
        album: AlbumId,
    ) -> Result<(), SerializableLibraryError> {
        let playlist = playlist.into();
        let album = album.into();
        info!("Adding album to playlist: {playlist} ({album})");

        Ok(Playlist::add_songs(
            &self.db,
            playlist,
            Album::read_songs(&self.db, album)
                .await?
                .iter()
                .map(|song| song.id.clone())
                .collect::<Vec<_>>(),
        )
        .await?)
    }
    /// Add songs to a playlist.
    #[instrument]
    async fn playlist_add_songs(
        self,
        context: Context,
        playlist: PlaylistId,
        songs: Vec<SongId>,
    ) -> Result<(), SerializableLibraryError> {
        let playlist = playlist.into();
        let songs = songs.into_iter().map(Into::into).collect::<Vec<_>>();
        info!("Adding songs to playlist: {playlist} ({songs:?})");

        Ok(Playlist::add_songs(&self.db, playlist, songs).await?)
    }
    /// Add a list of things to a playlist.
    #[instrument]
    async fn playlist_add_list(
        self,
        context: Context,
        playlist: PlaylistId,
        list: Vec<mecomp_storage::db::schemas::Thing>,
    ) -> Result<(), SerializableLibraryError> {
        let playlist = playlist.into();
        info!(
            "Adding list to playlist: {playlist} ({})",
            list.iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
                .join(", ")
        );

        // go through the list, and get songs for each thing (depending on what it is)
        let songs: OneOrMany<Song> = get_songs_from_things(&self.db, list).await?;

        Ok(Playlist::add_songs(
            &self.db,
            playlist,
            songs.into_iter().map(|s| s.id).collect::<Vec<_>>(),
        )
        .await?)
    }
    /// Get a playlist by its ID.
    #[instrument]
    async fn playlist_get(self, context: Context, id: PlaylistId) -> Option<Playlist> {
        let id = id.into();
        info!("Getting playlist by ID: {}", id);

        Playlist::read(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in playlist_get: {e}"))
            .ok()
            .flatten()
    }
    /// Get the songs of a playlist
    #[instrument]
    async fn playlist_get_songs(self, context: Context, id: PlaylistId) -> Option<Box<[Song]>> {
        let id = id.into();
        info!("Getting songs in: {id}");
        Playlist::read_songs(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in playlist_get_songs: {e}"))
            .ok()
            .map(Into::into)
    }

    /// Collections: Return brief information about the users auto curration collections.
    #[instrument]
    async fn collection_list(self, context: Context) -> Box<[CollectionBrief]> {
        info!("Listing collections");
        Collection::read_all(&self.db)
            .await
            .tap_err(|e| warn!("Error in collection_list: {e}"))
            .ok()
            .map(|collections| collections.iter().map(std::convert::Into::into).collect())
            .unwrap_or_default()
    }
    /// Collections: get a collection by its ID.
    #[instrument]
    async fn collection_get(self, context: Context, id: CollectionId) -> Option<Collection> {
        info!("Getting collection by ID: {id:?}");
        Collection::read(&self.db, id.into())
            .await
            .tap_err(|e| warn!("Error in collection_get: {e}"))
            .ok()
            .flatten()
    }
    /// Collections: freeze a collection (convert it to a playlist).
    #[instrument]
    async fn collection_freeze(
        self,
        context: Context,
        id: CollectionId,
        name: String,
    ) -> Result<PlaylistId, SerializableLibraryError> {
        info!("Freezing collection: {id:?} ({name})");
        Ok(Collection::freeze(&self.db, id.into(), name.into())
            .await
            .map(|p| p.id.into())?)
    }
    /// Get the songs of a collection
    #[instrument]
    async fn collection_get_songs(self, context: Context, id: CollectionId) -> Option<Box<[Song]>> {
        let id = id.into();
        info!("Getting songs in: {id}");
        Collection::read_songs(&self.db, id)
            .await
            .tap_err(|e| warn!("Error in collection_get_songs: {e}"))
            .ok()
            .map(Into::into)
    }

    /// Radio: get the `n` most similar songs to the given things.
    #[instrument]
    async fn radio_get_similar(
        self,
        context: Context,
        things: Vec<schemas::Thing>,
        n: u32,
    ) -> Result<Box<[Song]>, SerializableLibraryError> {
        #[cfg(not(feature = "analysis"))]
        {
            warn!("Analysis is not enabled");
            return Err(SerializableLibraryError::AnalysisNotEnabled);
        }

        #[cfg(feature = "analysis")]
        {
            info!("Getting the {n} most similar songs to: {things:?}");
            Ok(services::radio::get_similar(&self.db, things, n)
                .await
                .map(Vec::into_boxed_slice)
                .tap_err(|e| warn!("Error in radio_get_similar: {e}"))?)
        }
    }
    /// Radio: get the `n` most similar songs to the given song.
    #[instrument]
    async fn radio_get_similar_to_song(
        self,
        context: Context,
        song: SongId,
        n: u32,
    ) -> Result<Box<[SongId]>, SerializableLibraryError> {
        #[cfg(not(feature = "analysis"))]
        {
            warn!("Analysis is not enabled");
            return Err(SerializableLibraryError::AnalysisNotEnabled);
        }

        #[cfg(feature = "analysis")]
        {
            info!("Getting the {n} most similar songs to: {song:?}");
            Ok(
                services::radio::get_similar_to_song(&self.db, song.into(), n)
                    .await
                    .map(|songs| songs.into_iter().map(|song| song.id.into()).collect())
                    .tap_err(|e| warn!("Error in radio_get_similar_songs: {e}"))?,
            )
        }
    }

    /// Radio: get the `n` most similar songs to the given artist.
    #[instrument]
    async fn radio_get_similar_to_artist(
        self,
        context: Context,
        artist: ArtistId,
        n: u32,
    ) -> Result<Box<[SongId]>, SerializableLibraryError> {
        #[cfg(not(feature = "analysis"))]
        {
            warn!("Analysis is not enabled");
            return Err(SerializableLibraryError::AnalysisNotEnabled);
        }

        #[cfg(feature = "analysis")]
        {
            info!("Getting the {n} most similar songs to: {artist:?}");
            Ok(
                services::radio::get_similar_to_artist(&self.db, artist.into(), n)
                    .await
                    .map(|songs| songs.into_iter().map(|song| song.id.into()).collect())
                    .tap_err(|e| warn!("Error in radio_get_similar_to_artist: {e}"))?,
            )
        }
    }

    /// Radio: get the `n` most similar songs to the given album.
    #[instrument]
    async fn radio_get_similar_to_album(
        self,
        context: Context,
        album: AlbumId,
        n: u32,
    ) -> Result<Box<[SongId]>, SerializableLibraryError> {
        #[cfg(not(feature = "analysis"))]
        {
            warn!("Analysis is not enabled");
            return Err(SerializableLibraryError::AnalysisNotEnabled);
        }

        #[cfg(feature = "analysis")]
        {
            info!("Getting the {n} most similar songs to: {album:?}");
            Ok(
                services::radio::get_similar_to_album(&self.db, album.into(), n)
                    .await
                    .map(|songs| songs.into_iter().map(|song| song.id.into()).collect())
                    .tap_err(|e| warn!("Error in radio_get_similar_to_artist: {e}"))?,
            )
        }
    }

    /// Radio: get the `n` most similar songs to the given playlist.
    #[instrument]
    async fn radio_get_similar_to_playlist(
        self,
        context: Context,
        playlist: PlaylistId,
        n: u32,
    ) -> Result<Box<[SongId]>, SerializableLibraryError> {
        #[cfg(not(feature = "analysis"))]
        {
            warn!("Analysis is not enabled");
            return Err(SerializableLibraryError::AnalysisNotEnabled);
        }

        #[cfg(feature = "analysis")]
        {
            info!("Getting the {n} most similar songs to: {playlist:?}");
            Ok(
                services::radio::get_similar_to_playlist(&self.db, playlist.into(), n)
                    .await
                    .map(|songs| songs.into_iter().map(|song| song.id.into()).collect())
                    .tap_err(|e| warn!("Error in radio_get_similar_to_artist: {e}"))?,
            )
        }
    }
}