use crate::{ config::Config, downloads::Acquisition, model::{Item, Song, View, home_items}, playlists::{PlaylistChoice, PlaylistTarget, parse_playlist_choices}, }; use anyhow::{Context, Result, bail}; use rand::RngCore; use reqwest::{ Url, blocking::{Client, RequestBuilder}, }; use serde_json::Value; use std::{ sync::atomic::{AtomicU8, Ordering}, time::Duration, }; pub struct Api { base: Url, username: String, password: String, api_key: String, http: Client, octo: AtomicU8, acquisition_support: std::sync::OnceLock, } impl Api { pub fn new(config: Config) -> Result { let base = Url::parse(&format!("{}/", config.server.trim_end_matches('/'))) .context("Invalid server address")?; if !matches!(base.scheme(), "http" | "https") || !base.username().is_empty() || base.password().is_some() || base.query().is_some() || base.fragment().is_some() { bail!("Server must be an HTTP(S) address without credentials, query or fragment"); } Ok(Self { base, octo: AtomicU8::new(0), acquisition_support: std::sync::OnceLock::new(), username: config.username, password: config.password, api_key: config.api_key, http: Client::builder() .timeout(Duration::from_secs(180)) .connect_timeout(Duration::from_secs(10)) .redirect(reqwest::redirect::Policy::none()) .build()?, }) } /// Sign every call with a fresh salt; never print signed URLs in errors. pub fn url(&self, endpoint: &str, params: &[(&str, String)]) -> Result { let mut url = self .base .join(&format!("rest/{endpoint}")) .context("Invalid endpoint")?; let mut query = url.query_pairs_mut(); query.extend_pairs([("v", "1.16.1"), ("c", "octo-tui"), ("f", "json")]); if self.api_key.is_empty() { let mut bytes = [0u8; 16]; rand::thread_rng().fill_bytes(&mut bytes); let salt = bytes.iter().map(|b| format!("{b:02x}")).collect::(); let token = format!("{:x}", md5::compute(format!("{}{salt}", self.password))); query.extend_pairs([("u", self.username.as_str()), ("t", &token), ("s", &salt)]); } else { query.append_pair("apiKey", &self.api_key); } query.extend_pairs(params.iter().map(|(k, v)| (*k, v.as_str()))); drop(query); Ok(url) } pub fn call(&self, endpoint: &str, params: &[(&str, String)]) -> Result { Self::send_json(endpoint, self.http.get(self.url(endpoint, params)?)) } /// Announce a track using Subsonic's Now Playing notification. pub fn report_now_playing(&self, id: &str) -> Result<()> { let request = self .http .get(self.url( "scrobble", &[("id", id.into()), ("submission", "false".into())], )?) .timeout(Duration::from_secs(5)); Self::send_json("scrobble", request).map(|_| ()) } /// Read a Subsonic reply without exposing the authenticated request URL in errors. fn send_json(endpoint: &str, request: RequestBuilder) -> Result { let response = request .send() .map_err(|_| anyhow::anyhow!("{endpoint}: connection failed or timed out"))?; let status = response.status(); if !status.is_success() { bail!("{endpoint}: HTTP {status}"); } let body: Value = response .json() .map_err(|_| anyhow::anyhow!("{endpoint}: invalid JSON response"))?; envelope(body) } /// Limit cover downloads independently of the slower discovery endpoints. pub fn cover_art(&self, id: &str) -> Result { use std::io::Read; const MAX_BYTES: u64 = 8 * 1024 * 1024; let response = self .http .get(self.url("getCoverArt", &[("id", id.into()), ("size", "320".into())])?) .timeout(Duration::from_secs(15)) .send() .map_err(|_| anyhow::anyhow!("Cover download failed"))?; if !response.status().is_success() { bail!("Cover unavailable (HTTP {})", response.status()); } if response.content_length().is_some_and(|n| n > MAX_BYTES) { bail!("Cover is too large"); } let mut bytes = Vec::new(); response .take(MAX_BYTES + 1) .read_to_end(&mut bytes) .context("Cannot read cover")?; if bytes.len() as u64 > MAX_BYTES { bail!("Cover is too large"); } crate::artwork::decode(&bytes) } /// Only poll acquisition status on servers that advertise Octo's extension. pub fn acquisitions(&self) -> Result>> { let supported = if let Some(supported) = self.acquisition_support.get() { *supported } else { let response = self.call("getOpenSubsonicExtensions", &[])?; let supported = array(&response["openSubsonicExtensions"]) .iter() .any(|e| e["name"] == "octoAcquisitions"); let _ = self.acquisition_support.set(supported); supported }; if !supported { return Ok(None); } let response = self.call("getAcquisitions", &[])?; let acquisitions = array(&response["acquisitions"]["acquisition"]) .iter() .map(|v| serde_json::from_value(v.clone())) .collect::, _>>() .context("Invalid acquisition data")?; Ok(Some(acquisitions)) } /// A completed transfer is only local once the server can return a non-external song. pub fn library_song(&self, id: &str) -> Result> { let response = self.call("getSong", &[("id", id.into())])?; let mut song: Song = serde_json::from_value(response["song"].clone()).context("Invalid library song")?; if song.is_external || song.id.is_empty() { return Ok(None); } song.playback_source = None; Ok(Some(song)) } /// List the same playlists as browsing, retaining explicit editability markers for the UI. pub fn playlist_choices(&self) -> Result> { let response = self.call("getPlaylists", &[])?; let mut choices = parse_playlist_choices(playlist_rows(&response)?); choices.sort_by_key(|p| p.name.to_lowercase()); Ok(choices) } /// Fetch up to four albums at once, keeping server album order and per-track metadata. fn artist_songs(&self, id: &str) -> Result> { let response = self.call("getArtist", &[("id", id.into())])?; let artist = &response["artist"]; let load_album = |album: &Value| -> Result> { let album_id = album["id"] .as_str() .filter(|id| !id.is_empty()) .context("Artist album is missing its ID")?; let mut songs = self.load(&View::Album(album_id.into()))?; for item in &mut songs { if let Item::Song(song) = item { if song.year.is_none_or(|year| year == 0) { song.year = release_year(&album["year"]); } if song.album.is_empty() { song.album = album["name"].as_str().unwrap_or_default().into(); } if song.album_id.as_deref().is_none_or(str::is_empty) { song.album_id = Some(album_id.into()); } if song.artist.is_empty() { song.artist = artist["name"].as_str().unwrap_or_default().into(); song.artist_id = Some(id.into()); } } } Ok(songs) }; let mut tracks = Vec::new(); for albums in array(&artist["album"]).chunks(4) { let batch = std::thread::scope(|scope| -> Result> { let pending: Vec<_> = albums .iter() .map(|album| scope.spawn(|| load_album(album))) .collect(); let mut songs = Vec::new(); for worker in pending { songs.extend(worker.join().map_err(|_| { anyhow::anyhow!("Artist album loading worker failed") })??); } Ok(songs) })?; tracks.extend(batch); } Ok(tracks) } /// Append without replacing existing entries, or create a playlist with its first song atomically. pub fn add_to_playlist(&self, target: &PlaylistTarget, song_id: &str) -> Result<()> { let response = match target { PlaylistTarget::Existing { id, .. } => self.call( "updatePlaylist", &[("playlistId", id.clone()), ("songIdToAdd", song_id.into())], )?, PlaylistTarget::New { name } => self.call( "createPlaylist", &[("name", name.clone()), ("songId", song_id.into())], )?, }; if let Some(skipped) = response.get("octoSkipped").filter(|v| !v.is_null()) { let skipped = skipped .as_array() .context("Invalid playlist skipped-song response")?; if !skipped.is_empty() { if matches!(target, PlaylistTarget::New { .. }) { bail!( "Playlist created, but the server skipped the song. Check the playlist before retrying." ); } bail!("The server skipped this song; it was not added to the playlist."); } } Ok(()) } fn remember_extensions(&self, response: &Value) { let octo = array(&response["openSubsonicExtensions"]).iter().any(|e| { e["name"] .as_str() .is_some_and(|name| name.starts_with("octo")) }); self.octo.store(if octo { 2 } else { 1 }, Ordering::Relaxed); } /// Only Octo has the documented YouTube default; other Subsonic servers stay unknown. fn mark_playback_sources(&self, body: &Value, items: &mut [Item]) { if !items .iter() .any(|item| matches!(item,Item::Song(s) if s.is_external)) { return; } if body["type"] == "octo" { self.octo.store(2, Ordering::Relaxed); } if self.octo.load(Ordering::Relaxed) == 0 && let Ok(v) = self.call("getOpenSubsonicExtensions", &[]) { self.remember_extensions(&v); } apply_playback_source(items, self.octo.load(Ordering::Relaxed) == 2); } pub fn session_key(&self) -> String { format!( "{:x}", md5::compute(format!("{}|{}|{}", self.base, self.username, self.api_key)) ) } /// Match the original client's collection endpoints and preserve server ordering. /// Use library-backed discovery; ownership filtering happens after local-copy resolution. pub fn load_with_mode(&self, view: &View, library_only: bool) -> Result> { if library_only && matches!(view, View::Discover) { let response = self.call("getRandomSongs", &[("size", "100".into())])?; parse_items(&response["randomSongs"]["song"], "song") } else { self.load(view) } } pub fn load(&self, view: &View) -> Result> { let count = || ("count", "100".into()); let (endpoint, params, path, kind): (&str, Vec<(&str, String)>, &[&str], &str) = match view { View::Albums { kind, offset } => ( "getAlbumList2", vec![ ("type", kind.clone()), ("size", "100".into()), ("offset", offset.to_string()), ], &["albumList2", "album"], "album", ), View::Artists => ("getArtists", vec![], &["artists", "index"], "index"), View::Songs { offset } => ( "search3", vec![ ("query", "".into()), ("songCount", "100".into()), ("songOffset", offset.to_string()), ("artistCount", "0".into()), ("albumCount", "0".into()), ], &["searchResult3", "song"], "song", ), View::Playlists => { return Ok(self .playlist_choices()? .into_iter() .map(|p| Item::Playlist { id: p.id, name: p.name, }) .collect()); } View::Genres => ("getGenres", vec![], &["genres", "genre"], "genre"), View::Stations => ( "getInternetRadioStations", vec![], &["internetRadioStations", "internetRadioStation"], "station", ), View::Discover => { let ext = self.call("getOpenSubsonicExtensions", &[]); if let Ok(v) = &ext { self.remember_extensions(v); } let charts = ext.as_ref().ok().is_some_and(|v| { array(&v["openSubsonicExtensions"]) .iter() .any(|e| e["name"] == "octoTopSongs") }); if charts { ( "getTopChart", vec![count()], &["topSongs", "entry"], "chart", ) } else { ( "getRandomSongs", vec![("size", "100".into())], &["randomSongs", "song"], "song", ) } } View::Album(id) => ( "getAlbum", vec![("id", id.clone())], &["album", "song"], "song", ), View::ArtistByName(name) => { let response = self.call( "search3", &[ ("query", name.clone()), ("artistCount", "100".into()), ("albumCount", "0".into()), ("songCount", "0".into()), ], )?; let matches: Vec<_> = array(&response["searchResult3"]["artist"]) .iter() .filter(|artist| { artist["name"].as_str().is_some_and(|candidate| { candidate.trim().eq_ignore_ascii_case(name.trim()) }) }) .filter_map(|artist| artist["id"].as_str().filter(|id| !id.trim().is_empty())) .collect(); return match matches.as_slice() { [id] => self.load(&View::Artist((*id).into())), [] => bail!("No matching artist was returned. Use / to search for the artist."), _ => bail!("Several artists share this name. Use / to choose the artist."), }; } View::Artist(id) => return self.artist_songs(id), View::Playlist(id) => ( "getPlaylist", vec![("id", id.clone())], &["playlist", "entry"], "song", ), View::Genre(g) => ( "getSongsByGenre", vec![("genre", g.clone()), count()], &["songsByGenre", "song"], "song", ), View::Radio(id) => ( "getSimilarSongs2", vec![("id", id.clone()), count()], &["similarSongs2", "song"], "song", ), View::Station(id) => ( "getStationSongs", vec![("id", id.clone()), count()], &["stationSongs", "entry"], "song", ), View::Search(q) => { let v = self.call( "search3", &[ ("query", q.clone()), ("songCount", "100".into()), ("albumCount", "30".into()), ("artistCount", "30".into()), ], )?; let result = &v["searchResult3"]; let mut items = parse_items(&result["song"], "song")?; items.extend(parse_items(&result["album"], "album")?); items.extend(parse_items(&result["artist"], "artist")?); self.mark_playback_sources(&v, &mut items); return Ok(items); } View::History => return Ok(vec![]), View::Home => return Ok(home_items()), View::Queue => return Ok(vec![]), }; let body = self.call(endpoint, ¶ms)?; let value = path.iter().fold(&body, |v, key| &v[*key]); if kind == "index" { let mut items = vec![]; for index in array(value) { items.extend(parse_items(&index["artist"], "artist")?); } Ok(items) } else { let mut items = parse_items(value, kind)?; if matches!(view, View::Album(_)) { for item in &mut items { if let Item::Song(song) = item && song.year.is_none_or(|year| year == 0) { song.year = release_year(&body["album"]["year"]); } } } if kind == "chart" { apply_chart_source(&mut items, body["topSongs"]["source"].as_str()); } self.mark_playback_sources(&body, &mut items); Ok(items) } } } /// Octo proxies external previews through YouTube by default, but can serve a ready local copy. /// The wire API has no chosen-upstream field, so this label must stay explicitly provisional. fn apply_playback_source(items: &mut [Item], octo: bool) { if !octo { return; } for item in items { if let Item::Song(song) = item && song.is_external && song.playback_source.is_none() { song.playback_source = Some("YouTube (default)".into()); } } } /// A chart-level provider fills only missing per-song provenance. fn apply_chart_source(items: &mut [Item], source: Option<&str>) { let Some(source) = source.filter(|s| !s.trim().is_empty()) else { return; }; let source = match source { "lastfm" => "Last.fm", "deezer" => "Deezer", "apple" => "Apple Music", other => other, }; for item in items { if let Item::Song(song) = item && song .octo_suggested_by .as_deref() .is_none_or(|s| s.trim().is_empty()) { song.octo_suggested_by = Some(source.into()); } } } /// Missing lists are valid empty replies; a present list with the wrong shape is a protocol error. fn playlist_rows(response: &Value) -> Result<&Value> { if let Some(container) = response.get("playlists").filter(|v| !v.is_null()) { if !container.is_object() { bail!( "getPlaylists: expected a playlists object, but the server returned another response shape" ); } if let Some(rows) = container.get("playlist").filter(|v| !v.is_null()) && !rows.is_array() { bail!( "getPlaylists: expected a playlist array, but the server returned another response shape" ); } } Ok(&response["playlists"]["playlist"]) } /// Zero or absent release years mean the server has no date for this release. fn release_year(value: &Value) -> Option { value .as_u64() .and_then(|year| u32::try_from(year).ok()) .filter(|year| *year > 0) } fn array(v: &Value) -> &[Value] { v.as_array().map(Vec::as_slice).unwrap_or(&[]) } /// Only expose error codes: server messages may echo signed request URLs. fn envelope(body: Value) -> Result { let response = body .get("subsonic-response") .context("Not a Subsonic JSON response")?; if response["status"] != "ok" { if response["error"]["octoConflict"].as_bool() == Some(true) { bail!("The playlist changed on the server. Refresh it before retrying."); } bail!( "Server rejected request (code {}). Check credentials and endpoint support.", response["error"]["code"].as_u64().unwrap_or(0) ); } Ok(response.clone()) } fn parse_items(value: &Value, kind: &str) -> Result> { if kind == "playlist" { return Ok(parse_playlist_choices(value) .into_iter() .map(|p| Item::Playlist { id: p.id, name: p.name, }) .collect()); } array(value) .iter() .filter(|v| kind != "chart" || v["song"].is_object()) .map(|v| { let text = |key: &str| v[key].as_str().unwrap_or_default().to_owned(); Ok(match kind { "album" => Item::Album { id: text("id"), name: text("name"), artist: text("artist"), cover_art: v["coverArt"].as_str().map(str::to_owned), }, "artist" => Item::Artist { id: text("id"), name: text("name"), }, "station" => Item::Station { id: text("id"), name: text("name"), }, "genre" => Item::Genre(text("value")), "chart" => { return if v["song"].is_object() { Ok(Item::Song( serde_json::from_value(v["song"].clone()) .context("Invalid chart song")?, )) } else { bail!("Chart entry has no playable song") }; } _ => Item::Song( serde_json::from_value::(v.clone()).context("Invalid song data")?, ), }) }) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn now_playing_sends_an_authenticated_notification() { use std::{ io::{BufRead, BufReader, Write}, net::TcpListener, }; let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); let server = std::thread::spawn(move || { let (mut stream, _) = listener.accept().unwrap(); stream .set_read_timeout(Some(Duration::from_secs(5))) .unwrap(); let mut request = String::new(); let mut reader = BufReader::new(&mut stream); reader.read_line(&mut request).unwrap(); let mut parts = request.split_whitespace(); assert_eq!(parts.next(), Some("GET")); let url = Url::parse(&format!("http://{address}{}", parts.next().unwrap())).unwrap(); assert_eq!(url.path(), "/music/rest/scrobble"); let params = url .query_pairs() .collect::>(); assert_eq!(params["id"], "track + 42"); assert_eq!(params["submission"], "false"); assert_eq!(params["c"], "octo-tui"); assert_eq!(params["apiKey"], "test-key"); loop { request.clear(); if reader.read_line(&mut request).unwrap() == 0 || request == "\r\n" { break; } } let body = r#"{"subsonic-response":{"status":"ok"}}"#; write!( stream, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.len(), body ) .unwrap(); }); let api = Api::new(Config { server: format!("http://{address}/music"), api_key: "test-key".into(), ..Default::default() }) .unwrap(); api.report_now_playing("track + 42").unwrap(); server.join().unwrap(); } #[test] fn playlist_errors_distinguish_empty_malformed_and_conflicting_responses() { for response in [ serde_json::json!({}), serde_json::json!({"playlists":null}), serde_json::json!({"playlists":{"playlist":[]}}), ] { assert!(parse_playlist_choices(playlist_rows(&response).unwrap()).is_empty()); } for response in [ serde_json::json!({"playlists":[]}), serde_json::json!({"playlists":{"playlist":{}}}), ] { assert!(playlist_rows(&response).is_err()); } let error = envelope(serde_json::json!({"subsonic-response":{"status":"failed","error":{"octoConflict":true,"message":"private"}}})).unwrap_err().to_string(); assert!(error.contains("playlist changed")); assert!(!error.contains("private")); } #[test] fn successful_http_replies_with_skipped_songs_do_not_report_playlist_success() { use std::{ io::{Read, Write}, net::TcpListener, }; let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); let server = std::thread::spawn(move || { for _ in 0..2 { let (mut stream, _) = listener.accept().unwrap(); stream .set_read_timeout(Some(Duration::from_secs(5))) .unwrap(); let mut request = Vec::new(); let mut byte = [0]; while !request.ends_with(b"\r\n\r\n") { stream.read_exact(&mut byte).unwrap(); request.push(byte[0]); } let body = r#"{"subsonic-response":{"status":"ok","octoSkipped":["song"]}}"#; write!( stream, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.len(), body ) .unwrap(); } }); let api = Api::new(Config { server: format!("http://{address}"), ..Default::default() }) .unwrap(); let existing = api .add_to_playlist( &PlaylistTarget::Existing { id: "list".into(), name: "List".into(), }, "song", ) .unwrap_err() .to_string(); assert!(existing.contains("not added")); let new = api .add_to_playlist(&PlaylistTarget::New { name: "New".into() }, "song") .unwrap_err() .to_string(); assert!(new.contains("Playlist created")); server.join().unwrap(); } #[test] fn artist_albums_load_concurrently_in_order_and_fail_without_partial_results() { use serde_json::json; use std::{ io::{BufRead, BufReader, Write}, net::{TcpListener, TcpStream}, time::Instant, }; fn request(listener: &TcpListener) -> (TcpStream, Url) { let deadline = Instant::now() + Duration::from_secs(3); let (stream, _) = loop { match listener.accept() { Ok(connection) => break connection, Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { assert!( Instant::now() < deadline, "Album requests did not arrive concurrently" ); std::thread::sleep(Duration::from_millis(5)); } Err(error) => panic!("Accept failed: {error}"), } }; stream .set_read_timeout(Some(Duration::from_secs(3))) .unwrap(); let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut first = String::new(); reader.read_line(&mut first).unwrap(); let url = Url::parse(&format!( "http://localhost{}", first.split_whitespace().nth(1).unwrap() )) .unwrap(); loop { let mut line = String::new(); reader.read_line(&mut line).unwrap(); if line == "\r\n" || line.is_empty() { break; } } (stream, url) } fn respond(mut stream: TcpStream, mut payload: Value) { if payload.get("status").is_none() { payload["status"] = json!("ok"); } let body = json!({"subsonic-response":payload}).to_string(); write!( stream, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.len(), body ) .unwrap(); } let listener = TcpListener::bind("127.0.0.1:0").unwrap(); listener.set_nonblocking(true).unwrap(); let address = listener.local_addr().unwrap(); let server = std::thread::spawn(move || { for fail in [false, true] { let (stream, url) = request(&listener); assert_eq!(url.path(), "/rest/getArtist"); let albums: Vec<_> = (0..9) .map(|i| json!({"id":i.to_string(),"name":format!("Album {i}")})) .collect(); respond(stream, json!({"artist":{"name":"Artist","album":albums}})); for start in [0, 4, 8] { let count = (9 - start).min(4); // Hold every response until the whole batch is in flight. let mut pending = Vec::new(); for _ in 0..count { let (stream, url) = request(&listener); assert_eq!(url.path(), "/rest/getAlbum"); let index: usize = url .query_pairs() .find(|(k, _)| k == "id") .unwrap() .1 .parse() .unwrap(); assert!((start..start + count).contains(&index)); pending.push((index, stream)); } pending.sort_by_key(|(index, _)| *index); for (index, stream) in pending.into_iter().rev() { let payload = if fail && index == 8 { json!({"status":"failed","error":{"code":70}}) } else if index == 8 { json!({"album":{"song":[]}}) } else { json!({"album":{"song":[{"id":format!("{index}-a")},{"id":format!("{index}-b")}]}}) }; respond(stream, payload); } } } }); let api = Api::new(Config { server: format!("http://{address}"), ..Default::default() }) .unwrap(); let tracks = api.load(&View::Artist("artist".into())).unwrap(); let songs: Vec<_> = tracks .iter() .map(|item| match item { Item::Song(song) => song, _ => panic!("Expected song"), }) .collect(); let expected: Vec<_> = (0..8) .flat_map(|i| [format!("{i}-a"), format!("{i}-b")]) .collect(); assert_eq!( songs.iter().map(|s| s.id.clone()).collect::>(), expected ); for (i, song) in songs.iter().enumerate() { assert_eq!(song.album, format!("Album {}", i / 2)); } assert!(api.load(&View::Artist("artist".into())).is_err()); server.join().unwrap(); } #[test] fn artist_name_lookup_opens_exact_artist_and_rejects_ambiguous_or_missing_matches() { use serde_json::json; use std::{ io::{BufRead, BufReader, Write}, net::TcpListener, }; let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); let server = std::thread::spawn(move || { for (endpoint, mut payload) in [ ( "search3", json!({"searchResult3":{"artist":[{"id":"wrong","name":"Artist Tribute"},{"id":"right","name":"ARTIST"}]}}), ), ( "getArtist", json!({"artist":{"name":"Artist","album":[{"id":"album","name":"Record","year":1999},{"id":"second","name":"Second","year":2005},{"id":"empty","name":"Empty"}]}}), ), ( "getAlbum", json!({"album":{"year":2020,"song":[{"id":"first","title":"First","year":null},{"id":"second-track","title":"Next","album":"Explicit album","artist":"Guest","artistId":"guest","year":2001}]}}), ), ( "getAlbum", json!({"album":{"song":[{"id":"last","title":"Last","year":0}]}}), ), ("getAlbum", json!({"album":{"song":[]}})), ( "search3", json!({"searchResult3":{"artist":[{"id":"a","name":"Artist"},{"id":"b","name":"Artist"}]}}), ), ( "search3", json!({"searchResult3":{"artist":[{"id":"wrong","name":"Artist Tribute"}]}}), ), ] { let (mut stream, _) = listener.accept().unwrap(); stream .set_read_timeout(Some(Duration::from_secs(5))) .unwrap(); let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut first = String::new(); reader.read_line(&mut first).unwrap(); let url = Url::parse(&format!( "http://localhost{}", first.split_whitespace().nth(1).unwrap() )) .unwrap(); assert_eq!(url.path(), format!("/rest/{endpoint}")); if endpoint == "getArtist" { assert!(url.query_pairs().any(|(k, v)| k == "id" && v == "right")); } else if endpoint == "getAlbum" { let album = url .query_pairs() .find(|(k, _)| k == "id") .unwrap() .1 .into_owned(); payload = match album.as_str() { "album" => { serde_json::json!({"album":{"year":2020,"song":[{"id":"first","title":"First","year":null},{"id":"second-track","title":"Next","album":"Explicit album","artist":"Guest","artistId":"guest","year":2001}]}}) } "second" => { serde_json::json!({"album":{"song":[{"id":"last","title":"Last","year":0}]}}) } "empty" => serde_json::json!({"album":{"song":[]}}), _ => panic!("Unexpected album request"), }; } else { assert!( url.query_pairs() .any(|(k, v)| k == "query" && v == "Artist") ); assert!(url.query_pairs().any(|(k, v)| k == "songCount" && v == "0")); } loop { let mut line = String::new(); reader.read_line(&mut line).unwrap(); if line == "\r\n" || line.is_empty() { break; } } let mut payload = payload; payload["status"] = json!("ok"); let body = json!({"subsonic-response":payload}).to_string(); write!( stream, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.len(), body ) .unwrap(); } }); let api = Api::new(Config { server: format!("http://{address}"), ..Default::default() }) .unwrap(); let view = View::ArtistByName("Artist".into()); let tracks = api.load(&view).unwrap(); let songs: Vec<_> = tracks .iter() .map(|item| match item { Item::Song(song) => song, _ => panic!("expected flattened songs"), }) .collect(); assert_eq!( songs .iter() .map(|song| song.id.as_str()) .collect::>(), ["first", "second-track", "last"] ); assert_eq!(songs[0].year, Some(2020)); assert_eq!(songs[1].year, Some(2001)); assert_eq!(songs[2].year, Some(2005)); assert_eq!(songs[0].album, "Record"); assert_eq!(songs[0].album_id.as_deref(), Some("album")); assert_eq!(songs[0].artist, "Artist"); assert_eq!(songs[1].album, "Explicit album"); assert_eq!(songs[1].artist, "Guest"); assert_eq!(songs[1].artist_id.as_deref(), Some("guest")); assert_eq!(songs[2].album, "Second"); assert!( api.load(&view) .unwrap_err() .to_string() .contains("Several artists") ); assert!( api.load(&view) .unwrap_err() .to_string() .contains("No matching artist") ); server.join().unwrap(); } #[test] fn library_discovery_requests_random_library_songs_without_online_charts() { use std::{ io::{BufRead, BufReader, Write}, net::TcpListener, }; let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); let server = std::thread::spawn(move || { let (mut stream, _) = listener.accept().unwrap(); stream .set_read_timeout(Some(Duration::from_secs(3))) .unwrap(); let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut first = String::new(); reader.read_line(&mut first).unwrap(); let url = Url::parse(&format!( "http://localhost{}", first.split_whitespace().nth(1).unwrap() )) .unwrap(); assert_eq!(url.path(), "/rest/getRandomSongs"); loop { let mut line = String::new(); reader.read_line(&mut line).unwrap(); if line == "\r\n" || line.is_empty() { break; } } let body = r#"{"subsonic-response":{"status":"ok","randomSongs":{"song":[{"id":"local","title":"Library song"}]}}}"#; write!( stream, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.len(), body ) .unwrap(); }); let api = Api::new(Config { server: format!("http://{address}"), ..Default::default() }) .unwrap(); let items = api.load_with_mode(&View::Discover, true).unwrap(); assert!(matches!(&items[..],[Item::Song(song)] if song.id == "local" && !song.is_external)); server.join().unwrap(); } #[test] fn original_player_fixture_parses() { let v = envelope(serde_json::from_str(include_str!("../tests/fixtures/search3.json")).unwrap()) .unwrap(); let items = parse_items(&v["searchResult3"]["song"], "song").unwrap(); assert_eq!(items.len(), 2); assert_eq!(items[0].title(), "Nightcall"); } #[test] fn charts_keep_playable_external_and_library_songs() { let entries = serde_json::json!([ {"rank":1,"song":{"id":"local","title":"Owned"}}, {"rank":2,"song":{"id":"online","title":"Found","isExternal":true}}, {"rank":3,"song":null} ]); let items = parse_items(&entries, "chart").unwrap(); assert_eq!(items.len(), 2); assert_eq!(items[0].label(), "LIBRARY"); assert_eq!(items[1].label(), "DISCOVER"); } #[test] fn provenance_preserves_individual_source_and_uses_chart_fallback() { let mut items = parse_items( &serde_json::json!([ {"id":"radio","isExternal":true,"octoSuggestedBy":"Sounds alike"}, {"id":"chart","isExternal":true}, {"id":"unknown","isExternal":true} ]), "song", ) .unwrap(); assert_eq!(items[2].recommendation_source(), "Unknown"); apply_chart_source(&mut items, Some("lastfm")); assert_eq!(items[0].recommendation_source(), "Sounds alike"); assert_eq!(items[1].recommendation_source(), "Last.fm"); let roundtrip: Song = serde_json::from_value( serde_json::to_value(match &items[0] { Item::Song(s) => s, _ => unreachable!(), }) .unwrap(), ) .unwrap(); assert_eq!(roundtrip.octo_suggested_by.as_deref(), Some("Sounds alike")); } #[test] fn playback_source_never_uses_recommendation_provider() { let mut items = parse_items( &serde_json::json!([ {"id":"local","octoSuggestedBy":"Sounds alike"}, {"id":"outside","isExternal":true,"octoSuggestedBy":"Last.fm"} ]), "song", ) .unwrap(); assert_eq!(items[0].playback_source(), "Library"); assert_eq!(items[1].playback_source(), "Unknown"); apply_playback_source(&mut items, true); assert_eq!(items[1].playback_source(), "YouTube (default)"); assert_eq!(items[1].recommendation_source(), "Last.fm"); } #[test] fn home_history_shelves_request_server_album_order_and_page() { use std::{ io::{BufRead, BufReader, Write}, net::TcpListener, }; let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); let server = std::thread::spawn(move || { for kind in ["recent", "newest", "frequent", "random", "highest"] { let (mut stream, _) = listener.accept().unwrap(); stream .set_read_timeout(Some(Duration::from_secs(5))) .unwrap(); let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut first = String::new(); reader.read_line(&mut first).unwrap(); let target = first.split_whitespace().nth(1).unwrap(); let url = Url::parse(&format!("http://localhost{target}")).unwrap(); let params: std::collections::HashMap<_, _> = url.query_pairs().collect(); assert_eq!(url.path(), "/rest/getAlbumList2"); assert_eq!(params["type"], kind); assert_eq!(params["size"], "100"); assert_eq!(params["offset"], "100"); loop { let mut line = String::new(); reader.read_line(&mut line).unwrap(); if line == "\r\n" || line.is_empty() { break; } } let body=serde_json::json!({"subsonic-response":{"status":"ok","albumList2":{"album":[{"id":kind,"name":format!("{kind} album"),"artist":"Test artist"}]}}}).to_string(); write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",body.len(),body).unwrap(); } }); let api = Api::new(Config { server: format!("http://{address}"), api_key: "test-key".into(), ..Default::default() }) .unwrap(); for section in crate::model::HomeSection::ALL.into_iter().take(5) { let mut view = section.view(); let View::Albums { offset, kind } = &mut view else { unreachable!() }; *offset = 100; let title = format!("{kind} album"); let items = api.load(&view).unwrap(); assert_eq!(items[0].title(), title); } server.join().unwrap(); } #[test] fn acquisition_poll_checks_extension_once_and_parses_server_progress() { use std::{ io::{BufRead, BufReader, Write}, net::TcpListener, }; let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); let server = std::thread::spawn(move || { for endpoint in [ "getOpenSubsonicExtensions", "getAcquisitions", "getAcquisitions", ] { let (mut stream, _) = listener.accept().unwrap(); stream .set_read_timeout(Some(Duration::from_secs(5))) .unwrap(); let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut first = String::new(); reader.read_line(&mut first).unwrap(); assert!(first.starts_with(&format!("GET /rest/{endpoint}?"))); loop { let mut line = String::new(); reader.read_line(&mut line).unwrap(); if line == "\r\n" || line.is_empty() { break; } } let body = if endpoint == "getOpenSubsonicExtensions" { r#"{"subsonic-response":{"status":"ok","openSubsonicExtensions":[{"name":"octoAcquisitions","versions":[1]}]}}"# } else { include_str!("../tests/fixtures/acquisitions.json") }; write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",body.len(),body).unwrap(); } }); let api = Api::new(Config { server: format!("http://{address}"), api_key: "test-key".into(), ..Default::default() }) .unwrap(); for _ in 0..2 { let rows = api.acquisitions().unwrap().unwrap(); assert_eq!(rows[0].state, "downloading"); assert_eq!(rows[0].progress, Some(0.42)); assert_eq!(rows[0].source.as_deref(), Some("Soulseek")); } server.join().unwrap(); } #[test] fn playlist_browse_and_picker_parse_the_same_server_rows() { let rows = serde_json::json!([ {"id":7,"name":"My playlist","readonly":null}, {"id":"station","name":"Station","readonly":true}, {"id":"other","name":"Other playlist","readonly":"false"} ]); let choices = parse_playlist_choices(&rows); let browse = parse_items(&rows, "playlist").unwrap(); assert_eq!(choices.len(), 3); assert_eq!(browse.len(), choices.len()); for (choice, item) in choices.iter().zip(&browse) { assert_eq!(choice.name, item.title()); assert!(matches!(item,Item::Playlist {id,..} if id==&choice.id)); } assert!(!choices[0].readonly); } #[test] fn playlist_picker_keeps_readonly_visible_and_writes_only_the_selected_song() { use std::{ io::{BufRead, BufReader, Write}, net::TcpListener, }; let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); let server = std::thread::spawn(move || { for endpoint in ["getPlaylists", "updatePlaylist", "createPlaylist"] { let (mut stream, _) = listener.accept().unwrap(); stream .set_read_timeout(Some(Duration::from_secs(5))) .unwrap(); let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut first = String::new(); reader.read_line(&mut first).unwrap(); let target = first.split_whitespace().nth(1).unwrap(); let url = Url::parse(&format!("http://localhost{target}")).unwrap(); assert_eq!(url.path(), format!("/rest/{endpoint}")); let params: std::collections::HashMap<_, _> = url.query_pairs().collect(); if endpoint == "updatePlaylist" { assert_eq!(params["playlistId"], "editable"); assert_eq!(params["songIdToAdd"], "song & 1"); assert!(!params.contains_key("songId")); } if endpoint == "createPlaylist" { assert_eq!(params["name"], "Café & music"); assert_eq!(params["songId"], "song & 1"); assert!(!params.contains_key("playlistId")); } loop { let mut line = String::new(); reader.read_line(&mut line).unwrap(); if line == "\r\n" || line.is_empty() { break; } } let body = if endpoint == "getPlaylists" { r#"{"subsonic-response":{"status":"ok","playlists":{"playlist":[{"id":"station","name":"Station","readonly":true},{"id":"editable","name":"Evening","readonly":null},{"id":"first","name":"Afternoon"}]}}}"# } else { r#"{"subsonic-response":{"status":"ok"}}"# }; write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",body.len(),body).unwrap(); } }); let api = Api::new(Config { server: format!("http://{address}"), api_key: "test-key".into(), ..Default::default() }) .unwrap(); let choices = api.playlist_choices().unwrap(); assert_eq!(choices.len(), 3); assert_eq!(choices[0].name, "Afternoon"); assert!(choices[2].readonly); api.add_to_playlist( &PlaylistTarget::Existing { id: "editable".into(), name: "Evening".into(), }, "song & 1", ) .unwrap(); api.add_to_playlist( &PlaylistTarget::New { name: "Café & music".into(), }, "song & 1", ) .unwrap(); server.join().unwrap(); } #[test] fn library_lookup_confirms_indexed_metadata_before_switching_ids() { use std::{ io::{BufRead, BufReader, Write}, net::TcpListener, }; let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); let server = std::thread::spawn(move || { for (id, external) in [("indexed", false), ("waiting", true)] { let (mut stream, _) = listener.accept().unwrap(); stream .set_read_timeout(Some(Duration::from_secs(5))) .unwrap(); let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut first = String::new(); reader.read_line(&mut first).unwrap(); let url = Url::parse(&format!( "http://localhost{}", first.split_whitespace().nth(1).unwrap() )) .unwrap(); assert_eq!(url.path(), "/rest/getSong"); assert!(url.query_pairs().any(|(k, v)| k == "id" && v == id)); loop { let mut line = String::new(); reader.read_line(&mut line).unwrap(); if line == "\r\n" || line.is_empty() { break; } } let body=serde_json::json!({"subsonic-response":{"status":"ok","song":{"id":id,"title":"Track","isExternal":external,"playbackSource":"YouTube (default)"}}}).to_string(); write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",body.len(),body).unwrap(); } }); let api = Api::new(Config { server: format!("http://{address}"), api_key: "test-key".into(), ..Default::default() }) .unwrap(); let song = api.library_song("indexed").unwrap().unwrap(); assert_eq!(song.id, "indexed"); assert!(!song.is_external); assert!(song.playback_source.is_none()); assert!(api.library_song("waiting").unwrap().is_none()); server.join().unwrap(); } #[test] fn discovery_uses_octos_nested_chart_response() { use std::{ io::{BufRead, BufReader, Write}, net::TcpListener, }; let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let address = listener.local_addr().unwrap(); let server = std::thread::spawn(move || { for endpoint in ["getOpenSubsonicExtensions", "getTopChart"] { let (mut stream, _) = listener.accept().unwrap(); stream .set_read_timeout(Some(Duration::from_secs(5))) .unwrap(); let mut reader = BufReader::new(stream.try_clone().unwrap()); let mut request = String::new(); reader.read_line(&mut request).unwrap(); assert!(request.starts_with(&format!("GET /music/rest/{endpoint}?"))); loop { let mut line = String::new(); reader.read_line(&mut line).unwrap(); if line == "\r\n" || line.is_empty() { break; } } let body = if endpoint == "getTopChart" { r#"{"subsonic-response":{"status":"ok","topSongs":{"source":"lastfm","entry":[{"song":{"id":"found","title":"New music","isExternal":true}}]}}}"# } else { r#"{"subsonic-response":{"status":"ok","openSubsonicExtensions":[{"name":"octoTopSongs","versions":[1]}]}}"# }; write!(stream,"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",body.len(),body).unwrap(); } }); let api = Api::new(Config { server: format!("http://{address}/music"), api_key: "test-key".into(), ..Default::default() }) .unwrap(); let items = api.load(&View::Discover).unwrap(); assert_eq!(items.len(), 1); assert_eq!(items[0].title(), "New music"); assert_eq!(items[0].recommendation_source(), "Last.fm"); assert_eq!(items[0].label(), "DISCOVER"); server.join().unwrap(); } #[test] fn error_does_not_echo_secrets() { let err = envelope(serde_json::json!({"subsonic-response":{"status":"failed","error":{"code":40,"message":"secret"}}})).unwrap_err(); assert!(!err.to_string().contains("secret")); assert!(envelope(serde_json::json!({})).is_err()); } #[test] fn auth_and_subpath_are_preserved() { let api = Api::new(Config { server: "https://example.com/music".into(), username: "listener".into(), password: "private".into(), ..Default::default() }) .unwrap(); let url = api.url("search3", &[("query", "a & b".into())]).unwrap(); assert_eq!(url.path(), "/music/rest/search3"); let p: std::collections::HashMap<_, _> = url.query_pairs().collect(); assert_eq!(p["query"], "a & b"); assert_eq!( p["t"], format!("{:x}", md5::compute(format!("private{}", p["s"]))) ); assert_ne!(url, api.url("search3", &[]).unwrap()); } }