From 10710c1755c11e57dc555de350cfe9cc304a0589 Mon Sep 17 00:00:00 2001 From: Ansho Rei Date: Thu, 5 Nov 2026 18:39:03 +0100 Subject: [PATCH] feat: read a song's album id and fetch random songs from the server Album shuffle groups tracks by album id, since the album name alone merges different albums with the same title. Library shuffle tops up the queue with getRandomSongs. --- src/subsonic.rs | 79 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/src/subsonic.rs b/src/subsonic.rs index acd02a9..2fb6543 100644 --- a/src/subsonic.rs +++ b/src/subsonic.rs @@ -265,6 +265,27 @@ impl Client { Ok(r.result) } + /// Up to `size` random songs from the whole library. Servers cap `size` + /// at 500. + #[cfg_attr( + not(test), + expect(dead_code, reason = "library shuffle in 7ff72a1 is its first caller") + )] + pub async fn random_songs(&self, size: u32) -> Result> { + #[derive(Deserialize)] + struct R { + #[serde(rename = "randomSongs", default)] + list: Songs, + } + #[derive(Deserialize, Default)] + struct Songs { + #[serde(default)] + song: Vec, + } + let r: R = self.call("getRandomSongs", &[("size", size.to_string())]).await?; + Ok(r.list.song) + } + pub async fn scrobble(&self, id: &str, submission: bool) -> Result<()> { let _: serde_json::Value = self .call("scrobble", &[("id", id.into()), ("submission", submission.to_string())]) @@ -426,6 +447,9 @@ pub struct Song { pub artist: Option, #[serde(default)] pub album: Option, + /// None in queues saved before it was kept, and from servers that leave it out. + #[serde(default, deserialize_with = "de_opt_id")] + pub album_id: Option, #[serde(default, deserialize_with = "de_opt_id")] pub cover_art: Option, #[serde(default)] @@ -489,6 +513,56 @@ mod tests { let a: Album = serde_json::from_str(r#"{"id": 42, "name": "X", "coverArt": 7}"#).unwrap(); assert_eq!(a.id, "42"); assert_eq!(a.cover_art.as_deref(), Some("7")); + let s: Song = serde_json::from_str(r#"{"id": 1, "albumId": 42}"#).unwrap(); + assert_eq!(s.album_id.as_deref(), Some("42")); + let s: Song = serde_json::from_str(r#"{"id": 1}"#).unwrap(); + assert_eq!(s.album_id, None); + } + + /// A loopback HTTP server that answers every request with `body` and + /// sends each request line back. + fn fake_server(body: &'static str) -> (String, std::sync::mpsc::Receiver) { + use std::io::{BufRead, BufReader, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let mut line = String::new(); + let _ = BufReader::new(stream.try_clone().unwrap()).read_line(&mut line); + let _ = tx.send(line); + let _ = write!( + stream, + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ); + } + }); + (format!("http://{addr}"), rx) + } + + #[tokio::test] + async fn random_songs_asks_for_the_size_and_reads_the_songs() { + let (base, requests) = fake_server( + r#"{"subsonic-response":{"status":"ok","randomSongs":{"song":[ + {"id":"s1","title":"One","albumId":"al-1"},{"id":"s2","title":"Two"}]}}}"#, + ); + let c = Client::new(&base, "u", Auth::Password("sesame".into())); + let songs = c.random_songs(50).await.unwrap(); + let ids: Vec<_> = songs.iter().map(|s| s.id.as_str()).collect(); + assert_eq!(ids, ["s1", "s2"]); + assert_eq!(songs[0].album_id.as_deref(), Some("al-1")); + let line = requests.recv().unwrap(); + assert!(line.contains("/rest/getRandomSongs?"), "{line}"); + assert!(line.contains("size=50"), "{line}"); + } + + #[tokio::test] + async fn random_songs_from_an_empty_library_is_empty() { + let (base, _) = fake_server(r#"{"subsonic-response":{"status":"ok","randomSongs":{}}}"#); + let c = Client::new(&base, "u", Auth::Password("sesame".into())); + assert!(c.random_songs(50).await.unwrap().is_empty()); } /// Exercises every endpoint against a real server: @@ -514,6 +588,7 @@ mod tests { assert!(!albums.is_empty(), "no albums"); let album = c.album(&albums[0].id).await.unwrap(); assert!(!album.song.is_empty(), "album has no songs"); + assert_eq!(album.song[0].album_id.as_deref(), Some(albums[0].id.as_str())); println!( "album: {} by {:?}, {} songs", album.name, @@ -537,6 +612,10 @@ mod tests { println!("playlist: {} with {} entries", p.name, p.entry.len()); } + let random = c.random_songs(20).await.unwrap(); + assert!(!random.is_empty(), "no random songs"); + println!("random: {} songs", random.len()); + let found = c.search(&album.name).await.unwrap(); assert!(!found.album.is_empty(), "search found nothing for {}", album.name);