Skip to main content

koan_core/remote/
client.rs

1use std::collections::HashMap;
2use std::path::Path;
3
4use serde::Deserialize;
5use thiserror::Error;
6
7use super::download::{self, DownloadError};
8
9const API_VERSION: &str = "1.16.1";
10const CLIENT_NAME: &str = "koan";
11
12#[derive(Debug, Error)]
13pub enum SubsonicError {
14    #[error("http error: {0}")]
15    Http(#[from] reqwest::Error),
16    #[error("api error: {code} — {message}")]
17    Api { code: i32, message: String },
18    #[error("unexpected response format")]
19    BadResponse,
20    #[error("io error: {0}")]
21    Io(#[from] std::io::Error),
22    #[error("download error: {0}")]
23    Download(#[from] DownloadError),
24    #[error("entropy source unavailable: {0}")]
25    Entropy(#[from] getrandom::Error),
26}
27
28/// A Subsonic server and the credentials that sign requests to it.
29///
30/// Kept separate from `SubsonicClient` because constructing that builds two
31/// blocking `reqwest` clients, each carrying its own runtime — doing so from
32/// inside a tokio runtime panics. A caller that only needs a signed URL, such
33/// as koan's own Subsonic proxy, holds this instead.
34#[derive(Debug, Clone)]
35pub struct SubsonicAuth {
36    pub base_url: String,
37    pub username: String,
38    pub password: String,
39}
40
41impl SubsonicAuth {
42    pub fn new(base_url: &str, username: &str, password: &str) -> Self {
43        Self {
44            base_url: base_url.trim_end_matches('/').to_string(),
45            username: username.to_string(),
46            password: password.to_string(),
47        }
48    }
49
50    /// Build auth query params: u, t (token), s (salt), v, c, f.
51    fn params(&self) -> Result<HashMap<String, String>, SubsonicError> {
52        let salt = random_salt()?;
53
54        let token = format!("{:x}", md5::compute(format!("{}{}", self.password, salt)));
55
56        let mut params = HashMap::new();
57        params.insert("u".into(), self.username.clone());
58        params.insert("t".into(), token);
59        params.insert("s".into(), salt);
60        params.insert("v".into(), API_VERSION.into());
61        params.insert("c".into(), CLIENT_NAME.into());
62        params.insert("f".into(), "json".into());
63        Ok(params)
64    }
65
66    /// Build the streaming URL for a track (doesn't make a request).
67    pub fn stream_url(&self, track_id: &str) -> Result<String, SubsonicError> {
68        let query: String = self
69            .params()?
70            .iter()
71            .map(|(k, v)| format!("{}={}", k, v))
72            .collect::<Vec<_>>()
73            .join("&");
74        Ok(format!(
75            "{}/rest/stream?id={}&{}",
76            self.base_url, track_id, query
77        ))
78    }
79}
80
81/// Subsonic/Navidrome API client.
82///
83/// Holds two HTTP clients with different timeout semantics: `http` bounds a
84/// whole JSON request, which is right for small API responses read in one go;
85/// `downloader` bounds only connect and per-read stalls, so a large track on a
86/// slow link is never cut off for taking too long overall.
87pub struct SubsonicClient {
88    auth: SubsonicAuth,
89    http: reqwest::blocking::Client,
90    downloader: reqwest::blocking::Client,
91}
92
93impl SubsonicClient {
94    pub fn new(base_url: &str, username: &str, password: &str) -> Self {
95        Self::from_auth(SubsonicAuth::new(base_url, username, password))
96    }
97
98    pub fn from_auth(auth: SubsonicAuth) -> Self {
99        Self {
100            auth,
101            http: download::api_client().unwrap_or_else(|e| {
102                log::warn!("falling back to default HTTP client: {}", e);
103                reqwest::blocking::Client::new()
104            }),
105            downloader: download::download_client().unwrap_or_else(|e| {
106                log::warn!("falling back to default download client: {}", e);
107                reqwest::blocking::Client::new()
108            }),
109        }
110    }
111
112    fn auth_params(&self) -> Result<HashMap<String, String>, SubsonicError> {
113        self.auth.params()
114    }
115
116    /// Make a GET request to a Subsonic API endpoint.
117    fn get(&self, endpoint: &str) -> Result<SubsonicResponse, SubsonicError> {
118        self.get_with_params(endpoint, &[])
119    }
120
121    fn get_with_params(
122        &self,
123        endpoint: &str,
124        extra: &[(&str, &str)],
125    ) -> Result<SubsonicResponse, SubsonicError> {
126        let url = format!("{}/rest/{}", self.auth.base_url, endpoint);
127        let mut params = self.auth_params()?;
128        for (k, v) in extra {
129            params.insert((*k).to_string(), (*v).to_string());
130        }
131
132        let resp: SubsonicResponseWrapper = self.http.get(&url).query(&params).send()?.json()?;
133
134        let inner = resp.subsonic_response;
135        if inner.status != "ok" {
136            if let Some(err) = inner.error {
137                return Err(SubsonicError::Api {
138                    code: err.code,
139                    message: err.message,
140                });
141            }
142            return Err(SubsonicError::BadResponse);
143        }
144
145        Ok(inner)
146    }
147
148    /// Detect a Subsonic error returned from an endpoint that should have sent
149    /// binary data.
150    ///
151    /// Subsonic signals failure with HTTP 200 and a JSON or XML error body, so
152    /// checking the status code proves nothing here — without this, an error
153    /// response gets written to disk as if it were audio.
154    fn reject_error_body(resp: &reqwest::blocking::Response) -> Result<(), SubsonicError> {
155        let is_document = resp
156            .headers()
157            .get(reqwest::header::CONTENT_TYPE)
158            .and_then(|v| v.to_str().ok())
159            .is_some_and(|ct| ct.contains("json") || ct.contains("xml"));
160        if is_document {
161            return Err(SubsonicError::BadResponse);
162        }
163        if !resp.status().is_success() {
164            return Err(SubsonicError::BadResponse);
165        }
166        Ok(())
167    }
168
169    /// Fetch cover art bytes for a song or album ID.
170    ///
171    /// Returns the raw image rather than a parsed response — `getCoverArt`
172    /// answers with image data, not JSON, so it can't go through `get()`.
173    /// `size` requests a square thumbnail; omit it for the original.
174    pub fn get_cover_art(&self, id: &str, size: Option<u32>) -> Result<Vec<u8>, SubsonicError> {
175        let url = format!("{}/rest/getCoverArt", self.base_url());
176        let mut params = self.auth_params()?;
177        params.insert("id".into(), id.to_string());
178        if let Some(px) = size {
179            params.insert("size".into(), px.to_string());
180        }
181
182        let resp = self.http.get(&url).query(&params).send()?;
183        Self::reject_error_body(&resp)?;
184        Ok(resp.bytes()?.to_vec())
185    }
186
187    /// Ping the server — verify connection and credentials.
188    pub fn ping(&self) -> Result<(), SubsonicError> {
189        self.get("ping")?;
190        Ok(())
191    }
192
193    /// Get all artists (indexed).
194    pub fn get_artists(&self) -> Result<Vec<SubsonicArtist>, SubsonicError> {
195        let resp = self.get("getArtists")?;
196        let artists_data = resp.artists.ok_or(SubsonicError::BadResponse)?;
197        let mut all = Vec::new();
198        for index in artists_data.index {
199            all.extend(index.artist);
200        }
201        Ok(all)
202    }
203
204    /// Get an album by ID, including its tracks.
205    pub fn get_album(&self, id: &str) -> Result<SubsonicAlbumFull, SubsonicError> {
206        let resp = self.get_with_params("getAlbum", &[("id", id)])?;
207        resp.album.ok_or(SubsonicError::BadResponse)
208    }
209
210    /// Get a paginated list of albums.
211    pub fn get_album_list(
212        &self,
213        list_type: &str,
214        size: u32,
215        offset: u32,
216    ) -> Result<Vec<SubsonicAlbum>, SubsonicError> {
217        let size_str = size.to_string();
218        let offset_str = offset.to_string();
219        let resp = self.get_with_params(
220            "getAlbumList2",
221            &[
222                ("type", list_type),
223                ("size", &size_str),
224                ("offset", &offset_str),
225            ],
226        )?;
227        Ok(resp.album_list2.map(|al| al.album).unwrap_or_default())
228    }
229
230    /// Build the streaming URL for a track (doesn't make a request).
231    pub fn stream_url(&self, track_id: &str) -> Result<String, SubsonicError> {
232        self.auth.stream_url(track_id)
233    }
234
235    /// Stream URL without auth params — safe for database storage.
236    pub fn stream_url_template(&self, track_id: &str) -> String {
237        format!("{}/rest/stream?id={}", self.auth.base_url, track_id)
238    }
239
240    /// Download a track to a local path.
241    pub fn download(&self, track_id: &str, dest: &Path) -> Result<(), SubsonicError> {
242        self.download_with_progress(track_id, dest, |_, _| {})
243    }
244
245    /// Download a track with progress reporting.
246    ///
247    /// The callback receives `(bytes_downloaded, total_bytes)`; total is 0 when
248    /// the server sends no Content-Length, and the count restarts from zero if
249    /// an attempt is retried. `dest` only appears once the file is complete.
250    pub fn download_with_progress(
251        &self,
252        track_id: &str,
253        dest: &Path,
254        on_progress: impl Fn(u64, u64),
255    ) -> Result<(), SubsonicError> {
256        self.fetch_to_file("download", track_id, dest, on_progress)
257    }
258
259    /// Fetch a track through `/rest/stream` instead of `/rest/download`.
260    ///
261    /// `download` returns the untranscoded original and is what library sync
262    /// wants from Navidrome. koan's own server implements only `stream`, so
263    /// that is how the remote bridge pulls audio from a `koan serve` instance.
264    pub fn stream_to_file(
265        &self,
266        track_id: &str,
267        dest: &Path,
268        on_progress: impl Fn(u64, u64),
269    ) -> Result<(), SubsonicError> {
270        self.fetch_to_file("stream", track_id, dest, on_progress)
271    }
272
273    fn fetch_to_file(
274        &self,
275        endpoint: &str,
276        track_id: &str,
277        dest: &Path,
278        on_progress: impl Fn(u64, u64),
279    ) -> Result<(), SubsonicError> {
280        let url = format!("{}/rest/{}", self.auth.base_url, endpoint);
281        download::download_with_retries(
282            dest,
283            download::DEFAULT_ATTEMPTS,
284            || {
285                // Fresh auth params per attempt — the salt must not be replayed.
286                let mut params = self
287                    .auth_params()
288                    .map_err(|e| download::DownloadError::Request(e.to_string()))?;
289                params.insert("id".into(), track_id.to_string());
290                Ok(self.downloader.get(&url).query(&params))
291            },
292            on_progress,
293        )?;
294        Ok(())
295    }
296
297    /// Search for tracks/albums/artists.
298    pub fn search(&self, query: &str) -> Result<SubsonicSearchResult, SubsonicError> {
299        let resp = self.get_with_params("search3", &[("query", query)])?;
300        Ok(resp.search_result3.unwrap_or_default())
301    }
302
303    /// Report a play (scrobble).
304    pub fn scrobble(&self, track_id: &str) -> Result<(), SubsonicError> {
305        self.get_with_params("scrobble", &[("id", track_id)])?;
306        Ok(())
307    }
308
309    /// Star (favourite) a track on the server.
310    pub fn star(&self, track_id: &str) -> Result<(), SubsonicError> {
311        self.get_with_params("star", &[("id", track_id)])?;
312        Ok(())
313    }
314
315    /// Unstar (unfavourite) a track on the server.
316    pub fn unstar(&self, track_id: &str) -> Result<(), SubsonicError> {
317        self.get_with_params("unstar", &[("id", track_id)])?;
318        Ok(())
319    }
320
321    /// Get all starred (favourite) songs from the server.
322    pub fn get_starred(&self) -> Result<Vec<SubsonicSong>, SubsonicError> {
323        let resp = self.get("getStarred2")?;
324        Ok(resp.starred2.map(|s| s.song).unwrap_or_default())
325    }
326
327    /// Create a sharing link for one or more resources (songs, albums, etc).
328    /// Returns the created share including its ID which forms the public URL.
329    pub fn create_share(
330        &self,
331        ids: &[&str],
332        description: Option<&str>,
333    ) -> Result<SubsonicShare, SubsonicError> {
334        let url = format!("{}/rest/createShare", self.auth.base_url);
335        let mut params = self.auth_params()?;
336        if let Some(desc) = description {
337            params.insert("description".into(), desc.to_string());
338        }
339
340        // Subsonic API takes `id` as a repeated param for multiple resources.
341        let mut query: Vec<(String, String)> = params.into_iter().collect();
342        for id in ids {
343            query.push(("id".into(), (*id).to_string()));
344        }
345
346        let resp: SubsonicResponseWrapper = self.http.get(&url).query(&query).send()?.json()?;
347
348        let inner = resp.subsonic_response;
349        if inner.status != "ok" {
350            if let Some(err) = inner.error {
351                return Err(SubsonicError::Api {
352                    code: err.code,
353                    message: err.message,
354                });
355            }
356            return Err(SubsonicError::BadResponse);
357        }
358
359        inner
360            .shares
361            .and_then(|s| s.share.into_iter().next())
362            .ok_or(SubsonicError::BadResponse)
363    }
364
365    /// Get similar songs for a track (Subsonic getSimilarSongs2 endpoint).
366    /// Returns up to `count` similar songs based on the server's algorithm.
367    pub fn get_similar_songs(
368        &self,
369        song_id: &str,
370        count: usize,
371    ) -> Result<Vec<SubsonicSong>, SubsonicError> {
372        let count_str = count.to_string();
373        let resp = self.get_with_params(
374            "getSimilarSongs2",
375            &[("id", song_id), ("count", &count_str)],
376        )?;
377        Ok(resp.similar_songs2.and_then(|s| s.song).unwrap_or_default())
378    }
379
380    /// Get top songs for an artist by name.
381    pub fn get_top_songs(
382        &self,
383        artist_name: &str,
384        count: usize,
385    ) -> Result<Vec<SubsonicSong>, SubsonicError> {
386        let count_str = count.to_string();
387        let resp = self.get_with_params(
388            "getTopSongs",
389            &[("artist", artist_name), ("count", &count_str)],
390        )?;
391        Ok(resp.top_songs.and_then(|t| t.song).unwrap_or_default())
392    }
393
394    /// The configured server base URL (for constructing share links etc).
395    pub fn base_url(&self) -> &str {
396        &self.auth.base_url
397    }
398}
399
400// --- Response types ---
401
402#[derive(Debug, Deserialize)]
403struct SubsonicResponseWrapper {
404    #[serde(rename = "subsonic-response")]
405    subsonic_response: SubsonicResponse,
406}
407
408#[derive(Debug, Deserialize)]
409#[serde(rename_all = "camelCase")]
410struct SubsonicResponse {
411    status: String,
412    error: Option<SubsonicApiError>,
413    artists: Option<SubsonicArtists>,
414    album: Option<SubsonicAlbumFull>,
415    album_list2: Option<SubsonicAlbumList>,
416    search_result3: Option<SubsonicSearchResult>,
417    starred2: Option<SubsonicStarred>,
418    shares: Option<SubsonicShares>,
419    similar_songs2: Option<SubsonicSimilarSongs>,
420    top_songs: Option<SubsonicTopSongs>,
421}
422
423#[derive(Debug, Deserialize)]
424struct SubsonicApiError {
425    code: i32,
426    message: String,
427}
428
429#[derive(Debug, Deserialize)]
430struct SubsonicArtists {
431    index: Vec<SubsonicArtistIndex>,
432}
433
434#[derive(Debug, Deserialize)]
435struct SubsonicArtistIndex {
436    artist: Vec<SubsonicArtist>,
437}
438
439#[derive(Debug, Clone, Deserialize)]
440#[serde(rename_all = "camelCase")]
441pub struct SubsonicArtist {
442    pub id: String,
443    pub name: String,
444    pub album_count: Option<i32>,
445}
446
447#[derive(Debug, Clone, Deserialize)]
448#[serde(rename_all = "camelCase")]
449pub struct SubsonicAlbum {
450    pub id: String,
451    pub name: String,
452    pub artist: Option<String>,
453    pub artist_id: Option<String>,
454    pub song_count: Option<i32>,
455    pub year: Option<i32>,
456    pub genre: Option<String>,
457    pub created: Option<String>,
458}
459
460#[derive(Debug, Clone, Deserialize)]
461#[serde(rename_all = "camelCase")]
462pub struct SubsonicAlbumFull {
463    pub id: String,
464    pub name: String,
465    pub artist: Option<String>,
466    pub artist_id: Option<String>,
467    pub year: Option<i32>,
468    pub genre: Option<String>,
469    pub song_count: Option<i32>,
470    pub created: Option<String>,
471    #[serde(default)]
472    pub song: Vec<SubsonicSong>,
473}
474
475#[derive(Debug, Clone, Deserialize)]
476#[serde(rename_all = "camelCase")]
477pub struct SubsonicSong {
478    pub id: String,
479    pub title: String,
480    pub album: Option<String>,
481    pub artist: Option<String>,
482    pub track: Option<i32>,
483    pub disc_number: Option<i32>,
484    pub year: Option<i32>,
485    pub genre: Option<String>,
486    pub duration: Option<i64>,
487    pub bit_rate: Option<i32>,
488    pub suffix: Option<String>,
489    pub content_type: Option<String>,
490    pub album_id: Option<String>,
491    pub artist_id: Option<String>,
492}
493
494#[derive(Debug, Deserialize)]
495struct SubsonicAlbumList {
496    #[serde(default)]
497    album: Vec<SubsonicAlbum>,
498}
499
500#[derive(Debug, Default, Deserialize)]
501pub struct SubsonicSearchResult {
502    #[serde(default)]
503    pub artist: Vec<SubsonicArtist>,
504    #[serde(default)]
505    pub album: Vec<SubsonicAlbum>,
506    #[serde(default)]
507    pub song: Vec<SubsonicSong>,
508}
509
510#[derive(Debug, Default, Deserialize)]
511pub struct SubsonicStarred {
512    #[serde(default)]
513    pub song: Vec<SubsonicSong>,
514}
515
516#[derive(Debug, Deserialize)]
517pub struct SubsonicSimilarSongs {
518    pub song: Option<Vec<SubsonicSong>>,
519}
520
521#[derive(Debug, Deserialize)]
522pub struct SubsonicTopSongs {
523    pub song: Option<Vec<SubsonicSong>>,
524}
525
526#[derive(Debug, Deserialize)]
527struct SubsonicShares {
528    #[serde(default)]
529    share: Vec<SubsonicShare>,
530}
531
532#[derive(Debug, Clone, Deserialize)]
533#[serde(rename_all = "camelCase")]
534pub struct SubsonicShare {
535    pub id: String,
536    pub url: Option<String>,
537    pub description: Option<String>,
538    pub username: Option<String>,
539    pub created: Option<String>,
540    pub expires: Option<String>,
541    pub visit_count: Option<i64>,
542}
543
544/// Generate a random hex salt string for Subsonic auth.
545///
546/// The salt goes on the wire next to `md5(password + salt)`, so it has to be
547/// unpredictable — a clock- or counter-derived fallback would make the token
548/// precomputable from a captured exchange. A request without OS entropy fails
549/// rather than authenticating weakly.
550fn random_salt() -> Result<String, getrandom::Error> {
551    let mut buf = [0u8; 12];
552    getrandom::fill(&mut buf)?;
553    Ok(buf.iter().map(|b| format!("{:02x}", b)).collect())
554}
555
556#[cfg(test)]
557mod tests {
558    use super::*;
559
560    // --- SubsonicSong deserialization ---
561
562    #[test]
563    fn test_deserialize_subsonic_song() {
564        let json = r#"{
565            "id": "42",
566            "title": "Space Oddity",
567            "album": "Space Oddity",
568            "artist": "David Bowie",
569            "track": 1,
570            "discNumber": 1,
571            "year": 1969,
572            "genre": "Rock",
573            "duration": 314,
574            "bitRate": 320,
575            "suffix": "mp3",
576            "contentType": "audio/mpeg",
577            "albumId": "7",
578            "artistId": "3"
579        }"#;
580
581        let song: SubsonicSong = serde_json::from_str(json).unwrap();
582
583        assert_eq!(song.id, "42");
584        assert_eq!(song.title, "Space Oddity");
585        assert_eq!(song.album.as_deref(), Some("Space Oddity"));
586        assert_eq!(song.artist.as_deref(), Some("David Bowie"));
587        assert_eq!(song.track, Some(1));
588        assert_eq!(song.disc_number, Some(1));
589        assert_eq!(song.year, Some(1969));
590        assert_eq!(song.genre.as_deref(), Some("Rock"));
591        assert_eq!(song.duration, Some(314));
592        assert_eq!(song.bit_rate, Some(320));
593        assert_eq!(song.suffix.as_deref(), Some("mp3"));
594        assert_eq!(song.content_type.as_deref(), Some("audio/mpeg"));
595        assert_eq!(song.album_id.as_deref(), Some("7"));
596        assert_eq!(song.artist_id.as_deref(), Some("3"));
597    }
598
599    #[test]
600    fn test_deserialize_subsonic_song_optional_fields_absent() {
601        // Only the required fields (id, title) — all Option fields should be None.
602        let json = r#"{"id": "99", "title": "Minimal Track"}"#;
603
604        let song: SubsonicSong = serde_json::from_str(json).unwrap();
605
606        assert_eq!(song.id, "99");
607        assert_eq!(song.title, "Minimal Track");
608        assert!(song.album.is_none());
609        assert!(song.artist.is_none());
610        assert!(song.track.is_none());
611        assert!(song.disc_number.is_none());
612        assert!(song.year.is_none());
613        assert!(song.duration.is_none());
614        assert!(song.bit_rate.is_none());
615    }
616
617    // --- SubsonicAlbum deserialization ---
618
619    #[test]
620    fn test_deserialize_album_list() {
621        let json = r#"{
622            "subsonic-response": {
623                "status": "ok",
624                "version": "1.16.1",
625                "albumList2": {
626                    "album": [
627                        {
628                            "id": "1",
629                            "name": "Abbey Road",
630                            "artist": "The Beatles",
631                            "artistId": "10",
632                            "songCount": 17,
633                            "year": 1969,
634                            "genre": "Rock",
635                            "created": "2020-01-01T00:00:00"
636                        },
637                        {
638                            "id": "2",
639                            "name": "Led Zeppelin IV",
640                            "artist": "Led Zeppelin",
641                            "artistId": "11",
642                            "songCount": 8,
643                            "year": 1971,
644                            "genre": "Hard Rock",
645                            "created": "2020-01-02T00:00:00"
646                        }
647                    ]
648                }
649            }
650        }"#;
651
652        let wrapper: SubsonicResponseWrapper = serde_json::from_str(json).unwrap();
653        let album_list = wrapper
654            .subsonic_response
655            .album_list2
656            .expect("album_list2 should be present");
657
658        assert_eq!(album_list.album.len(), 2);
659
660        let first = &album_list.album[0];
661        assert_eq!(first.id, "1");
662        assert_eq!(first.name, "Abbey Road");
663        assert_eq!(first.artist.as_deref(), Some("The Beatles"));
664        assert_eq!(first.artist_id.as_deref(), Some("10"));
665        assert_eq!(first.song_count, Some(17));
666        assert_eq!(first.year, Some(1969));
667
668        let second = &album_list.album[1];
669        assert_eq!(second.id, "2");
670        assert_eq!(second.name, "Led Zeppelin IV");
671        assert_eq!(second.song_count, Some(8));
672    }
673
674    // --- SubsonicClient auth params ---
675
676    #[test]
677    fn test_auth_params_format() {
678        let client = SubsonicClient::new("http://localhost:4533", "alice", "secret");
679        let params = client.auth_params().unwrap();
680
681        // Must contain exactly these six keys.
682        assert!(params.contains_key("u"), "missing 'u' param");
683        assert!(params.contains_key("t"), "missing 't' param");
684        assert!(params.contains_key("s"), "missing 's' param");
685        assert!(params.contains_key("v"), "missing 'v' param");
686        assert!(params.contains_key("c"), "missing 'c' param");
687        assert!(params.contains_key("f"), "missing 'f' param");
688        assert_eq!(params.len(), 6);
689
690        assert_eq!(params["u"], "alice");
691        assert_eq!(params["v"], "1.16.1");
692        assert_eq!(params["c"], "koan");
693        assert_eq!(params["f"], "json");
694    }
695
696    #[test]
697    fn test_auth_params_token_is_md5_of_password_plus_salt() {
698        let client = SubsonicClient::new("http://localhost:4533", "bob", "letmein");
699        let params = client.auth_params().unwrap();
700
701        let salt = &params["s"];
702        let token = &params["t"];
703
704        // The token must equal md5(password + salt).
705        let expected = format!("{:x}", md5::compute(format!("letmein{}", salt)));
706        assert_eq!(token, &expected);
707    }
708
709    #[test]
710    fn test_auth_params_salt_is_different_each_call() {
711        let client = SubsonicClient::new("http://localhost:4533", "user", "pass");
712        let params1 = client.auth_params().unwrap();
713        let params2 = client.auth_params().unwrap();
714
715        // Salts should differ across calls (random); tokens will differ too.
716        // There is a negligible probability they collide — acceptable in tests.
717        assert_ne!(params1["s"], params2["s"], "salt should be random per call");
718    }
719
720    // --- stream_url ---
721
722    #[test]
723    fn test_stream_url_has_auth() {
724        let client = SubsonicClient::new("http://myserver:4533", "user", "pass");
725        let url = client.stream_url("track-123").unwrap();
726
727        assert!(url.contains("track-123"), "url must include the track id");
728        assert!(url.contains("u=user"), "url must include username param");
729        assert!(url.contains("v=1.16.1"), "url must include api version");
730        assert!(url.contains("c=koan"), "url must include client name");
731        assert!(url.contains("f=json"), "url must include format param");
732        assert!(url.contains("/rest/stream"), "url must target /rest/stream");
733        assert!(
734            url.starts_with("http://myserver:4533"),
735            "url must use the configured base_url"
736        );
737    }
738
739    #[test]
740    fn test_stream_url_base_url_trailing_slash_normalised() {
741        // SubsonicClient::new strips trailing slashes from base_url.
742        let client_with_slash = SubsonicClient::new("http://myserver:4533/", "u", "p");
743        let client_no_slash = SubsonicClient::new("http://myserver:4533", "u", "p");
744
745        let url_with = client_with_slash.stream_url("1").unwrap();
746        let url_without = client_no_slash.stream_url("1").unwrap();
747
748        // Both should produce the same path prefix (no double slash).
749        assert!(
750            url_with.contains("/rest/stream"),
751            "should not have double slash"
752        );
753        assert!(!url_with.contains("//rest"), "should not have double slash");
754        // Both base URLs normalise to the same path structure.
755        assert_eq!(
756            url_with.split('?').next(),
757            url_without.split('?').next(),
758            "path segment should be identical regardless of trailing slash"
759        );
760    }
761
762    // --- SubsonicAlbumFull deserialization ---
763
764    #[test]
765    fn test_deserialize_album_full_with_songs() {
766        let json = r#"{
767            "id": "5",
768            "name": "Kind of Blue",
769            "artist": "Miles Davis",
770            "artistId": "20",
771            "year": 1959,
772            "genre": "Jazz",
773            "songCount": 5,
774            "created": "2021-06-01T00:00:00",
775            "song": [
776                {"id": "101", "title": "So What"},
777                {"id": "102", "title": "Freddie Freeloader"},
778                {"id": "103", "title": "Blue in Green"}
779            ]
780        }"#;
781
782        let album: SubsonicAlbumFull = serde_json::from_str(json).unwrap();
783
784        assert_eq!(album.id, "5");
785        assert_eq!(album.name, "Kind of Blue");
786        assert_eq!(album.artist.as_deref(), Some("Miles Davis"));
787        assert_eq!(album.year, Some(1959));
788        assert_eq!(album.song.len(), 3);
789        assert_eq!(album.song[0].title, "So What");
790        assert_eq!(album.song[2].id, "103");
791    }
792
793    #[test]
794    fn test_deserialize_album_full_empty_song_list() {
795        // When `song` key is absent, the #[serde(default)] should yield an empty Vec.
796        let json = r#"{"id": "9", "name": "No Tracks Yet"}"#;
797
798        let album: SubsonicAlbumFull = serde_json::from_str(json).unwrap();
799
800        assert_eq!(album.id, "9");
801        assert!(album.song.is_empty(), "song list should default to empty");
802    }
803
804    // --- SubsonicSearchResult deserialization ---
805
806    #[test]
807    fn test_deserialize_search_result_mixed() {
808        let json = r#"{
809            "artist": [{"id": "1", "name": "Artist One"}],
810            "album":  [{"id": "2", "name": "Album One"}],
811            "song":   [{"id": "3", "title": "Song One"}]
812        }"#;
813
814        let result: SubsonicSearchResult = serde_json::from_str(json).unwrap();
815
816        assert_eq!(result.artist.len(), 1);
817        assert_eq!(result.artist[0].name, "Artist One");
818        assert_eq!(result.album.len(), 1);
819        assert_eq!(result.album[0].name, "Album One");
820        assert_eq!(result.song.len(), 1);
821        assert_eq!(result.song[0].title, "Song One");
822    }
823
824    #[test]
825    fn test_deserialize_search_result_defaults_to_empty() {
826        // All three lists are #[serde(default)], so an empty object is valid.
827        let result: SubsonicSearchResult = serde_json::from_str("{}").unwrap();
828
829        assert!(result.artist.is_empty());
830        assert!(result.album.is_empty());
831        assert!(result.song.is_empty());
832    }
833}