koan-core 0.30.1

Core library for koan — bit-perfect music player. Audio engine, player, database, format strings.
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
use std::collections::HashMap;
use std::path::Path;

use serde::Deserialize;
use thiserror::Error;

use super::download::{self, DownloadError};

const API_VERSION: &str = "1.16.1";
const CLIENT_NAME: &str = "koan";

#[derive(Debug, Error)]
pub enum SubsonicError {
    #[error("http error: {0}")]
    Http(#[from] reqwest::Error),
    #[error("api error: {code} — {message}")]
    Api { code: i32, message: String },
    #[error("unexpected response format")]
    BadResponse,
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("download error: {0}")]
    Download(#[from] DownloadError),
    #[error("entropy source unavailable: {0}")]
    Entropy(#[from] getrandom::Error),
}

/// A Subsonic server and the credentials that sign requests to it.
///
/// Kept separate from `SubsonicClient` because constructing that builds two
/// blocking `reqwest` clients, each carrying its own runtime — doing so from
/// inside a tokio runtime panics. A caller that only needs a signed URL, such
/// as koan's own Subsonic proxy, holds this instead.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubsonicAuth {
    pub base_url: String,
    pub username: String,
    pub password: String,
}

impl SubsonicAuth {
    pub fn new(base_url: &str, username: &str, password: &str) -> Self {
        Self {
            base_url: base_url.trim_end_matches('/').to_string(),
            username: username.to_string(),
            password: password.to_string(),
        }
    }

    /// Build auth query params: u, t (token), s (salt), v, c, f.
    fn params(&self) -> Result<HashMap<String, String>, SubsonicError> {
        let salt = random_salt()?;

        let token = format!("{:x}", md5::compute(format!("{}{}", self.password, salt)));

        let mut params = HashMap::new();
        params.insert("u".into(), self.username.clone());
        params.insert("t".into(), token);
        params.insert("s".into(), salt);
        params.insert("v".into(), API_VERSION.into());
        params.insert("c".into(), CLIENT_NAME.into());
        params.insert("f".into(), "json".into());
        Ok(params)
    }

    /// Build the streaming URL for a track (doesn't make a request).
    pub fn stream_url(&self, track_id: &str) -> Result<String, SubsonicError> {
        let query: String = self
            .params()?
            .iter()
            .map(|(k, v)| format!("{}={}", k, v))
            .collect::<Vec<_>>()
            .join("&");
        Ok(format!(
            "{}/rest/stream?id={}&{}",
            self.base_url, track_id, query
        ))
    }
}

/// Subsonic/Navidrome API client.
///
/// Holds two HTTP clients with different timeout semantics: `http` bounds a
/// whole JSON request, which is right for small API responses read in one go;
/// `downloader` bounds only connect and per-read stalls, so a large track on a
/// slow link is never cut off for taking too long overall.
pub struct SubsonicClient {
    auth: SubsonicAuth,
    http: reqwest::blocking::Client,
    downloader: reqwest::blocking::Client,
}

impl SubsonicClient {
    pub fn new(base_url: &str, username: &str, password: &str) -> Self {
        Self::from_auth(SubsonicAuth::new(base_url, username, password))
    }

    pub fn from_auth(auth: SubsonicAuth) -> Self {
        Self {
            auth,
            http: download::api_client().unwrap_or_else(|e| {
                log::warn!("falling back to default HTTP client: {}", e);
                reqwest::blocking::Client::new()
            }),
            downloader: download::download_client().unwrap_or_else(|e| {
                log::warn!("falling back to default download client: {}", e);
                reqwest::blocking::Client::new()
            }),
        }
    }

    fn auth_params(&self) -> Result<HashMap<String, String>, SubsonicError> {
        self.auth.params()
    }

    /// Make a GET request to a Subsonic API endpoint.
    fn get(&self, endpoint: &str) -> Result<SubsonicResponse, SubsonicError> {
        self.get_with_params(endpoint, &[])
    }

    fn get_with_params(
        &self,
        endpoint: &str,
        extra: &[(&str, &str)],
    ) -> Result<SubsonicResponse, SubsonicError> {
        let url = format!("{}/rest/{}", self.auth.base_url, endpoint);
        let mut params = self.auth_params()?;
        for (k, v) in extra {
            params.insert((*k).to_string(), (*v).to_string());
        }

        let resp: SubsonicResponseWrapper = self.http.get(&url).query(&params).send()?.json()?;

        let inner = resp.subsonic_response;
        if inner.status != "ok" {
            if let Some(err) = inner.error {
                return Err(SubsonicError::Api {
                    code: err.code,
                    message: err.message,
                });
            }
            return Err(SubsonicError::BadResponse);
        }

        Ok(inner)
    }

    /// Detect a Subsonic error returned from an endpoint that should have sent
    /// binary data.
    ///
    /// Subsonic signals failure with HTTP 200 and a JSON or XML error body, so
    /// checking the status code proves nothing here — without this, an error
    /// response gets written to disk as if it were audio.
    fn reject_error_body(resp: &reqwest::blocking::Response) -> Result<(), SubsonicError> {
        let is_document = resp
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .is_some_and(|ct| ct.contains("json") || ct.contains("xml"));
        if is_document {
            return Err(SubsonicError::BadResponse);
        }
        if !resp.status().is_success() {
            return Err(SubsonicError::BadResponse);
        }
        Ok(())
    }

    /// Fetch cover art bytes for a song or album ID.
    ///
    /// Returns the raw image rather than a parsed response — `getCoverArt`
    /// answers with image data, not JSON, so it can't go through `get()`.
    /// `size` requests a square thumbnail; omit it for the original.
    pub fn get_cover_art(&self, id: &str, size: Option<u32>) -> Result<Vec<u8>, SubsonicError> {
        let url = format!("{}/rest/getCoverArt", self.base_url());
        let mut params = self.auth_params()?;
        params.insert("id".into(), id.to_string());
        if let Some(px) = size {
            params.insert("size".into(), px.to_string());
        }

        let resp = self.http.get(&url).query(&params).send()?;
        Self::reject_error_body(&resp)?;
        Ok(resp.bytes()?.to_vec())
    }

    /// Ping the server — verify connection and credentials.
    pub fn ping(&self) -> Result<(), SubsonicError> {
        self.get("ping")?;
        Ok(())
    }

    /// Get all artists (indexed).
    pub fn get_artists(&self) -> Result<Vec<SubsonicArtist>, SubsonicError> {
        let resp = self.get("getArtists")?;
        let artists_data = resp.artists.ok_or(SubsonicError::BadResponse)?;
        let mut all = Vec::new();
        for index in artists_data.index {
            all.extend(index.artist);
        }
        Ok(all)
    }

    /// Get an album by ID, including its tracks.
    pub fn get_album(&self, id: &str) -> Result<SubsonicAlbumFull, SubsonicError> {
        let resp = self.get_with_params("getAlbum", &[("id", id)])?;
        resp.album.ok_or(SubsonicError::BadResponse)
    }

    /// Get a paginated list of albums.
    pub fn get_album_list(
        &self,
        list_type: &str,
        size: u32,
        offset: u32,
    ) -> Result<Vec<SubsonicAlbum>, SubsonicError> {
        let size_str = size.to_string();
        let offset_str = offset.to_string();
        let resp = self.get_with_params(
            "getAlbumList2",
            &[
                ("type", list_type),
                ("size", &size_str),
                ("offset", &offset_str),
            ],
        )?;
        Ok(resp.album_list2.map(|al| al.album).unwrap_or_default())
    }

    /// Build the streaming URL for a track (doesn't make a request).
    pub fn stream_url(&self, track_id: &str) -> Result<String, SubsonicError> {
        self.auth.stream_url(track_id)
    }

    /// Stream URL without auth params — safe for database storage.
    pub fn stream_url_template(&self, track_id: &str) -> String {
        format!("{}/rest/stream?id={}", self.auth.base_url, track_id)
    }

    /// Download a track to a local path.
    pub fn download(&self, track_id: &str, dest: &Path) -> Result<(), SubsonicError> {
        self.download_with_progress(track_id, dest, |_, _| {})
    }

    /// Download a track with progress reporting.
    ///
    /// The callback receives `(bytes_downloaded, total_bytes)`; total is 0 when
    /// the server sends no Content-Length, and the count restarts from zero if
    /// an attempt is retried. `dest` only appears once the file is complete.
    pub fn download_with_progress(
        &self,
        track_id: &str,
        dest: &Path,
        on_progress: impl Fn(u64, u64),
    ) -> Result<(), SubsonicError> {
        self.fetch_to_file("download", track_id, dest, on_progress)
    }

    /// Fetch a track through `/rest/stream` instead of `/rest/download`.
    ///
    /// `download` returns the untranscoded original and is what library sync
    /// wants from Navidrome. koan's own server implements only `stream`, so
    /// that is how the remote bridge pulls audio from a `koan serve` instance.
    pub fn stream_to_file(
        &self,
        track_id: &str,
        dest: &Path,
        on_progress: impl Fn(u64, u64),
    ) -> Result<(), SubsonicError> {
        self.fetch_to_file("stream", track_id, dest, on_progress)
    }

    fn fetch_to_file(
        &self,
        endpoint: &str,
        track_id: &str,
        dest: &Path,
        on_progress: impl Fn(u64, u64),
    ) -> Result<(), SubsonicError> {
        let url = format!("{}/rest/{}", self.auth.base_url, endpoint);
        download::download_with_retries(
            dest,
            download::DEFAULT_ATTEMPTS,
            || {
                // Fresh auth params per attempt — the salt must not be replayed.
                let mut params = self
                    .auth_params()
                    .map_err(|e| download::DownloadError::Request(e.to_string()))?;
                params.insert("id".into(), track_id.to_string());
                Ok(self.downloader.get(&url).query(&params))
            },
            on_progress,
        )?;
        Ok(())
    }

    /// Search for tracks/albums/artists.
    pub fn search(&self, query: &str) -> Result<SubsonicSearchResult, SubsonicError> {
        let resp = self.get_with_params("search3", &[("query", query)])?;
        Ok(resp.search_result3.unwrap_or_default())
    }

    /// Report a play (scrobble).
    pub fn scrobble(&self, track_id: &str) -> Result<(), SubsonicError> {
        self.get_with_params("scrobble", &[("id", track_id)])?;
        Ok(())
    }

    /// Star (favourite) a track on the server.
    pub fn star(&self, track_id: &str) -> Result<(), SubsonicError> {
        self.get_with_params("star", &[("id", track_id)])?;
        Ok(())
    }

    /// Unstar (unfavourite) a track on the server.
    pub fn unstar(&self, track_id: &str) -> Result<(), SubsonicError> {
        self.get_with_params("unstar", &[("id", track_id)])?;
        Ok(())
    }

    /// Get all starred (favourite) songs from the server.
    pub fn get_starred(&self) -> Result<Vec<SubsonicSong>, SubsonicError> {
        let resp = self.get("getStarred2")?;
        Ok(resp.starred2.map(|s| s.song).unwrap_or_default())
    }

    /// Everything the server has starred: songs, albums and artists.
    ///
    /// Subsonic returns all three from one call, so asking for songs alone
    /// leaves a starred album invisible to us for no saving.
    pub fn get_starred_all(&self) -> Result<SubsonicStarred, SubsonicError> {
        let resp = self.get("getStarred2")?;
        Ok(resp.starred2.unwrap_or_default())
    }

    /// Star an album. Subsonic keys this off a different parameter to a song —
    /// `id` would be read as a track and silently star nothing.
    pub fn star_album(&self, album_id: &str) -> Result<(), SubsonicError> {
        self.get_with_params("star", &[("albumId", album_id)])?;
        Ok(())
    }

    pub fn unstar_album(&self, album_id: &str) -> Result<(), SubsonicError> {
        self.get_with_params("unstar", &[("albumId", album_id)])?;
        Ok(())
    }

    pub fn star_artist(&self, artist_id: &str) -> Result<(), SubsonicError> {
        self.get_with_params("star", &[("artistId", artist_id)])?;
        Ok(())
    }

    pub fn unstar_artist(&self, artist_id: &str) -> Result<(), SubsonicError> {
        self.get_with_params("unstar", &[("artistId", artist_id)])?;
        Ok(())
    }

    /// Create a sharing link for one or more resources (songs, albums, etc).
    /// Returns the created share including its ID which forms the public URL.
    pub fn create_share(
        &self,
        ids: &[&str],
        description: Option<&str>,
    ) -> Result<SubsonicShare, SubsonicError> {
        let url = format!("{}/rest/createShare", self.auth.base_url);
        let mut params = self.auth_params()?;
        if let Some(desc) = description {
            params.insert("description".into(), desc.to_string());
        }

        // Subsonic API takes `id` as a repeated param for multiple resources.
        let mut query: Vec<(String, String)> = params.into_iter().collect();
        for id in ids {
            query.push(("id".into(), (*id).to_string()));
        }

        let resp: SubsonicResponseWrapper = self.http.get(&url).query(&query).send()?.json()?;

        let inner = resp.subsonic_response;
        if inner.status != "ok" {
            if let Some(err) = inner.error {
                return Err(SubsonicError::Api {
                    code: err.code,
                    message: err.message,
                });
            }
            return Err(SubsonicError::BadResponse);
        }

        inner
            .shares
            .and_then(|s| s.share.into_iter().next())
            .ok_or(SubsonicError::BadResponse)
    }

    /// Get similar songs for a track (Subsonic getSimilarSongs2 endpoint).
    /// Returns up to `count` similar songs based on the server's algorithm.
    pub fn get_similar_songs(
        &self,
        song_id: &str,
        count: usize,
    ) -> Result<Vec<SubsonicSong>, SubsonicError> {
        let count_str = count.to_string();
        let resp = self.get_with_params(
            "getSimilarSongs2",
            &[("id", song_id), ("count", &count_str)],
        )?;
        Ok(resp.similar_songs2.and_then(|s| s.song).unwrap_or_default())
    }

    /// Get top songs for an artist by name.
    pub fn get_top_songs(
        &self,
        artist_name: &str,
        count: usize,
    ) -> Result<Vec<SubsonicSong>, SubsonicError> {
        let count_str = count.to_string();
        let resp = self.get_with_params(
            "getTopSongs",
            &[("artist", artist_name), ("count", &count_str)],
        )?;
        Ok(resp.top_songs.and_then(|t| t.song).unwrap_or_default())
    }

    /// The configured server base URL (for constructing share links etc).
    pub fn base_url(&self) -> &str {
        &self.auth.base_url
    }
}

// --- Response types ---

#[derive(Debug, Deserialize)]
struct SubsonicResponseWrapper {
    #[serde(rename = "subsonic-response")]
    subsonic_response: SubsonicResponse,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SubsonicResponse {
    status: String,
    error: Option<SubsonicApiError>,
    artists: Option<SubsonicArtists>,
    album: Option<SubsonicAlbumFull>,
    album_list2: Option<SubsonicAlbumList>,
    search_result3: Option<SubsonicSearchResult>,
    starred2: Option<SubsonicStarred>,
    shares: Option<SubsonicShares>,
    similar_songs2: Option<SubsonicSimilarSongs>,
    top_songs: Option<SubsonicTopSongs>,
}

#[derive(Debug, Deserialize)]
struct SubsonicApiError {
    code: i32,
    message: String,
}

#[derive(Debug, Deserialize)]
struct SubsonicArtists {
    index: Vec<SubsonicArtistIndex>,
}

#[derive(Debug, Deserialize)]
struct SubsonicArtistIndex {
    artist: Vec<SubsonicArtist>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubsonicArtist {
    pub id: String,
    pub name: String,
    pub album_count: Option<i32>,
    // OpenSubsonic. Both arrive in `getArtists`, so keeping them costs no
    // extra request.
    pub music_brainz_id: Option<String>,
    pub sort_name: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubsonicAlbum {
    pub id: String,
    pub name: String,
    pub artist: Option<String>,
    pub artist_id: Option<String>,
    pub song_count: Option<i32>,
    pub year: Option<i32>,
    pub genre: Option<String>,
    pub created: Option<String>,
    // OpenSubsonic. All of these arrive in `getAlbumList2`, which the sync
    // already pages through.
    pub music_brainz_id: Option<String>,
    pub sort_name: Option<String>,
    #[serde(default)]
    pub record_labels: Vec<SubsonicName>,
}

/// A bare `{"name": "..."}` object. The server uses this shape for record
/// labels, genres and moods alike.
#[derive(Debug, Clone, Deserialize)]
pub struct SubsonicName {
    pub name: String,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubsonicAlbumFull {
    pub id: String,
    pub name: String,
    pub artist: Option<String>,
    pub artist_id: Option<String>,
    pub year: Option<i32>,
    pub genre: Option<String>,
    pub song_count: Option<i32>,
    pub created: Option<String>,
    pub music_brainz_id: Option<String>,
    pub sort_name: Option<String>,
    #[serde(default)]
    pub record_labels: Vec<SubsonicName>,
    #[serde(default)]
    pub song: Vec<SubsonicSong>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubsonicSong {
    pub id: String,
    pub title: String,
    pub album: Option<String>,
    pub artist: Option<String>,
    pub track: Option<i32>,
    pub disc_number: Option<i32>,
    pub year: Option<i32>,
    pub genre: Option<String>,
    pub duration: Option<i64>,
    pub bit_rate: Option<i32>,
    pub suffix: Option<String>,
    pub content_type: Option<String>,
    pub album_id: Option<String>,
    pub artist_id: Option<String>,
    // OpenSubsonic. Absent on a plain Subsonic server, which is why they are
    // Options rather than defaults — a missing sample rate is not 0 Hz.
    pub sampling_rate: Option<i32>,
    pub bit_depth: Option<i32>,
    pub channel_count: Option<i32>,
    pub music_brainz_id: Option<String>,
}

#[derive(Debug, Deserialize)]
struct SubsonicAlbumList {
    #[serde(default)]
    album: Vec<SubsonicAlbum>,
}

#[derive(Debug, Default, Deserialize)]
pub struct SubsonicSearchResult {
    #[serde(default)]
    pub artist: Vec<SubsonicArtist>,
    #[serde(default)]
    pub album: Vec<SubsonicAlbum>,
    #[serde(default)]
    pub song: Vec<SubsonicSong>,
}

#[derive(Debug, Default, Deserialize)]
pub struct SubsonicStarred {
    #[serde(default)]
    pub song: Vec<SubsonicSong>,
    #[serde(default)]
    pub album: Vec<SubsonicAlbum>,
    #[serde(default)]
    pub artist: Vec<SubsonicArtist>,
}

#[derive(Debug, Deserialize)]
pub struct SubsonicSimilarSongs {
    pub song: Option<Vec<SubsonicSong>>,
}

#[derive(Debug, Deserialize)]
pub struct SubsonicTopSongs {
    pub song: Option<Vec<SubsonicSong>>,
}

#[derive(Debug, Deserialize)]
struct SubsonicShares {
    #[serde(default)]
    share: Vec<SubsonicShare>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubsonicShare {
    pub id: String,
    pub url: Option<String>,
    pub description: Option<String>,
    pub username: Option<String>,
    pub created: Option<String>,
    pub expires: Option<String>,
    pub visit_count: Option<i64>,
}

/// Generate a random hex salt string for Subsonic auth.
///
/// The salt goes on the wire next to `md5(password + salt)`, so it has to be
/// unpredictable — a clock- or counter-derived fallback would make the token
/// precomputable from a captured exchange. A request without OS entropy fails
/// rather than authenticating weakly.
fn random_salt() -> Result<String, getrandom::Error> {
    let mut buf = [0u8; 12];
    getrandom::fill(&mut buf)?;
    Ok(buf.iter().map(|b| format!("{:02x}", b)).collect())
}

#[cfg(test)]
mod tests {
    use super::*;

    // --- SubsonicSong deserialization ---

    #[test]
    fn test_deserialize_subsonic_song() {
        let json = r#"{
            "id": "42",
            "title": "Space Oddity",
            "album": "Space Oddity",
            "artist": "David Bowie",
            "track": 1,
            "discNumber": 1,
            "year": 1969,
            "genre": "Rock",
            "duration": 314,
            "bitRate": 320,
            "suffix": "mp3",
            "contentType": "audio/mpeg",
            "albumId": "7",
            "artistId": "3"
        }"#;

        let song: SubsonicSong = serde_json::from_str(json).unwrap();

        assert_eq!(song.id, "42");
        assert_eq!(song.title, "Space Oddity");
        assert_eq!(song.album.as_deref(), Some("Space Oddity"));
        assert_eq!(song.artist.as_deref(), Some("David Bowie"));
        assert_eq!(song.track, Some(1));
        assert_eq!(song.disc_number, Some(1));
        assert_eq!(song.year, Some(1969));
        assert_eq!(song.genre.as_deref(), Some("Rock"));
        assert_eq!(song.duration, Some(314));
        assert_eq!(song.bit_rate, Some(320));
        assert_eq!(song.suffix.as_deref(), Some("mp3"));
        assert_eq!(song.content_type.as_deref(), Some("audio/mpeg"));
        assert_eq!(song.album_id.as_deref(), Some("7"));
        assert_eq!(song.artist_id.as_deref(), Some("3"));
    }

    /// An OpenSubsonic server reports the figures that make a track's quality
    /// legible. Ignoring them left every remote-only track with no sample rate
    /// and no bit depth at all.
    #[test]
    fn opensubsonic_quality_fields_are_read() {
        let json = r#"{
            "id": "000XtGC7jsWEbOjDsZi4Xw",
            "title": "Anguish",
            "suffix": "flac",
            "bitRate": 913,
            "samplingRate": 44100,
            "bitDepth": 16,
            "channelCount": 2
        }"#;

        let song: SubsonicSong = serde_json::from_str(json).unwrap();

        assert_eq!(song.sampling_rate, Some(44100));
        assert_eq!(song.bit_depth, Some(16));
        assert_eq!(song.channel_count, Some(2));
    }

    /// A plain Subsonic server omits them, and a missing sample rate is not
    /// 0 Hz — the fields have to stay absent rather than default.
    #[test]
    fn a_plain_subsonic_song_has_no_quality_figures() {
        let json = r#"{"id": "1", "title": "Track", "bitRate": 320}"#;
        let song: SubsonicSong = serde_json::from_str(json).unwrap();

        assert_eq!(song.sampling_rate, None);
        assert_eq!(song.bit_depth, None);
        assert_eq!(song.channel_count, None);
    }

    #[test]
    fn test_deserialize_subsonic_song_optional_fields_absent() {
        // Only the required fields (id, title) — all Option fields should be None.
        let json = r#"{"id": "99", "title": "Minimal Track"}"#;

        let song: SubsonicSong = serde_json::from_str(json).unwrap();

        assert_eq!(song.id, "99");
        assert_eq!(song.title, "Minimal Track");
        assert!(song.album.is_none());
        assert!(song.artist.is_none());
        assert!(song.track.is_none());
        assert!(song.disc_number.is_none());
        assert!(song.year.is_none());
        assert!(song.duration.is_none());
        assert!(song.bit_rate.is_none());
    }

    // --- SubsonicAlbum deserialization ---

    #[test]
    fn test_deserialize_album_list() {
        let json = r#"{
            "subsonic-response": {
                "status": "ok",
                "version": "1.16.1",
                "albumList2": {
                    "album": [
                        {
                            "id": "1",
                            "name": "Abbey Road",
                            "artist": "The Beatles",
                            "artistId": "10",
                            "songCount": 17,
                            "year": 1969,
                            "genre": "Rock",
                            "created": "2020-01-01T00:00:00"
                        },
                        {
                            "id": "2",
                            "name": "Led Zeppelin IV",
                            "artist": "Led Zeppelin",
                            "artistId": "11",
                            "songCount": 8,
                            "year": 1971,
                            "genre": "Hard Rock",
                            "created": "2020-01-02T00:00:00"
                        }
                    ]
                }
            }
        }"#;

        let wrapper: SubsonicResponseWrapper = serde_json::from_str(json).unwrap();
        let album_list = wrapper
            .subsonic_response
            .album_list2
            .expect("album_list2 should be present");

        assert_eq!(album_list.album.len(), 2);

        let first = &album_list.album[0];
        assert_eq!(first.id, "1");
        assert_eq!(first.name, "Abbey Road");
        assert_eq!(first.artist.as_deref(), Some("The Beatles"));
        assert_eq!(first.artist_id.as_deref(), Some("10"));
        assert_eq!(first.song_count, Some(17));
        assert_eq!(first.year, Some(1969));

        let second = &album_list.album[1];
        assert_eq!(second.id, "2");
        assert_eq!(second.name, "Led Zeppelin IV");
        assert_eq!(second.song_count, Some(8));
    }

    // --- SubsonicClient auth params ---

    #[test]
    fn test_auth_params_format() {
        let client = SubsonicClient::new("http://localhost:4533", "alice", "secret");
        let params = client.auth_params().unwrap();

        // Must contain exactly these six keys.
        assert!(params.contains_key("u"), "missing 'u' param");
        assert!(params.contains_key("t"), "missing 't' param");
        assert!(params.contains_key("s"), "missing 's' param");
        assert!(params.contains_key("v"), "missing 'v' param");
        assert!(params.contains_key("c"), "missing 'c' param");
        assert!(params.contains_key("f"), "missing 'f' param");
        assert_eq!(params.len(), 6);

        assert_eq!(params["u"], "alice");
        assert_eq!(params["v"], "1.16.1");
        assert_eq!(params["c"], "koan");
        assert_eq!(params["f"], "json");
    }

    #[test]
    fn test_auth_params_token_is_md5_of_password_plus_salt() {
        let client = SubsonicClient::new("http://localhost:4533", "bob", "letmein");
        let params = client.auth_params().unwrap();

        let salt = &params["s"];
        let token = &params["t"];

        // The token must equal md5(password + salt).
        let expected = format!("{:x}", md5::compute(format!("letmein{}", salt)));
        assert_eq!(token, &expected);
    }

    #[test]
    fn test_auth_params_salt_is_different_each_call() {
        let client = SubsonicClient::new("http://localhost:4533", "user", "pass");
        let params1 = client.auth_params().unwrap();
        let params2 = client.auth_params().unwrap();

        // Salts should differ across calls (random); tokens will differ too.
        // There is a negligible probability they collide — acceptable in tests.
        assert_ne!(params1["s"], params2["s"], "salt should be random per call");
    }

    // --- stream_url ---

    #[test]
    fn test_stream_url_has_auth() {
        let client = SubsonicClient::new("http://myserver:4533", "user", "pass");
        let url = client.stream_url("track-123").unwrap();

        assert!(url.contains("track-123"), "url must include the track id");
        assert!(url.contains("u=user"), "url must include username param");
        assert!(url.contains("v=1.16.1"), "url must include api version");
        assert!(url.contains("c=koan"), "url must include client name");
        assert!(url.contains("f=json"), "url must include format param");
        assert!(url.contains("/rest/stream"), "url must target /rest/stream");
        assert!(
            url.starts_with("http://myserver:4533"),
            "url must use the configured base_url"
        );
    }

    #[test]
    fn test_stream_url_base_url_trailing_slash_normalised() {
        // SubsonicClient::new strips trailing slashes from base_url.
        let client_with_slash = SubsonicClient::new("http://myserver:4533/", "u", "p");
        let client_no_slash = SubsonicClient::new("http://myserver:4533", "u", "p");

        let url_with = client_with_slash.stream_url("1").unwrap();
        let url_without = client_no_slash.stream_url("1").unwrap();

        // Both should produce the same path prefix (no double slash).
        assert!(
            url_with.contains("/rest/stream"),
            "should not have double slash"
        );
        assert!(!url_with.contains("//rest"), "should not have double slash");
        // Both base URLs normalise to the same path structure.
        assert_eq!(
            url_with.split('?').next(),
            url_without.split('?').next(),
            "path segment should be identical regardless of trailing slash"
        );
    }

    // --- SubsonicAlbumFull deserialization ---

    #[test]
    fn test_deserialize_album_full_with_songs() {
        let json = r#"{
            "id": "5",
            "name": "Kind of Blue",
            "artist": "Miles Davis",
            "artistId": "20",
            "year": 1959,
            "genre": "Jazz",
            "songCount": 5,
            "created": "2021-06-01T00:00:00",
            "song": [
                {"id": "101", "title": "So What"},
                {"id": "102", "title": "Freddie Freeloader"},
                {"id": "103", "title": "Blue in Green"}
            ]
        }"#;

        let album: SubsonicAlbumFull = serde_json::from_str(json).unwrap();

        assert_eq!(album.id, "5");
        assert_eq!(album.name, "Kind of Blue");
        assert_eq!(album.artist.as_deref(), Some("Miles Davis"));
        assert_eq!(album.year, Some(1959));
        assert_eq!(album.song.len(), 3);
        assert_eq!(album.song[0].title, "So What");
        assert_eq!(album.song[2].id, "103");
    }

    #[test]
    fn test_deserialize_album_full_empty_song_list() {
        // When `song` key is absent, the #[serde(default)] should yield an empty Vec.
        let json = r#"{"id": "9", "name": "No Tracks Yet"}"#;

        let album: SubsonicAlbumFull = serde_json::from_str(json).unwrap();

        assert_eq!(album.id, "9");
        assert!(album.song.is_empty(), "song list should default to empty");
    }

    // --- SubsonicSearchResult deserialization ---

    #[test]
    fn test_deserialize_search_result_mixed() {
        let json = r#"{
            "artist": [{"id": "1", "name": "Artist One"}],
            "album":  [{"id": "2", "name": "Album One"}],
            "song":   [{"id": "3", "title": "Song One"}]
        }"#;

        let result: SubsonicSearchResult = serde_json::from_str(json).unwrap();

        assert_eq!(result.artist.len(), 1);
        assert_eq!(result.artist[0].name, "Artist One");
        assert_eq!(result.album.len(), 1);
        assert_eq!(result.album[0].name, "Album One");
        assert_eq!(result.song.len(), 1);
        assert_eq!(result.song[0].title, "Song One");
    }

    #[test]
    fn test_deserialize_search_result_defaults_to_empty() {
        // All three lists are #[serde(default)], so an empty object is valid.
        let result: SubsonicSearchResult = serde_json::from_str("{}").unwrap();

        assert!(result.artist.is_empty());
        assert!(result.album.is_empty());
        assert!(result.song.is_empty());
    }
}