Browses a Subsonic library and plays it through mpv, driven by a gamepad or keyboard. The UI scales from the window's physical height rather than the compositor's scale factor, so it keeps its proportions on a Steam Deck and on a 4K TV, where other players open small or scale badly.
485 lines
15 KiB
Rust
485 lines
15 KiB
Rust
//! Minimal OpenSubsonic client covering what the browser and player need.
|
|
|
|
use std::hash::{BuildHasher, RandomState};
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
|
|
|
use anyhow::{Context, Result, anyhow, bail};
|
|
use serde::Deserialize;
|
|
use serde::de::{DeserializeOwned, Deserializer};
|
|
|
|
const API_VERSION: &str = "1.16.1";
|
|
const CLIENT_NAME: &str = "remus";
|
|
|
|
#[derive(Clone)]
|
|
pub struct Client {
|
|
http: reqwest::Client,
|
|
base: String,
|
|
user: String,
|
|
salt: String,
|
|
token: String,
|
|
}
|
|
|
|
impl Client {
|
|
pub fn new(base: &str, user: &str, salt: &str, token: &str) -> Self {
|
|
let http = reqwest::Client::builder()
|
|
.user_agent(concat!("remus/", env!("CARGO_PKG_VERSION")))
|
|
.timeout(std::time::Duration::from_secs(30))
|
|
.build()
|
|
.expect("http client");
|
|
Client {
|
|
http,
|
|
base: normalize_base(base),
|
|
user: user.to_string(),
|
|
salt: salt.to_string(),
|
|
token: token.to_string(),
|
|
}
|
|
}
|
|
|
|
/// Derives a token from the password so the password itself is never stored.
|
|
/// The token is still password-equivalent for this server.
|
|
pub fn from_password(base: &str, user: &str, password: &str) -> Self {
|
|
let salt = random_salt();
|
|
let token = format!("{:x}", md5::compute(format!("{password}{salt}")));
|
|
Client::new(base, user, &salt, &token)
|
|
}
|
|
|
|
pub fn base(&self) -> &str {
|
|
&self.base
|
|
}
|
|
pub fn user(&self) -> &str {
|
|
&self.user
|
|
}
|
|
pub fn salt(&self) -> &str {
|
|
&self.salt
|
|
}
|
|
pub fn token(&self) -> &str {
|
|
&self.token
|
|
}
|
|
|
|
fn endpoint_url(&self, endpoint: &str, params: &[(&str, String)]) -> Result<reqwest::Url> {
|
|
let mut all: Vec<(&str, String)> = vec![
|
|
("u", self.user.clone()),
|
|
("t", self.token.clone()),
|
|
("s", self.salt.clone()),
|
|
("v", API_VERSION.to_string()),
|
|
("c", CLIENT_NAME.to_string()),
|
|
("f", "json".to_string()),
|
|
];
|
|
all.extend(params.iter().cloned());
|
|
reqwest::Url::parse_with_params(&format!("{}/rest/{endpoint}", self.base), &all)
|
|
.with_context(|| format!("invalid server url {}", self.base))
|
|
}
|
|
|
|
async fn call<T: DeserializeOwned>(&self, endpoint: &str, params: &[(&str, String)]) -> Result<T> {
|
|
let url = self.endpoint_url(endpoint, params)?;
|
|
let resp = self
|
|
.http
|
|
.get(url)
|
|
.send()
|
|
.await
|
|
.map_err(redact)
|
|
.with_context(|| format!("{endpoint} request failed"))?;
|
|
let status = resp.status();
|
|
if !status.is_success() {
|
|
bail!("{endpoint}: server returned {status}");
|
|
}
|
|
let mut body: serde_json::Value = resp
|
|
.json()
|
|
.await
|
|
.map_err(redact)
|
|
.with_context(|| format!("{endpoint}: invalid json"))?;
|
|
let inner = body
|
|
.get_mut("subsonic-response")
|
|
.map(serde_json::Value::take)
|
|
.ok_or_else(|| anyhow!("{endpoint}: not a subsonic response"))?;
|
|
if inner.get("status").and_then(|s| s.as_str()) != Some("ok") {
|
|
let msg = inner
|
|
.pointer("/error/message")
|
|
.and_then(|m| m.as_str())
|
|
.unwrap_or("unknown error");
|
|
bail!("{msg}");
|
|
}
|
|
serde_json::from_value(inner).with_context(|| format!("{endpoint}: unexpected response shape"))
|
|
}
|
|
|
|
pub async fn ping(&self) -> Result<()> {
|
|
let _: serde_json::Value = self.call("ping", &[]).await?;
|
|
Ok(())
|
|
}
|
|
|
|
/// `kind` is a getAlbumList2 type: newest, random, alphabeticalByName, frequent, recent...
|
|
pub async fn album_list(&self, kind: &str, size: u32, offset: u32) -> Result<Vec<Album>> {
|
|
#[derive(Deserialize)]
|
|
struct R {
|
|
#[serde(rename = "albumList2", default)]
|
|
list: AlbumList,
|
|
}
|
|
#[derive(Deserialize, Default)]
|
|
struct AlbumList {
|
|
#[serde(default)]
|
|
album: Vec<Album>,
|
|
}
|
|
let r: R = self
|
|
.call(
|
|
"getAlbumList2",
|
|
&[
|
|
("type", kind.into()),
|
|
("size", size.to_string()),
|
|
("offset", offset.to_string()),
|
|
],
|
|
)
|
|
.await?;
|
|
Ok(r.list.album)
|
|
}
|
|
|
|
pub async fn artists(&self) -> Result<Vec<Artist>> {
|
|
#[derive(Deserialize)]
|
|
struct R {
|
|
#[serde(default)]
|
|
artists: Indexes,
|
|
}
|
|
#[derive(Deserialize, Default)]
|
|
struct Indexes {
|
|
#[serde(default)]
|
|
index: Vec<Index>,
|
|
}
|
|
#[derive(Deserialize)]
|
|
struct Index {
|
|
#[serde(default)]
|
|
artist: Vec<Artist>,
|
|
}
|
|
let r: R = self.call("getArtists", &[]).await?;
|
|
Ok(r.artists.index.into_iter().flat_map(|i| i.artist).collect())
|
|
}
|
|
|
|
pub async fn artist(&self, id: &str) -> Result<ArtistDetail> {
|
|
#[derive(Deserialize)]
|
|
struct R {
|
|
artist: ArtistDetail,
|
|
}
|
|
let r: R = self.call("getArtist", &[("id", id.into())]).await?;
|
|
Ok(r.artist)
|
|
}
|
|
|
|
pub async fn album(&self, id: &str) -> Result<AlbumDetail> {
|
|
#[derive(Deserialize)]
|
|
struct R {
|
|
album: AlbumDetail,
|
|
}
|
|
let r: R = self.call("getAlbum", &[("id", id.into())]).await?;
|
|
Ok(r.album)
|
|
}
|
|
|
|
pub async fn playlists(&self) -> Result<Vec<Playlist>> {
|
|
#[derive(Deserialize)]
|
|
struct R {
|
|
#[serde(default)]
|
|
playlists: Lists,
|
|
}
|
|
#[derive(Deserialize, Default)]
|
|
struct Lists {
|
|
#[serde(default)]
|
|
playlist: Vec<Playlist>,
|
|
}
|
|
let r: R = self.call("getPlaylists", &[]).await?;
|
|
Ok(r.playlists.playlist)
|
|
}
|
|
|
|
pub async fn playlist(&self, id: &str) -> Result<PlaylistDetail> {
|
|
#[derive(Deserialize)]
|
|
struct R {
|
|
playlist: PlaylistDetail,
|
|
}
|
|
let r: R = self.call("getPlaylist", &[("id", id.into())]).await?;
|
|
Ok(r.playlist)
|
|
}
|
|
|
|
pub async fn search(&self, query: &str) -> Result<SearchResult> {
|
|
#[derive(Deserialize)]
|
|
struct R {
|
|
#[serde(rename = "searchResult3", default)]
|
|
result: SearchResult,
|
|
}
|
|
let r: R = self
|
|
.call(
|
|
"search3",
|
|
&[
|
|
("query", query.into()),
|
|
("artistCount", "20".into()),
|
|
("albumCount", "40".into()),
|
|
("songCount", "80".into()),
|
|
],
|
|
)
|
|
.await?;
|
|
Ok(r.result)
|
|
}
|
|
|
|
pub async fn scrobble(&self, id: &str, submission: bool) -> Result<()> {
|
|
let _: serde_json::Value = self
|
|
.call("scrobble", &[("id", id.into()), ("submission", submission.to_string())])
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn cover_art(&self, id: &str, size: u32) -> Result<Vec<u8>> {
|
|
let url = self.endpoint_url("getCoverArt", &[("id", id.into()), ("size", size.to_string())])?;
|
|
let resp = self.http.get(url).send().await.map_err(redact)?;
|
|
let status = resp.status();
|
|
if !status.is_success() {
|
|
bail!("getCoverArt: server returned {status}");
|
|
}
|
|
let is_json = resp
|
|
.headers()
|
|
.get(reqwest::header::CONTENT_TYPE)
|
|
.and_then(|v| v.to_str().ok())
|
|
.is_some_and(|v| v.contains("json") || v.contains("xml"));
|
|
if is_json {
|
|
bail!("getCoverArt: no image for {id}");
|
|
}
|
|
Ok(resp.bytes().await.map_err(redact)?.to_vec())
|
|
}
|
|
|
|
pub fn stream_url(&self, id: &str) -> String {
|
|
self.endpoint_url("stream", &[("id", id.into())])
|
|
.map(|u| u.to_string())
|
|
.unwrap_or_default()
|
|
}
|
|
}
|
|
|
|
/// Request URLs carry the auth token, so they must never reach an error
|
|
/// message: those end up on screen and in the logs.
|
|
fn redact(e: reqwest::Error) -> reqwest::Error {
|
|
e.without_url()
|
|
}
|
|
|
|
fn normalize_base(base: &str) -> String {
|
|
let base = base.trim().trim_end_matches('/');
|
|
let base = base.strip_suffix("/rest").unwrap_or(base);
|
|
if base.starts_with("http://") || base.starts_with("https://") {
|
|
base.to_string()
|
|
} else {
|
|
format!("https://{base}")
|
|
}
|
|
}
|
|
|
|
fn random_salt() -> String {
|
|
let nanos = SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.map(|d| d.as_nanos())
|
|
.unwrap_or(0);
|
|
let a = RandomState::new().hash_one(nanos);
|
|
let b = RandomState::new().hash_one(a ^ u64::from(std::process::id()));
|
|
format!("{a:016x}{b:016x}")
|
|
}
|
|
|
|
/// Older servers send ids as numbers, OpenSubsonic as strings.
|
|
fn de_id<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
|
Ok(match serde_json::Value::deserialize(d)? {
|
|
serde_json::Value::String(s) => s,
|
|
serde_json::Value::Number(n) => n.to_string(),
|
|
other => other.to_string(),
|
|
})
|
|
}
|
|
|
|
fn de_opt_id<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
|
|
Ok(match Option::<serde_json::Value>::deserialize(d)? {
|
|
Some(serde_json::Value::String(s)) if !s.is_empty() => Some(s),
|
|
Some(serde_json::Value::Number(n)) => Some(n.to_string()),
|
|
_ => None,
|
|
})
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Album {
|
|
#[serde(deserialize_with = "de_id")]
|
|
pub id: String,
|
|
#[serde(default)]
|
|
pub name: String,
|
|
#[serde(default)]
|
|
pub artist: Option<String>,
|
|
#[serde(default, deserialize_with = "de_opt_id")]
|
|
pub cover_art: Option<String>,
|
|
#[serde(default)]
|
|
pub year: Option<i32>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Artist {
|
|
#[serde(deserialize_with = "de_id")]
|
|
pub id: String,
|
|
#[serde(default)]
|
|
pub name: String,
|
|
#[serde(default)]
|
|
pub album_count: Option<u32>,
|
|
#[serde(default, deserialize_with = "de_opt_id")]
|
|
pub cover_art: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct ArtistDetail {
|
|
#[serde(default)]
|
|
pub name: String,
|
|
#[serde(default)]
|
|
pub album: Vec<Album>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct AlbumDetail {
|
|
#[serde(default)]
|
|
pub name: String,
|
|
#[serde(default)]
|
|
pub artist: Option<String>,
|
|
#[serde(default, deserialize_with = "de_opt_id")]
|
|
pub cover_art: Option<String>,
|
|
#[serde(default)]
|
|
pub year: Option<i32>,
|
|
#[serde(default)]
|
|
pub duration: Option<u32>,
|
|
#[serde(default)]
|
|
pub song: Vec<Song>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Song {
|
|
#[serde(deserialize_with = "de_id")]
|
|
pub id: String,
|
|
#[serde(default)]
|
|
pub title: String,
|
|
#[serde(default)]
|
|
pub artist: Option<String>,
|
|
#[serde(default)]
|
|
pub album: Option<String>,
|
|
#[serde(default, deserialize_with = "de_opt_id")]
|
|
pub cover_art: Option<String>,
|
|
#[serde(default)]
|
|
pub duration: Option<u32>,
|
|
#[serde(default)]
|
|
pub track: Option<u32>,
|
|
#[serde(default)]
|
|
pub disc_number: Option<u32>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Playlist {
|
|
#[serde(deserialize_with = "de_id")]
|
|
pub id: String,
|
|
#[serde(default)]
|
|
pub name: String,
|
|
#[serde(default)]
|
|
pub song_count: Option<u32>,
|
|
#[serde(default, deserialize_with = "de_opt_id")]
|
|
pub cover_art: Option<String>,
|
|
#[serde(default)]
|
|
pub owner: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct PlaylistDetail {
|
|
#[serde(default)]
|
|
pub name: String,
|
|
#[serde(default, deserialize_with = "de_opt_id")]
|
|
pub cover_art: Option<String>,
|
|
#[serde(default)]
|
|
pub duration: Option<u32>,
|
|
#[serde(default)]
|
|
pub entry: Vec<Song>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Default, Deserialize)]
|
|
pub struct SearchResult {
|
|
#[serde(default)]
|
|
pub artist: Vec<Artist>,
|
|
#[serde(default)]
|
|
pub album: Vec<Album>,
|
|
#[serde(default)]
|
|
pub song: Vec<Song>,
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn base_url_is_normalized() {
|
|
assert_eq!(normalize_base("music.example.com/"), "https://music.example.com");
|
|
assert_eq!(normalize_base("http://nas:4533/rest"), "http://nas:4533");
|
|
}
|
|
|
|
#[test]
|
|
fn numeric_ids_are_accepted() {
|
|
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"));
|
|
}
|
|
|
|
/// Exercises every endpoint against a real server:
|
|
/// REMUS_TEST_URL=... REMUS_TEST_USER=... REMUS_TEST_PASS=... cargo test -- --ignored
|
|
#[tokio::test]
|
|
#[ignore]
|
|
async fn live_server() {
|
|
let var = |k| std::env::var(k).unwrap_or_else(|_| panic!("{k} not set"));
|
|
let c = Client::from_password(&var("REMUS_TEST_URL"), &var("REMUS_TEST_USER"), &var("REMUS_TEST_PASS"));
|
|
c.ping().await.unwrap();
|
|
|
|
let albums = c.album_list("newest", 10, 0).await.unwrap();
|
|
assert!(!albums.is_empty(), "no albums");
|
|
let album = c.album(&albums[0].id).await.unwrap();
|
|
assert!(!album.song.is_empty(), "album has no songs");
|
|
println!(
|
|
"album: {} by {:?}, {} songs",
|
|
album.name,
|
|
album.artist,
|
|
album.song.len()
|
|
);
|
|
|
|
let cover = album.cover_art.as_deref().expect("album has no cover id");
|
|
let bytes = c.cover_art(cover, 256).await.unwrap();
|
|
let img = image::load_from_memory(&bytes).unwrap();
|
|
println!("cover: {}x{}", img.width(), img.height());
|
|
|
|
let artists = c.artists().await.unwrap();
|
|
assert!(!artists.is_empty(), "no artists");
|
|
let artist = c.artist(&artists[0].id).await.unwrap();
|
|
println!("artist: {} with {} albums", artist.name, artist.album.len());
|
|
|
|
let playlists = c.playlists().await.unwrap();
|
|
if let Some(p) = playlists.first() {
|
|
let p = c.playlist(&p.id).await.unwrap();
|
|
println!("playlist: {} with {} entries", p.name, p.entry.len());
|
|
}
|
|
|
|
let found = c.search(&album.name).await.unwrap();
|
|
assert!(!found.album.is_empty(), "search found nothing for {}", album.name);
|
|
|
|
let url = c.stream_url(&album.song[0].id);
|
|
let resp = reqwest::get(&url).await.unwrap();
|
|
assert!(resp.status().is_success(), "stream returned {}", resp.status());
|
|
println!("stream content-type: {:?}", resp.headers().get("content-type"));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn errors_never_contain_the_token() {
|
|
// Port 1 on loopback refuses the connection, so the request fails.
|
|
let c = Client::new("http://127.0.0.1:1", "u", "somesalt", "secrettoken");
|
|
let err = format!("{:#}", c.ping().await.unwrap_err());
|
|
assert!(!err.contains("secrettoken"), "token leaked: {err}");
|
|
assert!(!err.contains("somesalt"), "salt leaked: {err}");
|
|
let err = format!("{:#}", c.cover_art("al-1", 256).await.unwrap_err());
|
|
assert!(!err.contains("secrettoken"), "token leaked: {err}");
|
|
}
|
|
|
|
#[test]
|
|
fn token_is_md5_of_password_and_salt() {
|
|
let c = Client::from_password("http://x", "u", "sesame");
|
|
let expected = format!("{:x}", md5::compute(format!("sesame{}", c.salt())));
|
|
assert_eq!(c.token(), expected);
|
|
}
|
|
}
|