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    /// Everything the server has starred: songs, albums and artists.
328    ///
329    /// Subsonic returns all three from one call, so asking for songs alone
330    /// leaves a starred album invisible to us for no saving.
331    pub fn get_starred_all(&self) -> Result<SubsonicStarred, SubsonicError> {
332        let resp = self.get("getStarred2")?;
333        Ok(resp.starred2.unwrap_or_default())
334    }
335
336    /// Star an album. Subsonic keys this off a different parameter to a song —
337    /// `id` would be read as a track and silently star nothing.
338    pub fn star_album(&self, album_id: &str) -> Result<(), SubsonicError> {
339        self.get_with_params("star", &[("albumId", album_id)])?;
340        Ok(())
341    }
342
343    pub fn unstar_album(&self, album_id: &str) -> Result<(), SubsonicError> {
344        self.get_with_params("unstar", &[("albumId", album_id)])?;
345        Ok(())
346    }
347
348    pub fn star_artist(&self, artist_id: &str) -> Result<(), SubsonicError> {
349        self.get_with_params("star", &[("artistId", artist_id)])?;
350        Ok(())
351    }
352
353    pub fn unstar_artist(&self, artist_id: &str) -> Result<(), SubsonicError> {
354        self.get_with_params("unstar", &[("artistId", artist_id)])?;
355        Ok(())
356    }
357
358    /// Create a sharing link for one or more resources (songs, albums, etc).
359    /// Returns the created share including its ID which forms the public URL.
360    pub fn create_share(
361        &self,
362        ids: &[&str],
363        description: Option<&str>,
364    ) -> Result<SubsonicShare, SubsonicError> {
365        let url = format!("{}/rest/createShare", self.auth.base_url);
366        let mut params = self.auth_params()?;
367        if let Some(desc) = description {
368            params.insert("description".into(), desc.to_string());
369        }
370
371        // Subsonic API takes `id` as a repeated param for multiple resources.
372        let mut query: Vec<(String, String)> = params.into_iter().collect();
373        for id in ids {
374            query.push(("id".into(), (*id).to_string()));
375        }
376
377        let resp: SubsonicResponseWrapper = self.http.get(&url).query(&query).send()?.json()?;
378
379        let inner = resp.subsonic_response;
380        if inner.status != "ok" {
381            if let Some(err) = inner.error {
382                return Err(SubsonicError::Api {
383                    code: err.code,
384                    message: err.message,
385                });
386            }
387            return Err(SubsonicError::BadResponse);
388        }
389
390        inner
391            .shares
392            .and_then(|s| s.share.into_iter().next())
393            .ok_or(SubsonicError::BadResponse)
394    }
395
396    /// Get similar songs for a track (Subsonic getSimilarSongs2 endpoint).
397    /// Returns up to `count` similar songs based on the server's algorithm.
398    pub fn get_similar_songs(
399        &self,
400        song_id: &str,
401        count: usize,
402    ) -> Result<Vec<SubsonicSong>, SubsonicError> {
403        let count_str = count.to_string();
404        let resp = self.get_with_params(
405            "getSimilarSongs2",
406            &[("id", song_id), ("count", &count_str)],
407        )?;
408        Ok(resp.similar_songs2.and_then(|s| s.song).unwrap_or_default())
409    }
410
411    /// Get top songs for an artist by name.
412    pub fn get_top_songs(
413        &self,
414        artist_name: &str,
415        count: usize,
416    ) -> Result<Vec<SubsonicSong>, SubsonicError> {
417        let count_str = count.to_string();
418        let resp = self.get_with_params(
419            "getTopSongs",
420            &[("artist", artist_name), ("count", &count_str)],
421        )?;
422        Ok(resp.top_songs.and_then(|t| t.song).unwrap_or_default())
423    }
424
425    /// The configured server base URL (for constructing share links etc).
426    pub fn base_url(&self) -> &str {
427        &self.auth.base_url
428    }
429}
430
431// --- Response types ---
432
433#[derive(Debug, Deserialize)]
434struct SubsonicResponseWrapper {
435    #[serde(rename = "subsonic-response")]
436    subsonic_response: SubsonicResponse,
437}
438
439#[derive(Debug, Deserialize)]
440#[serde(rename_all = "camelCase")]
441struct SubsonicResponse {
442    status: String,
443    error: Option<SubsonicApiError>,
444    artists: Option<SubsonicArtists>,
445    album: Option<SubsonicAlbumFull>,
446    album_list2: Option<SubsonicAlbumList>,
447    search_result3: Option<SubsonicSearchResult>,
448    starred2: Option<SubsonicStarred>,
449    shares: Option<SubsonicShares>,
450    similar_songs2: Option<SubsonicSimilarSongs>,
451    top_songs: Option<SubsonicTopSongs>,
452}
453
454#[derive(Debug, Deserialize)]
455struct SubsonicApiError {
456    code: i32,
457    message: String,
458}
459
460#[derive(Debug, Deserialize)]
461struct SubsonicArtists {
462    index: Vec<SubsonicArtistIndex>,
463}
464
465#[derive(Debug, Deserialize)]
466struct SubsonicArtistIndex {
467    artist: Vec<SubsonicArtist>,
468}
469
470#[derive(Debug, Clone, Deserialize)]
471#[serde(rename_all = "camelCase")]
472pub struct SubsonicArtist {
473    pub id: String,
474    pub name: String,
475    pub album_count: Option<i32>,
476}
477
478#[derive(Debug, Clone, Deserialize)]
479#[serde(rename_all = "camelCase")]
480pub struct SubsonicAlbum {
481    pub id: String,
482    pub name: String,
483    pub artist: Option<String>,
484    pub artist_id: Option<String>,
485    pub song_count: Option<i32>,
486    pub year: Option<i32>,
487    pub genre: Option<String>,
488    pub created: Option<String>,
489}
490
491#[derive(Debug, Clone, Deserialize)]
492#[serde(rename_all = "camelCase")]
493pub struct SubsonicAlbumFull {
494    pub id: String,
495    pub name: String,
496    pub artist: Option<String>,
497    pub artist_id: Option<String>,
498    pub year: Option<i32>,
499    pub genre: Option<String>,
500    pub song_count: Option<i32>,
501    pub created: Option<String>,
502    #[serde(default)]
503    pub song: Vec<SubsonicSong>,
504}
505
506#[derive(Debug, Clone, Deserialize)]
507#[serde(rename_all = "camelCase")]
508pub struct SubsonicSong {
509    pub id: String,
510    pub title: String,
511    pub album: Option<String>,
512    pub artist: Option<String>,
513    pub track: Option<i32>,
514    pub disc_number: Option<i32>,
515    pub year: Option<i32>,
516    pub genre: Option<String>,
517    pub duration: Option<i64>,
518    pub bit_rate: Option<i32>,
519    pub suffix: Option<String>,
520    pub content_type: Option<String>,
521    pub album_id: Option<String>,
522    pub artist_id: Option<String>,
523}
524
525#[derive(Debug, Deserialize)]
526struct SubsonicAlbumList {
527    #[serde(default)]
528    album: Vec<SubsonicAlbum>,
529}
530
531#[derive(Debug, Default, Deserialize)]
532pub struct SubsonicSearchResult {
533    #[serde(default)]
534    pub artist: Vec<SubsonicArtist>,
535    #[serde(default)]
536    pub album: Vec<SubsonicAlbum>,
537    #[serde(default)]
538    pub song: Vec<SubsonicSong>,
539}
540
541#[derive(Debug, Default, Deserialize)]
542pub struct SubsonicStarred {
543    #[serde(default)]
544    pub song: Vec<SubsonicSong>,
545    #[serde(default)]
546    pub album: Vec<SubsonicAlbum>,
547    #[serde(default)]
548    pub artist: Vec<SubsonicArtist>,
549}
550
551#[derive(Debug, Deserialize)]
552pub struct SubsonicSimilarSongs {
553    pub song: Option<Vec<SubsonicSong>>,
554}
555
556#[derive(Debug, Deserialize)]
557pub struct SubsonicTopSongs {
558    pub song: Option<Vec<SubsonicSong>>,
559}
560
561#[derive(Debug, Deserialize)]
562struct SubsonicShares {
563    #[serde(default)]
564    share: Vec<SubsonicShare>,
565}
566
567#[derive(Debug, Clone, Deserialize)]
568#[serde(rename_all = "camelCase")]
569pub struct SubsonicShare {
570    pub id: String,
571    pub url: Option<String>,
572    pub description: Option<String>,
573    pub username: Option<String>,
574    pub created: Option<String>,
575    pub expires: Option<String>,
576    pub visit_count: Option<i64>,
577}
578
579/// Generate a random hex salt string for Subsonic auth.
580///
581/// The salt goes on the wire next to `md5(password + salt)`, so it has to be
582/// unpredictable — a clock- or counter-derived fallback would make the token
583/// precomputable from a captured exchange. A request without OS entropy fails
584/// rather than authenticating weakly.
585fn random_salt() -> Result<String, getrandom::Error> {
586    let mut buf = [0u8; 12];
587    getrandom::fill(&mut buf)?;
588    Ok(buf.iter().map(|b| format!("{:02x}", b)).collect())
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594
595    // --- SubsonicSong deserialization ---
596
597    #[test]
598    fn test_deserialize_subsonic_song() {
599        let json = r#"{
600            "id": "42",
601            "title": "Space Oddity",
602            "album": "Space Oddity",
603            "artist": "David Bowie",
604            "track": 1,
605            "discNumber": 1,
606            "year": 1969,
607            "genre": "Rock",
608            "duration": 314,
609            "bitRate": 320,
610            "suffix": "mp3",
611            "contentType": "audio/mpeg",
612            "albumId": "7",
613            "artistId": "3"
614        }"#;
615
616        let song: SubsonicSong = serde_json::from_str(json).unwrap();
617
618        assert_eq!(song.id, "42");
619        assert_eq!(song.title, "Space Oddity");
620        assert_eq!(song.album.as_deref(), Some("Space Oddity"));
621        assert_eq!(song.artist.as_deref(), Some("David Bowie"));
622        assert_eq!(song.track, Some(1));
623        assert_eq!(song.disc_number, Some(1));
624        assert_eq!(song.year, Some(1969));
625        assert_eq!(song.genre.as_deref(), Some("Rock"));
626        assert_eq!(song.duration, Some(314));
627        assert_eq!(song.bit_rate, Some(320));
628        assert_eq!(song.suffix.as_deref(), Some("mp3"));
629        assert_eq!(song.content_type.as_deref(), Some("audio/mpeg"));
630        assert_eq!(song.album_id.as_deref(), Some("7"));
631        assert_eq!(song.artist_id.as_deref(), Some("3"));
632    }
633
634    #[test]
635    fn test_deserialize_subsonic_song_optional_fields_absent() {
636        // Only the required fields (id, title) — all Option fields should be None.
637        let json = r#"{"id": "99", "title": "Minimal Track"}"#;
638
639        let song: SubsonicSong = serde_json::from_str(json).unwrap();
640
641        assert_eq!(song.id, "99");
642        assert_eq!(song.title, "Minimal Track");
643        assert!(song.album.is_none());
644        assert!(song.artist.is_none());
645        assert!(song.track.is_none());
646        assert!(song.disc_number.is_none());
647        assert!(song.year.is_none());
648        assert!(song.duration.is_none());
649        assert!(song.bit_rate.is_none());
650    }
651
652    // --- SubsonicAlbum deserialization ---
653
654    #[test]
655    fn test_deserialize_album_list() {
656        let json = r#"{
657            "subsonic-response": {
658                "status": "ok",
659                "version": "1.16.1",
660                "albumList2": {
661                    "album": [
662                        {
663                            "id": "1",
664                            "name": "Abbey Road",
665                            "artist": "The Beatles",
666                            "artistId": "10",
667                            "songCount": 17,
668                            "year": 1969,
669                            "genre": "Rock",
670                            "created": "2020-01-01T00:00:00"
671                        },
672                        {
673                            "id": "2",
674                            "name": "Led Zeppelin IV",
675                            "artist": "Led Zeppelin",
676                            "artistId": "11",
677                            "songCount": 8,
678                            "year": 1971,
679                            "genre": "Hard Rock",
680                            "created": "2020-01-02T00:00:00"
681                        }
682                    ]
683                }
684            }
685        }"#;
686
687        let wrapper: SubsonicResponseWrapper = serde_json::from_str(json).unwrap();
688        let album_list = wrapper
689            .subsonic_response
690            .album_list2
691            .expect("album_list2 should be present");
692
693        assert_eq!(album_list.album.len(), 2);
694
695        let first = &album_list.album[0];
696        assert_eq!(first.id, "1");
697        assert_eq!(first.name, "Abbey Road");
698        assert_eq!(first.artist.as_deref(), Some("The Beatles"));
699        assert_eq!(first.artist_id.as_deref(), Some("10"));
700        assert_eq!(first.song_count, Some(17));
701        assert_eq!(first.year, Some(1969));
702
703        let second = &album_list.album[1];
704        assert_eq!(second.id, "2");
705        assert_eq!(second.name, "Led Zeppelin IV");
706        assert_eq!(second.song_count, Some(8));
707    }
708
709    // --- SubsonicClient auth params ---
710
711    #[test]
712    fn test_auth_params_format() {
713        let client = SubsonicClient::new("http://localhost:4533", "alice", "secret");
714        let params = client.auth_params().unwrap();
715
716        // Must contain exactly these six keys.
717        assert!(params.contains_key("u"), "missing 'u' param");
718        assert!(params.contains_key("t"), "missing 't' param");
719        assert!(params.contains_key("s"), "missing 's' param");
720        assert!(params.contains_key("v"), "missing 'v' param");
721        assert!(params.contains_key("c"), "missing 'c' param");
722        assert!(params.contains_key("f"), "missing 'f' param");
723        assert_eq!(params.len(), 6);
724
725        assert_eq!(params["u"], "alice");
726        assert_eq!(params["v"], "1.16.1");
727        assert_eq!(params["c"], "koan");
728        assert_eq!(params["f"], "json");
729    }
730
731    #[test]
732    fn test_auth_params_token_is_md5_of_password_plus_salt() {
733        let client = SubsonicClient::new("http://localhost:4533", "bob", "letmein");
734        let params = client.auth_params().unwrap();
735
736        let salt = &params["s"];
737        let token = &params["t"];
738
739        // The token must equal md5(password + salt).
740        let expected = format!("{:x}", md5::compute(format!("letmein{}", salt)));
741        assert_eq!(token, &expected);
742    }
743
744    #[test]
745    fn test_auth_params_salt_is_different_each_call() {
746        let client = SubsonicClient::new("http://localhost:4533", "user", "pass");
747        let params1 = client.auth_params().unwrap();
748        let params2 = client.auth_params().unwrap();
749
750        // Salts should differ across calls (random); tokens will differ too.
751        // There is a negligible probability they collide — acceptable in tests.
752        assert_ne!(params1["s"], params2["s"], "salt should be random per call");
753    }
754
755    // --- stream_url ---
756
757    #[test]
758    fn test_stream_url_has_auth() {
759        let client = SubsonicClient::new("http://myserver:4533", "user", "pass");
760        let url = client.stream_url("track-123").unwrap();
761
762        assert!(url.contains("track-123"), "url must include the track id");
763        assert!(url.contains("u=user"), "url must include username param");
764        assert!(url.contains("v=1.16.1"), "url must include api version");
765        assert!(url.contains("c=koan"), "url must include client name");
766        assert!(url.contains("f=json"), "url must include format param");
767        assert!(url.contains("/rest/stream"), "url must target /rest/stream");
768        assert!(
769            url.starts_with("http://myserver:4533"),
770            "url must use the configured base_url"
771        );
772    }
773
774    #[test]
775    fn test_stream_url_base_url_trailing_slash_normalised() {
776        // SubsonicClient::new strips trailing slashes from base_url.
777        let client_with_slash = SubsonicClient::new("http://myserver:4533/", "u", "p");
778        let client_no_slash = SubsonicClient::new("http://myserver:4533", "u", "p");
779
780        let url_with = client_with_slash.stream_url("1").unwrap();
781        let url_without = client_no_slash.stream_url("1").unwrap();
782
783        // Both should produce the same path prefix (no double slash).
784        assert!(
785            url_with.contains("/rest/stream"),
786            "should not have double slash"
787        );
788        assert!(!url_with.contains("//rest"), "should not have double slash");
789        // Both base URLs normalise to the same path structure.
790        assert_eq!(
791            url_with.split('?').next(),
792            url_without.split('?').next(),
793            "path segment should be identical regardless of trailing slash"
794        );
795    }
796
797    // --- SubsonicAlbumFull deserialization ---
798
799    #[test]
800    fn test_deserialize_album_full_with_songs() {
801        let json = r#"{
802            "id": "5",
803            "name": "Kind of Blue",
804            "artist": "Miles Davis",
805            "artistId": "20",
806            "year": 1959,
807            "genre": "Jazz",
808            "songCount": 5,
809            "created": "2021-06-01T00:00:00",
810            "song": [
811                {"id": "101", "title": "So What"},
812                {"id": "102", "title": "Freddie Freeloader"},
813                {"id": "103", "title": "Blue in Green"}
814            ]
815        }"#;
816
817        let album: SubsonicAlbumFull = serde_json::from_str(json).unwrap();
818
819        assert_eq!(album.id, "5");
820        assert_eq!(album.name, "Kind of Blue");
821        assert_eq!(album.artist.as_deref(), Some("Miles Davis"));
822        assert_eq!(album.year, Some(1959));
823        assert_eq!(album.song.len(), 3);
824        assert_eq!(album.song[0].title, "So What");
825        assert_eq!(album.song[2].id, "103");
826    }
827
828    #[test]
829    fn test_deserialize_album_full_empty_song_list() {
830        // When `song` key is absent, the #[serde(default)] should yield an empty Vec.
831        let json = r#"{"id": "9", "name": "No Tracks Yet"}"#;
832
833        let album: SubsonicAlbumFull = serde_json::from_str(json).unwrap();
834
835        assert_eq!(album.id, "9");
836        assert!(album.song.is_empty(), "song list should default to empty");
837    }
838
839    // --- SubsonicSearchResult deserialization ---
840
841    #[test]
842    fn test_deserialize_search_result_mixed() {
843        let json = r#"{
844            "artist": [{"id": "1", "name": "Artist One"}],
845            "album":  [{"id": "2", "name": "Album One"}],
846            "song":   [{"id": "3", "title": "Song One"}]
847        }"#;
848
849        let result: SubsonicSearchResult = serde_json::from_str(json).unwrap();
850
851        assert_eq!(result.artist.len(), 1);
852        assert_eq!(result.artist[0].name, "Artist One");
853        assert_eq!(result.album.len(), 1);
854        assert_eq!(result.album[0].name, "Album One");
855        assert_eq!(result.song.len(), 1);
856        assert_eq!(result.song[0].title, "Song One");
857    }
858
859    #[test]
860    fn test_deserialize_search_result_defaults_to_empty() {
861        // All three lists are #[serde(default)], so an empty object is valid.
862        let result: SubsonicSearchResult = serde_json::from_str("{}").unwrap();
863
864        assert!(result.artist.is_empty());
865        assert!(result.album.is_empty());
866        assert!(result.song.is_empty());
867    }
868}