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, PartialEq, Eq)]
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    // OpenSubsonic. Both arrive in `getArtists`, so keeping them costs no
477    // extra request.
478    pub music_brainz_id: Option<String>,
479    pub sort_name: Option<String>,
480}
481
482#[derive(Debug, Clone, Deserialize)]
483#[serde(rename_all = "camelCase")]
484pub struct SubsonicAlbum {
485    pub id: String,
486    pub name: String,
487    pub artist: Option<String>,
488    pub artist_id: Option<String>,
489    pub song_count: Option<i32>,
490    pub year: Option<i32>,
491    pub genre: Option<String>,
492    pub created: Option<String>,
493    // OpenSubsonic. All of these arrive in `getAlbumList2`, which the sync
494    // already pages through.
495    pub music_brainz_id: Option<String>,
496    pub sort_name: Option<String>,
497    #[serde(default)]
498    pub record_labels: Vec<SubsonicName>,
499}
500
501/// A bare `{"name": "..."}` object. The server uses this shape for record
502/// labels, genres and moods alike.
503#[derive(Debug, Clone, Deserialize)]
504pub struct SubsonicName {
505    pub name: String,
506}
507
508#[derive(Debug, Clone, Deserialize)]
509#[serde(rename_all = "camelCase")]
510pub struct SubsonicAlbumFull {
511    pub id: String,
512    pub name: String,
513    pub artist: Option<String>,
514    pub artist_id: Option<String>,
515    pub year: Option<i32>,
516    pub genre: Option<String>,
517    pub song_count: Option<i32>,
518    pub created: Option<String>,
519    pub music_brainz_id: Option<String>,
520    pub sort_name: Option<String>,
521    #[serde(default)]
522    pub record_labels: Vec<SubsonicName>,
523    #[serde(default)]
524    pub song: Vec<SubsonicSong>,
525}
526
527#[derive(Debug, Clone, Deserialize)]
528#[serde(rename_all = "camelCase")]
529pub struct SubsonicSong {
530    pub id: String,
531    pub title: String,
532    pub album: Option<String>,
533    pub artist: Option<String>,
534    pub track: Option<i32>,
535    pub disc_number: Option<i32>,
536    pub year: Option<i32>,
537    pub genre: Option<String>,
538    pub duration: Option<i64>,
539    pub bit_rate: Option<i32>,
540    pub suffix: Option<String>,
541    pub content_type: Option<String>,
542    pub album_id: Option<String>,
543    pub artist_id: Option<String>,
544    // OpenSubsonic. Absent on a plain Subsonic server, which is why they are
545    // Options rather than defaults — a missing sample rate is not 0 Hz.
546    pub sampling_rate: Option<i32>,
547    pub bit_depth: Option<i32>,
548    pub channel_count: Option<i32>,
549    pub music_brainz_id: Option<String>,
550}
551
552#[derive(Debug, Deserialize)]
553struct SubsonicAlbumList {
554    #[serde(default)]
555    album: Vec<SubsonicAlbum>,
556}
557
558#[derive(Debug, Default, Deserialize)]
559pub struct SubsonicSearchResult {
560    #[serde(default)]
561    pub artist: Vec<SubsonicArtist>,
562    #[serde(default)]
563    pub album: Vec<SubsonicAlbum>,
564    #[serde(default)]
565    pub song: Vec<SubsonicSong>,
566}
567
568#[derive(Debug, Default, Deserialize)]
569pub struct SubsonicStarred {
570    #[serde(default)]
571    pub song: Vec<SubsonicSong>,
572    #[serde(default)]
573    pub album: Vec<SubsonicAlbum>,
574    #[serde(default)]
575    pub artist: Vec<SubsonicArtist>,
576}
577
578#[derive(Debug, Deserialize)]
579pub struct SubsonicSimilarSongs {
580    pub song: Option<Vec<SubsonicSong>>,
581}
582
583#[derive(Debug, Deserialize)]
584pub struct SubsonicTopSongs {
585    pub song: Option<Vec<SubsonicSong>>,
586}
587
588#[derive(Debug, Deserialize)]
589struct SubsonicShares {
590    #[serde(default)]
591    share: Vec<SubsonicShare>,
592}
593
594#[derive(Debug, Clone, Deserialize)]
595#[serde(rename_all = "camelCase")]
596pub struct SubsonicShare {
597    pub id: String,
598    pub url: Option<String>,
599    pub description: Option<String>,
600    pub username: Option<String>,
601    pub created: Option<String>,
602    pub expires: Option<String>,
603    pub visit_count: Option<i64>,
604}
605
606/// Generate a random hex salt string for Subsonic auth.
607///
608/// The salt goes on the wire next to `md5(password + salt)`, so it has to be
609/// unpredictable — a clock- or counter-derived fallback would make the token
610/// precomputable from a captured exchange. A request without OS entropy fails
611/// rather than authenticating weakly.
612fn random_salt() -> Result<String, getrandom::Error> {
613    let mut buf = [0u8; 12];
614    getrandom::fill(&mut buf)?;
615    Ok(buf.iter().map(|b| format!("{:02x}", b)).collect())
616}
617
618#[cfg(test)]
619mod tests {
620    use super::*;
621
622    // --- SubsonicSong deserialization ---
623
624    #[test]
625    fn test_deserialize_subsonic_song() {
626        let json = r#"{
627            "id": "42",
628            "title": "Space Oddity",
629            "album": "Space Oddity",
630            "artist": "David Bowie",
631            "track": 1,
632            "discNumber": 1,
633            "year": 1969,
634            "genre": "Rock",
635            "duration": 314,
636            "bitRate": 320,
637            "suffix": "mp3",
638            "contentType": "audio/mpeg",
639            "albumId": "7",
640            "artistId": "3"
641        }"#;
642
643        let song: SubsonicSong = serde_json::from_str(json).unwrap();
644
645        assert_eq!(song.id, "42");
646        assert_eq!(song.title, "Space Oddity");
647        assert_eq!(song.album.as_deref(), Some("Space Oddity"));
648        assert_eq!(song.artist.as_deref(), Some("David Bowie"));
649        assert_eq!(song.track, Some(1));
650        assert_eq!(song.disc_number, Some(1));
651        assert_eq!(song.year, Some(1969));
652        assert_eq!(song.genre.as_deref(), Some("Rock"));
653        assert_eq!(song.duration, Some(314));
654        assert_eq!(song.bit_rate, Some(320));
655        assert_eq!(song.suffix.as_deref(), Some("mp3"));
656        assert_eq!(song.content_type.as_deref(), Some("audio/mpeg"));
657        assert_eq!(song.album_id.as_deref(), Some("7"));
658        assert_eq!(song.artist_id.as_deref(), Some("3"));
659    }
660
661    /// An OpenSubsonic server reports the figures that make a track's quality
662    /// legible. Ignoring them left every remote-only track with no sample rate
663    /// and no bit depth at all.
664    #[test]
665    fn opensubsonic_quality_fields_are_read() {
666        let json = r#"{
667            "id": "000XtGC7jsWEbOjDsZi4Xw",
668            "title": "Anguish",
669            "suffix": "flac",
670            "bitRate": 913,
671            "samplingRate": 44100,
672            "bitDepth": 16,
673            "channelCount": 2
674        }"#;
675
676        let song: SubsonicSong = serde_json::from_str(json).unwrap();
677
678        assert_eq!(song.sampling_rate, Some(44100));
679        assert_eq!(song.bit_depth, Some(16));
680        assert_eq!(song.channel_count, Some(2));
681    }
682
683    /// A plain Subsonic server omits them, and a missing sample rate is not
684    /// 0 Hz — the fields have to stay absent rather than default.
685    #[test]
686    fn a_plain_subsonic_song_has_no_quality_figures() {
687        let json = r#"{"id": "1", "title": "Track", "bitRate": 320}"#;
688        let song: SubsonicSong = serde_json::from_str(json).unwrap();
689
690        assert_eq!(song.sampling_rate, None);
691        assert_eq!(song.bit_depth, None);
692        assert_eq!(song.channel_count, None);
693    }
694
695    #[test]
696    fn test_deserialize_subsonic_song_optional_fields_absent() {
697        // Only the required fields (id, title) — all Option fields should be None.
698        let json = r#"{"id": "99", "title": "Minimal Track"}"#;
699
700        let song: SubsonicSong = serde_json::from_str(json).unwrap();
701
702        assert_eq!(song.id, "99");
703        assert_eq!(song.title, "Minimal Track");
704        assert!(song.album.is_none());
705        assert!(song.artist.is_none());
706        assert!(song.track.is_none());
707        assert!(song.disc_number.is_none());
708        assert!(song.year.is_none());
709        assert!(song.duration.is_none());
710        assert!(song.bit_rate.is_none());
711    }
712
713    // --- SubsonicAlbum deserialization ---
714
715    #[test]
716    fn test_deserialize_album_list() {
717        let json = r#"{
718            "subsonic-response": {
719                "status": "ok",
720                "version": "1.16.1",
721                "albumList2": {
722                    "album": [
723                        {
724                            "id": "1",
725                            "name": "Abbey Road",
726                            "artist": "The Beatles",
727                            "artistId": "10",
728                            "songCount": 17,
729                            "year": 1969,
730                            "genre": "Rock",
731                            "created": "2020-01-01T00:00:00"
732                        },
733                        {
734                            "id": "2",
735                            "name": "Led Zeppelin IV",
736                            "artist": "Led Zeppelin",
737                            "artistId": "11",
738                            "songCount": 8,
739                            "year": 1971,
740                            "genre": "Hard Rock",
741                            "created": "2020-01-02T00:00:00"
742                        }
743                    ]
744                }
745            }
746        }"#;
747
748        let wrapper: SubsonicResponseWrapper = serde_json::from_str(json).unwrap();
749        let album_list = wrapper
750            .subsonic_response
751            .album_list2
752            .expect("album_list2 should be present");
753
754        assert_eq!(album_list.album.len(), 2);
755
756        let first = &album_list.album[0];
757        assert_eq!(first.id, "1");
758        assert_eq!(first.name, "Abbey Road");
759        assert_eq!(first.artist.as_deref(), Some("The Beatles"));
760        assert_eq!(first.artist_id.as_deref(), Some("10"));
761        assert_eq!(first.song_count, Some(17));
762        assert_eq!(first.year, Some(1969));
763
764        let second = &album_list.album[1];
765        assert_eq!(second.id, "2");
766        assert_eq!(second.name, "Led Zeppelin IV");
767        assert_eq!(second.song_count, Some(8));
768    }
769
770    // --- SubsonicClient auth params ---
771
772    #[test]
773    fn test_auth_params_format() {
774        let client = SubsonicClient::new("http://localhost:4533", "alice", "secret");
775        let params = client.auth_params().unwrap();
776
777        // Must contain exactly these six keys.
778        assert!(params.contains_key("u"), "missing 'u' param");
779        assert!(params.contains_key("t"), "missing 't' param");
780        assert!(params.contains_key("s"), "missing 's' param");
781        assert!(params.contains_key("v"), "missing 'v' param");
782        assert!(params.contains_key("c"), "missing 'c' param");
783        assert!(params.contains_key("f"), "missing 'f' param");
784        assert_eq!(params.len(), 6);
785
786        assert_eq!(params["u"], "alice");
787        assert_eq!(params["v"], "1.16.1");
788        assert_eq!(params["c"], "koan");
789        assert_eq!(params["f"], "json");
790    }
791
792    #[test]
793    fn test_auth_params_token_is_md5_of_password_plus_salt() {
794        let client = SubsonicClient::new("http://localhost:4533", "bob", "letmein");
795        let params = client.auth_params().unwrap();
796
797        let salt = &params["s"];
798        let token = &params["t"];
799
800        // The token must equal md5(password + salt).
801        let expected = format!("{:x}", md5::compute(format!("letmein{}", salt)));
802        assert_eq!(token, &expected);
803    }
804
805    #[test]
806    fn test_auth_params_salt_is_different_each_call() {
807        let client = SubsonicClient::new("http://localhost:4533", "user", "pass");
808        let params1 = client.auth_params().unwrap();
809        let params2 = client.auth_params().unwrap();
810
811        // Salts should differ across calls (random); tokens will differ too.
812        // There is a negligible probability they collide — acceptable in tests.
813        assert_ne!(params1["s"], params2["s"], "salt should be random per call");
814    }
815
816    // --- stream_url ---
817
818    #[test]
819    fn test_stream_url_has_auth() {
820        let client = SubsonicClient::new("http://myserver:4533", "user", "pass");
821        let url = client.stream_url("track-123").unwrap();
822
823        assert!(url.contains("track-123"), "url must include the track id");
824        assert!(url.contains("u=user"), "url must include username param");
825        assert!(url.contains("v=1.16.1"), "url must include api version");
826        assert!(url.contains("c=koan"), "url must include client name");
827        assert!(url.contains("f=json"), "url must include format param");
828        assert!(url.contains("/rest/stream"), "url must target /rest/stream");
829        assert!(
830            url.starts_with("http://myserver:4533"),
831            "url must use the configured base_url"
832        );
833    }
834
835    #[test]
836    fn test_stream_url_base_url_trailing_slash_normalised() {
837        // SubsonicClient::new strips trailing slashes from base_url.
838        let client_with_slash = SubsonicClient::new("http://myserver:4533/", "u", "p");
839        let client_no_slash = SubsonicClient::new("http://myserver:4533", "u", "p");
840
841        let url_with = client_with_slash.stream_url("1").unwrap();
842        let url_without = client_no_slash.stream_url("1").unwrap();
843
844        // Both should produce the same path prefix (no double slash).
845        assert!(
846            url_with.contains("/rest/stream"),
847            "should not have double slash"
848        );
849        assert!(!url_with.contains("//rest"), "should not have double slash");
850        // Both base URLs normalise to the same path structure.
851        assert_eq!(
852            url_with.split('?').next(),
853            url_without.split('?').next(),
854            "path segment should be identical regardless of trailing slash"
855        );
856    }
857
858    // --- SubsonicAlbumFull deserialization ---
859
860    #[test]
861    fn test_deserialize_album_full_with_songs() {
862        let json = r#"{
863            "id": "5",
864            "name": "Kind of Blue",
865            "artist": "Miles Davis",
866            "artistId": "20",
867            "year": 1959,
868            "genre": "Jazz",
869            "songCount": 5,
870            "created": "2021-06-01T00:00:00",
871            "song": [
872                {"id": "101", "title": "So What"},
873                {"id": "102", "title": "Freddie Freeloader"},
874                {"id": "103", "title": "Blue in Green"}
875            ]
876        }"#;
877
878        let album: SubsonicAlbumFull = serde_json::from_str(json).unwrap();
879
880        assert_eq!(album.id, "5");
881        assert_eq!(album.name, "Kind of Blue");
882        assert_eq!(album.artist.as_deref(), Some("Miles Davis"));
883        assert_eq!(album.year, Some(1959));
884        assert_eq!(album.song.len(), 3);
885        assert_eq!(album.song[0].title, "So What");
886        assert_eq!(album.song[2].id, "103");
887    }
888
889    #[test]
890    fn test_deserialize_album_full_empty_song_list() {
891        // When `song` key is absent, the #[serde(default)] should yield an empty Vec.
892        let json = r#"{"id": "9", "name": "No Tracks Yet"}"#;
893
894        let album: SubsonicAlbumFull = serde_json::from_str(json).unwrap();
895
896        assert_eq!(album.id, "9");
897        assert!(album.song.is_empty(), "song list should default to empty");
898    }
899
900    // --- SubsonicSearchResult deserialization ---
901
902    #[test]
903    fn test_deserialize_search_result_mixed() {
904        let json = r#"{
905            "artist": [{"id": "1", "name": "Artist One"}],
906            "album":  [{"id": "2", "name": "Album One"}],
907            "song":   [{"id": "3", "title": "Song One"}]
908        }"#;
909
910        let result: SubsonicSearchResult = serde_json::from_str(json).unwrap();
911
912        assert_eq!(result.artist.len(), 1);
913        assert_eq!(result.artist[0].name, "Artist One");
914        assert_eq!(result.album.len(), 1);
915        assert_eq!(result.album[0].name, "Album One");
916        assert_eq!(result.song.len(), 1);
917        assert_eq!(result.song[0].title, "Song One");
918    }
919
920    #[test]
921    fn test_deserialize_search_result_defaults_to_empty() {
922        // All three lists are #[serde(default)], so an empty object is valid.
923        let result: SubsonicSearchResult = serde_json::from_str("{}").unwrap();
924
925        assert!(result.artist.is_empty());
926        assert!(result.album.is_empty());
927        assert!(result.song.is_empty());
928    }
929}