feat: My server, browse and play a Navidrome library

Adds a "My server" sidebar item (⌘5) for Navidrome and other
Subsonic-compatible servers: albums, artists, playlists, starred songs
and search, with album, artist and playlist pages. Server songs share the
player and queue with Yandex tracks and scrobble back to the server.

- New subsonic-api crate: token auth, envelope and error parsing, and a
  stream plan that keeps files the player decodes and asks the server to
  transcode the rest to MP3.
- ym_api::Track gains a Subsonic source; the player fetches, reports and
  scrobbles by source. Server errors never sign out of Yandex, and the
  Yandex client never fetches server audio or covers.
- Server credentials live in the keychain; connect and disconnect from
  the page or Settings.
- Server tracks have no likes; lyrics come from LRCLIB.
This commit is contained in:
yuriy.p committed 2026-11-16 12:21:02 +06:00
1 parent 391a554736
commit 5dbdc04cd4
32 files changed
+2906 -150

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
[package]
name = "subsonic-api"
description = "Client for Subsonic-compatible music servers such as Navidrome"
version.workspace = true
edition.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
md-5 = "0.10"
rand = "0.9"
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
[lints]
workspace = true
+584
View File
@@ -0,0 +1,584 @@
//! Requests, authentication and the `subsonic-response` envelope.
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use md5::{Digest, Md5};
use rand::Rng;
use rand::distr::Alphanumeric;
use reqwest::Url;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use crate::models::{
self, Album, AlbumSummary, Artist, ArtistSummary, Playlist, PlaylistSummary, RawAlbum, RawArtist,
RawIndex, RawMixed, RawPlaylist, SearchResults, Song,
};
use crate::{Error, Result};
/// The REST version Musyx speaks. 1.13 added token auth; 1.16.1 is what Navidrome reports.
const API_VERSION: &str = "1.16.1";
const CLIENT_NAME: &str = "musyx";
const API_TIMEOUT: Duration = Duration::from_secs(30);
/// Whole files are downloaded before playback; a long FLAC on a slow link takes a while.
const STREAM_TIMEOUT: Duration = Duration::from_secs(300);
/// What the user types to connect. Stored in the system keychain as JSON.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Config {
pub url: String,
pub username: String,
pub password: String,
}
/// The password stays out of logs.
impl std::fmt::Debug for Config {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Config").field("url", &self.url).field("username", &self.username).finish_non_exhaustive()
}
}
impl Config {
/// The server's `/rest/` base. Accepts what people paste: no scheme
/// (`music.example.com` means https), trailing slashes, or the web UI's
/// own address (`…/app/#/album/…`).
pub fn rest_base(&self) -> Result<Url> {
let raw = self.url.trim();
if raw.is_empty() {
return Err(Error::InvalidUrl("empty".into()));
}
let with_scheme = if raw.contains("://") { raw.to_owned() } else { format!("https://{raw}") };
let mut url = Url::parse(&with_scheme).map_err(|e| Error::InvalidUrl(e.to_string()))?;
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
return Err(Error::InvalidUrl(format!("unsupported address {raw}")));
}
url.set_query(None);
url.set_fragment(None);
let mut path = format!("{}/", url.path().trim_end_matches('/'));
// Everything from a pasted API path (`/rest/ping`) or the web UI (`/app/`) on.
for marker in ["/rest/", "/app/"] {
if let Some(i) = path.find(marker) {
path.truncate(i + 1);
}
}
let path = path.trim_end_matches('/');
url.set_path(&format!("{path}/rest/"));
Ok(url)
}
}
/// How to ask for a song's audio: the file as stored, when the player decodes
/// it and it fits the quality cap, or an MP3 the server transcodes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StreamPlan {
pub transcode: bool,
/// The cap sent as `maxBitRate`; also the label's bitrate when transcoding.
pub max_kbps: Option<u32>,
/// "mp3", "flac" or "aac-mp4", the codec names the player's decoder expects.
pub codec: &'static str,
pub bitrate_kbps: u32,
}
impl StreamPlan {
/// `max_kbps: None` means no cap; `lossless` lets FLAC through untouched.
pub fn for_song(suffix: &str, bit_rate: u32, max_kbps: Option<u32>, lossless: bool) -> Self {
// Unknown bitrates only pass when there's no cap to break.
let fits = max_kbps.is_none_or(|cap| bit_rate != 0 && bit_rate <= cap);
let raw = |codec, bitrate_kbps| StreamPlan { transcode: false, max_kbps: None, codec, bitrate_kbps };
match suffix {
"flac" if lossless => raw("flac", 0),
"mp3" if fits => raw("mp3", bit_rate),
"m4a" | "mp4" if fits => raw("aac-mp4", bit_rate),
_ => {
let cap = max_kbps.unwrap_or(320).min(320);
StreamPlan { transcode: true, max_kbps: Some(cap), codec: "mp3", bitrate_kbps: cap }
}
}
}
}
/// A downloaded song, ready for the decoder.
#[derive(Clone)]
pub struct Audio {
pub bytes: Vec<u8>,
pub codec: &'static str,
pub bitrate_kbps: u32,
}
impl std::fmt::Debug for Audio {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Audio")
.field("codec", &self.codec)
.field("bitrate_kbps", &self.bitrate_kbps)
.field("bytes", &self.bytes.len())
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlbumSort {
/// Recently added to the library.
#[default]
Newest,
AlphabeticalByName,
}
impl AlbumSort {
fn param(self) -> &'static str {
match self {
AlbumSort::Newest => "newest",
AlbumSort::AlphabeticalByName => "alphabeticalByName",
}
}
}
/// A signed-in connection. Cheap to clone: the HTTP pool is shared.
#[derive(Clone)]
pub struct Client {
http: reqwest::Client,
base: Url,
username: String,
password: String,
}
impl std::fmt::Debug for Client {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Client").field("base", &self.base.as_str()).field("username", &self.username).finish_non_exhaustive()
}
}
impl PartialEq for Client {
fn eq(&self, other: &Self) -> bool {
self.base == other.base && self.username == other.username && self.password == other.password
}
}
impl Client {
/// Builds the client; nothing is sent until the first call (see [`Client::ping`]).
pub fn new(config: &Config) -> Result<Self> {
let base = config.rest_base()?;
let http = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(10))
.user_agent(concat!("musyx/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(|e| Error::Network(e.to_string()))?;
Ok(Self { http, base, username: config.username.trim().to_owned(), password: config.password.clone() })
}
pub fn username(&self) -> &str {
&self.username
}
/// `music.example.com` or `10.0.0.2:4533`, for display.
pub fn host(&self) -> String {
let host = self.base.host_str().unwrap_or_default();
match self.base.port() {
Some(port) => format!("{host}:{port}"),
None => host.to_owned(),
}
}
fn url(&self, method: &str, params: &[(&str, &str)]) -> Url {
let salt: String = rand::rng().sample_iter(Alphanumeric).take(12).map(char::from).collect();
self.url_with_salt(method, params, &salt)
}
/// Token auth: `t = md5(password + salt)`, so the password never travels.
fn url_with_salt(&self, method: &str, params: &[(&str, &str)], salt: &str) -> Url {
let mut url = self.base.join(method).expect("method names are plain path segments");
url.query_pairs_mut()
.append_pair("u", &self.username)
.append_pair("t", &token(&self.password, salt))
.append_pair("s", salt)
.append_pair("v", API_VERSION)
.append_pair("c", CLIENT_NAME)
.append_pair("f", "json")
.extend_pairs(params);
url
}
async fn call<T: DeserializeOwned>(&self, method: &str, params: &[(&str, &str)]) -> Result<T> {
let body = self
.http
.get(self.url(method, params))
.timeout(API_TIMEOUT)
.send()
.await?
.error_for_status()?
.text()
.await?;
unwrap_envelope(&body)
}
/// Endpoints that answer with a file, or with an error envelope.
async fn bytes(&self, method: &str, params: &[(&str, &str)], timeout: Duration) -> Result<Vec<u8>> {
let reply = self.http.get(self.url(method, params)).timeout(timeout).send().await?.error_for_status()?;
let is_envelope = reply
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|ct| ct.contains("json") || ct.contains("xml"));
let body = reply.bytes().await?;
if is_envelope {
let text = String::from_utf8_lossy(&body);
unwrap_envelope::<serde_json::Value>(&text)?;
return Err(Error::Api(format!("{method} answered with a message instead of a file")));
}
Ok(body.to_vec())
}
/// Checks the address and the credentials.
pub async fn ping(&self) -> Result<()> {
self.call::<serde_json::Value>("ping", &[]).await.map(drop)
}
pub async fn albums(&self, sort: AlbumSort, offset: usize, size: usize) -> Result<Vec<AlbumSummary>> {
let (offset, size) = (offset.to_string(), size.to_string());
let reply: AlbumListReply = self
.call("getAlbumList2", &[("type", sort.param()), ("offset", &offset), ("size", &size)])
.await?;
Ok(reply.resolve())
}
pub async fn album(&self, id: &str) -> Result<Album> {
let reply: AlbumReply = self.call("getAlbum", &[("id", id)]).await?;
reply.resolve()
}
pub async fn artists(&self) -> Result<Vec<ArtistSummary>> {
let reply: ArtistsReply = self.call("getArtists", &[]).await?;
Ok(reply.resolve())
}
pub async fn artist(&self, id: &str) -> Result<Artist> {
let reply: ArtistReply = self.call("getArtist", &[("id", id)]).await?;
reply.resolve()
}
pub async fn playlists(&self) -> Result<Vec<PlaylistSummary>> {
let reply: PlaylistsReply = self.call("getPlaylists", &[]).await?;
Ok(reply.resolve())
}
pub async fn playlist(&self, id: &str) -> Result<Playlist> {
let reply: PlaylistReply = self.call("getPlaylist", &[("id", id)]).await?;
reply.resolve()
}
/// Starred songs, newest first as the server orders them.
pub async fn starred(&self) -> Result<Vec<Song>> {
let reply: StarredReply = self.call("getStarred2", &[]).await?;
Ok(reply.starred.resolve().songs)
}
pub async fn search(&self, query: &str) -> Result<SearchResults> {
let reply: SearchReply = self
.call(
"search3",
&[("query", query.trim()), ("artistCount", "12"), ("albumCount", "24"), ("songCount", "60")],
)
.await?;
Ok(reply.result.resolve())
}
/// Cover image bytes at about `size` pixels square.
pub async fn cover_art(&self, id: &str, size: u32) -> Result<Vec<u8>> {
self.bytes("getCoverArt", &[("id", id), ("size", &size.to_string())], API_TIMEOUT).await
}
/// Downloads a whole song as `plan` says.
pub async fn stream(&self, song_id: &str, plan: StreamPlan) -> Result<Audio> {
let cap = plan.max_kbps.map(|k| k.to_string());
let mut params = vec![("id", song_id), ("format", if plan.transcode { "mp3" } else { "raw" })];
if let Some(cap) = &cap {
params.push(("maxBitRate", cap));
}
let bytes = self.bytes("stream", &params, STREAM_TIMEOUT).await?;
if bytes.is_empty() {
return Err(Error::Api("empty stream".into()));
}
Ok(Audio { bytes, codec: plan.codec, bitrate_kbps: plan.bitrate_kbps })
}
/// `submission: false` sets "now playing"; `true` records a play.
pub async fn scrobble(&self, song_id: &str, submission: bool) -> Result<()> {
let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis()).to_string();
let mut params = vec![("id", song_id), ("submission", if submission { "true" } else { "false" })];
if submission {
params.push(("time", &now));
}
self.call::<serde_json::Value>("scrobble", &params).await.map(drop)
}
}
fn token(password: &str, salt: &str) -> String {
format!("{:x}", Md5::digest(format!("{password}{salt}").as_bytes()))
}
#[derive(Deserialize)]
struct Envelope {
#[serde(rename = "subsonic-response")]
response: serde_json::Value,
}
/// Opens `{"subsonic-response": {...}}`, turning `"status": "failed"` into an error.
fn unwrap_envelope<T: DeserializeOwned>(body: &str) -> Result<T> {
let Ok(Envelope { response }) = serde_json::from_str(body) else {
return Err(Error::Api("not a Subsonic server reply".into()));
};
if response.get("status").and_then(serde_json::Value::as_str) != Some("ok") {
let error = response.get("error");
let code = error.and_then(|e| e.get("code")).and_then(serde_json::Value::as_i64).unwrap_or(0);
let message =
error.and_then(|e| e.get("message")).and_then(serde_json::Value::as_str).unwrap_or("failed").to_owned();
return Err(Error::from_code(code, message));
}
serde_json::from_value(response).map_err(|e| Error::Api(e.to_string()))
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct AlbumList {
album: Vec<RawAlbum>,
}
#[derive(Deserialize)]
struct AlbumListReply {
#[serde(rename = "albumList2", default)]
list: AlbumList,
}
impl AlbumListReply {
fn resolve(self) -> Vec<AlbumSummary> {
models::albums(self.list.album)
}
}
#[derive(Deserialize)]
struct AlbumReply {
album: RawAlbum,
}
impl AlbumReply {
fn resolve(self) -> Result<Album> {
self.album.resolve().ok_or_else(|| Error::Api("album without id".into()))
}
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct ArtistIndex {
index: Vec<RawIndex>,
}
#[derive(Deserialize)]
struct ArtistsReply {
#[serde(default)]
artists: ArtistIndex,
}
impl ArtistsReply {
fn resolve(self) -> Vec<ArtistSummary> {
models::artists(self.artists.index.into_iter().flat_map(|i| i.artist).collect())
}
}
#[derive(Deserialize)]
struct ArtistReply {
artist: RawArtist,
}
impl ArtistReply {
fn resolve(self) -> Result<Artist> {
self.artist.resolve().ok_or_else(|| Error::Api("artist without id".into()))
}
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct PlaylistList {
playlist: Vec<RawPlaylist>,
}
#[derive(Deserialize)]
struct PlaylistsReply {
#[serde(default)]
playlists: PlaylistList,
}
impl PlaylistsReply {
fn resolve(self) -> Vec<PlaylistSummary> {
models::playlists(self.playlists.playlist)
}
}
#[derive(Deserialize)]
struct PlaylistReply {
playlist: RawPlaylist,
}
impl PlaylistReply {
fn resolve(self) -> Result<Playlist> {
self.playlist.resolve().ok_or_else(|| Error::Api("playlist without id".into()))
}
}
#[derive(Deserialize)]
struct StarredReply {
#[serde(rename = "starred2", default)]
starred: RawMixed,
}
#[derive(Deserialize)]
struct SearchReply {
#[serde(rename = "searchResult3", default)]
result: RawMixed,
}
#[cfg(test)]
mod tests {
use super::*;
fn config(url: &str) -> Config {
Config { url: url.into(), username: "yp".into(), password: "sesame".into() }
}
fn ok(body: &str) -> String {
format!(r#"{{"subsonic-response":{{"status":"ok","version":"1.16.1",{body}}}}}"#)
}
#[test]
fn token_matches_the_subsonic_docs_example() {
assert_eq!(token("sesame", "c19b2d"), "26719a1196d2a940705a59634eb18eab");
}
#[test]
fn urls_carry_a_token_never_the_password() {
let client = Client::new(&config("https://music.example.com")).unwrap();
let url = client.url_with_salt("getAlbum", &[("id", "al 1")], "c19b2d");
assert_eq!(
url.as_str(),
"https://music.example.com/rest/getAlbum?u=yp&t=26719a1196d2a940705a59634eb18eab&s=c19b2d&v=1.16.1&c=musyx&f=json&id=al+1"
);
let fresh = client.url("ping", &[]);
assert!(!fresh.as_str().contains("sesame"));
assert!(!format!("{client:?}{:?}", config("x")).contains("sesame"), "password leaked into Debug");
assert_ne!(client.url("ping", &[]), fresh, "every request gets a new salt");
}
#[test]
fn pasted_addresses_become_rest_bases() {
let base = |u: &str| config(u).rest_base().map(|u| u.to_string());
assert_eq!(base("music.example.com/").unwrap(), "https://music.example.com/rest/");
assert_eq!(base(" http://10.0.0.2:4533 ").unwrap(), "http://10.0.0.2:4533/rest/");
assert_eq!(base("https://example.com/music/app/#/album/1").unwrap(), "https://example.com/music/rest/");
assert_eq!(base("https://example.com/rest/ping?u=x").unwrap(), "https://example.com/rest/");
assert!(matches!(base(""), Err(Error::InvalidUrl(_))));
assert!(matches!(base("ftp://example.com"), Err(Error::InvalidUrl(_))));
let client = Client::new(&config("http://10.0.0.2:4533")).unwrap();
assert_eq!(client.host(), "10.0.0.2:4533");
}
#[test]
fn failed_envelopes_become_errors() {
let failed = r#"{"subsonic-response":{"status":"failed","version":"1.16.1",
"error":{"code":40,"message":"Wrong username or password"}}}"#;
assert_eq!(
unwrap_envelope::<serde_json::Value>(failed),
Err(Error::Unauthorized("Wrong username or password".into()))
);
assert!(matches!(unwrap_envelope::<serde_json::Value>("<html>Nginx</html>"), Err(Error::Api(_))));
assert!(unwrap_envelope::<serde_json::Value>(&ok(r#""type":"navidrome""#)).is_ok());
}
#[test]
fn album_lists_and_albums_parse() {
let list: AlbumListReply = unwrap_envelope(&ok(
r#""albumList2":{"album":[{"id":"a1","name":"One","artist":"X","coverArt":"al-a1","songCount":2},
{"id":"a2","name":"Two"}]}"#,
))
.unwrap();
let list = list.resolve();
assert_eq!(list.iter().map(|a| a.id.as_str()).collect::<Vec<_>>(), ["a1", "a2"]);
assert_eq!(list[0].cover_art.as_deref(), Some("al-a1"));
let empty: AlbumListReply = unwrap_envelope(&ok(r#""albumList2":{}"#)).unwrap();
assert!(empty.resolve().is_empty(), "Navidrome omits empty arrays");
let album: AlbumReply = unwrap_envelope(&ok(
r#""album":{"id":"a1","name":"One","artist":"X","artistId":"ar1","year":2001,"duration":400,
"song":[{"id":"s1","title":"First","track":1,"duration":200,"suffix":"mp3","bitRate":320},
{"id":"s2","title":"Second","track":2,"duration":200,"suffix":"opus"}]}"#,
))
.unwrap();
let album = album.resolve().unwrap();
assert_eq!(album.info.subtitle(), "X · 2001");
assert_eq!(album.songs.len(), 2);
assert_eq!(album.songs[1].suffix, "opus");
}
#[test]
fn artists_flatten_the_index_and_artist_pages_list_albums() {
let artists: ArtistsReply = unwrap_envelope(&ok(
r#""artists":{"ignoredArticles":"The","index":[
{"name":"A","artist":[{"id":"ar1","name":"Aquarium","albumCount":3,"coverArt":"ar-ar1"}]},
{"name":"K","artist":[{"id":"ar2","name":"Kino"}]}]}"#,
))
.unwrap();
let artists = artists.resolve();
assert_eq!(artists.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["Aquarium", "Kino"]);
assert_eq!(artists[0].album_count, 3);
let artist: ArtistReply = unwrap_envelope(&ok(
r#""artist":{"id":"ar2","name":"Kino","album":[{"id":"a1","name":"45"},{"id":"a2","name":"Nachalnik Kamchatki"}]}"#,
))
.unwrap();
let artist = artist.resolve().unwrap();
assert_eq!(artist.info.name, "Kino");
assert_eq!(artist.albums.len(), 2);
}
#[test]
fn playlists_starred_and_search_parse() {
let lists: PlaylistsReply = unwrap_envelope(&ok(
r#""playlists":{"playlist":[{"id":"p1","name":"Road","owner":"yp","songCount":12,"duration":3000}]}"#,
))
.unwrap();
let lists = lists.resolve();
assert_eq!((lists[0].name.as_str(), lists[0].song_count), ("Road", 12));
let list: PlaylistReply = unwrap_envelope(&ok(
r#""playlist":{"id":"p1","name":"Road","entry":[{"id":"s1","title":"A"},{"id":"s2","title":"B"}]}"#,
))
.unwrap();
assert_eq!(list.resolve().unwrap().songs.len(), 2);
let starred: StarredReply =
unwrap_envelope(&ok(r#""starred2":{"song":[{"id":"s9","title":"Fav","starred":"2026-01-01T00:00:00Z"}]}"#))
.unwrap();
assert_eq!(starred.starred.resolve().songs[0].id, "s9");
let found: SearchReply = unwrap_envelope(&ok(
r#""searchResult3":{"artist":[{"id":"ar1","name":"Kino"}],"song":[{"id":"s1","title":"Kukushka"}]}"#,
))
.unwrap();
let found = found.result.resolve();
assert_eq!((found.artists.len(), found.albums.len(), found.songs.len()), (1, 0, 1));
let nothing: SearchReply = unwrap_envelope(&ok(r#""searchResult3":{}"#)).unwrap();
assert!(nothing.result.resolve().is_empty());
}
#[test]
fn stream_plans_keep_files_the_player_decodes_within_the_cap() {
let plan = StreamPlan::for_song;
assert_eq!(plan("mp3", 320, None, false), StreamPlan { transcode: false, max_kbps: None, codec: "mp3", bitrate_kbps: 320 });
assert_eq!(plan("m4a", 256, None, false).codec, "aac-mp4");
assert_eq!(plan("flac", 1000, None, true), StreamPlan { transcode: false, max_kbps: None, codec: "flac", bitrate_kbps: 0 });
// FLAC without the Lossless setting, formats the player can't decode, and
// files over the cap all become server-side MP3s.
assert_eq!(plan("flac", 1000, None, false), StreamPlan { transcode: true, max_kbps: Some(320), codec: "mp3", bitrate_kbps: 320 });
assert_eq!(plan("opus", 128, None, true).max_kbps, Some(320));
assert_eq!(plan("ogg", 160, Some(128), false).max_kbps, Some(128));
assert_eq!(plan("mp3", 320, Some(192), false), StreamPlan { transcode: true, max_kbps: Some(192), codec: "mp3", bitrate_kbps: 192 });
assert!(!plan("mp3", 128, Some(192), false).transcode);
assert!(plan("mp3", 0, Some(192), false).transcode, "unknown bitrate under a cap");
}
}
+61
View File
@@ -0,0 +1,61 @@
/// Errors the app can act on. Messages are for logs, not for display.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
/// Wrong username or password, or the server refuses token sign-in.
#[error("unauthorized: {0}")]
Unauthorized(String),
/// The address isn't a usable http(s) URL.
#[error("invalid server address: {0}")]
InvalidUrl(String),
/// The album, artist or playlist doesn't exist (any more).
#[error("not found: {0}")]
NotFound(String),
/// No connection, DNS failure, timeout: worth retrying.
#[error("network: {0}")]
Network(String),
/// Anything else the server rejected, or a reply that isn't Subsonic.
#[error("api: {0}")]
Api(String),
}
pub type Result<T> = std::result::Result<T, Error>;
impl Error {
/// Subsonic error codes: 40 wrong credentials, 41 token auth unsupported
/// (LDAP users), 70 not found.
pub(crate) fn from_code(code: i64, message: String) -> Self {
match code {
40 | 41 => Error::Unauthorized(message),
70 => Error::NotFound(message),
_ => Error::Api(format!("{code}: {message}")),
}
}
}
impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Self {
if e.is_decode() {
Error::Api(e.to_string())
} else if e.status() == Some(reqwest::StatusCode::UNAUTHORIZED) {
Error::Unauthorized(e.to_string())
} else if e.status() == Some(reqwest::StatusCode::NOT_FOUND) {
// Usually a wrong address: the host answers, but has no /rest.
Error::Api(e.to_string())
} else {
Error::Network(e.to_string())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn subsonic_codes_map_to_actionable_errors() {
assert!(matches!(Error::from_code(40, "Wrong username or password".into()), Error::Unauthorized(_)));
assert!(matches!(Error::from_code(41, String::new()), Error::Unauthorized(_)));
assert!(matches!(Error::from_code(70, "Album not found".into()), Error::NotFound(_)));
assert_eq!(Error::from_code(0, "boom".into()), Error::Api("0: boom".into()));
}
}
+14
View File
@@ -0,0 +1,14 @@
//! Client for Subsonic-compatible music servers (Navidrome, Gonic, Airsonic).
//!
//! Like `ym-api`, it hands the app its own resolved types and keeps the wire
//! format, authentication and error codes in here.
mod client;
mod error;
mod models;
pub use client::{AlbumSort, Audio, Client, Config, StreamPlan};
pub use error::{Error, Result};
pub use models::{
Album, AlbumSummary, Artist, ArtistSummary, Playlist, PlaylistSummary, SearchResults, Song,
};
+348
View File
@@ -0,0 +1,348 @@
//! The app-facing shapes of Subsonic objects, converted from the wire format
//! with every `Option` the UI doesn't care about resolved here.
use std::time::Duration;
use serde::Deserialize;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Song {
pub id: String,
pub title: String,
pub artist: Option<String>,
pub artist_id: Option<String>,
pub album: Option<String>,
pub album_id: Option<String>,
pub duration: Duration,
pub track: Option<u32>,
pub disc: Option<u32>,
/// Id for `getCoverArt`.
pub cover_art: Option<String>,
/// File extension on the server: "mp3", "flac", "m4a", "opus"…
pub suffix: String,
/// Kbps of the stored file; 0 when the server doesn't say.
pub bit_rate: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlbumSummary {
pub id: String,
pub name: String,
pub artist: Option<String>,
pub artist_id: Option<String>,
pub cover_art: Option<String>,
pub song_count: u32,
pub duration: Duration,
pub year: Option<u32>,
}
impl AlbumSummary {
/// "Artist · 2019", or whichever half is known.
pub fn subtitle(&self) -> String {
match (&self.artist, self.year) {
(Some(a), Some(y)) => format!("{a} · {y}"),
(Some(a), None) => a.clone(),
(None, Some(y)) => y.to_string(),
(None, None) => String::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Album {
pub info: AlbumSummary,
pub songs: Vec<Song>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArtistSummary {
pub id: String,
pub name: String,
pub cover_art: Option<String>,
pub album_count: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Artist {
pub info: ArtistSummary,
pub albums: Vec<AlbumSummary>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlaylistSummary {
pub id: String,
pub name: String,
pub owner: Option<String>,
pub cover_art: Option<String>,
pub song_count: u32,
pub duration: Duration,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Playlist {
pub info: PlaylistSummary,
pub songs: Vec<Song>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SearchResults {
pub artists: Vec<ArtistSummary>,
pub albums: Vec<AlbumSummary>,
pub songs: Vec<Song>,
}
impl SearchResults {
pub fn is_empty(&self) -> bool {
self.artists.is_empty() && self.albums.is_empty() && self.songs.is_empty()
}
}
// ---- Wire format ----------------------------------------------------------
/// Ids are strings in Navidrome, numbers in some older servers.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub(crate) enum Id {
Text(String),
Number(i64),
}
impl Id {
fn into_string(self) -> Option<String> {
match self {
Id::Text(s) if s.is_empty() => None,
Id::Text(s) => Some(s),
Id::Number(n) => Some(n.to_string()),
}
}
}
fn id(raw: Option<Id>) -> Option<String> {
raw.and_then(Id::into_string)
}
fn non_empty(s: Option<String>) -> Option<String> {
s.filter(|s| !s.trim().is_empty())
}
fn count(n: Option<i64>) -> u32 {
n.unwrap_or(0).clamp(0, i64::from(u32::MAX)) as u32
}
fn secs(n: Option<i64>) -> Duration {
Duration::from_secs(n.unwrap_or(0).max(0) as u64)
}
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub(crate) struct RawSong {
id: Option<Id>,
title: Option<String>,
artist: Option<String>,
artist_id: Option<Id>,
album: Option<String>,
album_id: Option<Id>,
duration: Option<i64>,
track: Option<i64>,
disc_number: Option<i64>,
cover_art: Option<Id>,
suffix: Option<String>,
bit_rate: Option<i64>,
is_dir: Option<bool>,
is_video: Option<bool>,
}
impl RawSong {
pub(crate) fn resolve(self) -> Option<Song> {
if self.is_dir == Some(true) || self.is_video == Some(true) {
return None;
}
let positive = |n: Option<i64>| n.filter(|&n| n > 0).map(|n| n as u32);
Some(Song {
id: id(self.id)?,
title: non_empty(self.title).unwrap_or_else(|| "Untitled".into()),
artist: non_empty(self.artist),
artist_id: id(self.artist_id),
album: non_empty(self.album),
album_id: id(self.album_id),
duration: secs(self.duration),
track: positive(self.track),
disc: positive(self.disc_number),
cover_art: id(self.cover_art),
suffix: self.suffix.unwrap_or_default().to_ascii_lowercase(),
bit_rate: count(self.bit_rate),
})
}
}
pub(crate) fn songs(raw: Vec<RawSong>) -> Vec<Song> {
raw.into_iter().filter_map(RawSong::resolve).collect()
}
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub(crate) struct RawAlbum {
id: Option<Id>,
name: Option<String>,
/// Older servers send `title` instead of `name`.
title: Option<String>,
artist: Option<String>,
artist_id: Option<Id>,
cover_art: Option<Id>,
song_count: Option<i64>,
duration: Option<i64>,
year: Option<i64>,
pub(crate) song: Vec<RawSong>,
}
impl RawAlbum {
pub(crate) fn summary(&mut self) -> Option<AlbumSummary> {
Some(AlbumSummary {
id: id(self.id.take())?,
name: non_empty(self.name.take().or(self.title.take())).unwrap_or_else(|| "Untitled".into()),
artist: non_empty(self.artist.take()),
artist_id: id(self.artist_id.take()),
cover_art: id(self.cover_art.take()),
song_count: count(self.song_count),
duration: secs(self.duration),
year: self.year.filter(|&y| y > 0).map(|y| y as u32),
})
}
pub(crate) fn resolve(mut self) -> Option<Album> {
let info = self.summary()?;
Some(Album { info, songs: songs(self.song) })
}
}
pub(crate) fn albums(raw: Vec<RawAlbum>) -> Vec<AlbumSummary> {
raw.into_iter().filter_map(|mut a| a.summary()).collect()
}
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub(crate) struct RawArtist {
id: Option<Id>,
name: Option<String>,
cover_art: Option<Id>,
album_count: Option<i64>,
pub(crate) album: Vec<RawAlbum>,
}
impl RawArtist {
pub(crate) fn summary(&mut self) -> Option<ArtistSummary> {
Some(ArtistSummary {
id: id(self.id.take())?,
name: non_empty(self.name.take()).unwrap_or_else(|| "Unknown artist".into()),
cover_art: id(self.cover_art.take()),
album_count: count(self.album_count),
})
}
pub(crate) fn resolve(mut self) -> Option<Artist> {
let info = self.summary()?;
Some(Artist { info, albums: albums(self.album) })
}
}
pub(crate) fn artists(raw: Vec<RawArtist>) -> Vec<ArtistSummary> {
raw.into_iter().filter_map(|mut a| a.summary()).collect()
}
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub(crate) struct RawPlaylist {
id: Option<Id>,
name: Option<String>,
owner: Option<String>,
cover_art: Option<Id>,
song_count: Option<i64>,
duration: Option<i64>,
pub(crate) entry: Vec<RawSong>,
}
impl RawPlaylist {
pub(crate) fn summary(&mut self) -> Option<PlaylistSummary> {
Some(PlaylistSummary {
id: id(self.id.take())?,
name: non_empty(self.name.take()).unwrap_or_else(|| "Untitled".into()),
owner: non_empty(self.owner.take()),
cover_art: id(self.cover_art.take()),
song_count: count(self.song_count),
duration: secs(self.duration),
})
}
pub(crate) fn resolve(mut self) -> Option<Playlist> {
let info = self.summary()?;
Some(Playlist { info, songs: songs(self.entry) })
}
}
pub(crate) fn playlists(raw: Vec<RawPlaylist>) -> Vec<PlaylistSummary> {
raw.into_iter().filter_map(|mut p| p.summary()).collect()
}
/// `search3` and `getStarred2` share this shape.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub(crate) struct RawMixed {
artist: Vec<RawArtist>,
album: Vec<RawAlbum>,
song: Vec<RawSong>,
}
impl RawMixed {
pub(crate) fn resolve(self) -> SearchResults {
SearchResults { artists: artists(self.artist), albums: albums(self.album), songs: songs(self.song) }
}
}
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub(crate) struct RawIndex {
pub(crate) artist: Vec<RawArtist>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn songs_resolve_and_skip_folders_and_videos() {
let raw: Vec<RawSong> = serde_json::from_str(
r#"[{"id":"s1","title":"Kukushka","artist":"Kino","artistId":"ar1","album":"Chorny Albom",
"albumId":"al1","duration":402,"track":3,"discNumber":1,"coverArt":"al-al1",
"suffix":"FLAC","bitRate":1011},
{"id":"d1","title":"Folder","isDir":true},
{"id":"v1","title":"Clip","isVideo":true},
{"id":7,"title":"","suffix":"mp3","track":0},
{"title":"no id"}]"#,
)
.unwrap();
let s = songs(raw);
assert_eq!(s.len(), 2);
assert_eq!(s[0].id, "s1");
assert_eq!(s[0].duration, Duration::from_secs(402));
assert_eq!((s[0].track, s[0].disc), (Some(3), Some(1)));
assert_eq!(s[0].suffix, "flac", "suffix is lowercased");
assert_eq!(s[0].cover_art.as_deref(), Some("al-al1"));
assert_eq!(s[1].id, "7", "numeric ids become strings");
assert_eq!(s[1].title, "Untitled");
assert_eq!(s[1].track, None);
}
#[test]
fn albums_take_name_or_title_and_build_subtitles() {
let mut a: RawAlbum =
serde_json::from_str(r#"{"id":"al1","name":"Gruppa krovi","artist":"Kino","year":1988,"songCount":11}"#)
.unwrap();
let a = a.summary().unwrap();
assert_eq!(a.subtitle(), "Kino · 1988");
assert_eq!(a.song_count, 11);
let mut old: RawAlbum = serde_json::from_str(r#"{"id":5,"title":"Old","year":0}"#).unwrap();
let old = old.summary().unwrap();
assert_eq!((old.id.as_str(), old.name.as_str(), old.year), ("5", "Old", None));
assert_eq!(old.subtitle(), "");
}
}
+38
View File
@@ -0,0 +1,38 @@
//! Talks to a real server. Run with
//! `SUBSONIC_URL=… SUBSONIC_USER=… SUBSONIC_PASSWORD=… cargo test -p subsonic-api -- --ignored`.
use subsonic_api::{AlbumSort, Client, Config, StreamPlan};
fn client() -> Client {
let var = |name: &str| std::env::var(name).unwrap_or_else(|_| panic!("set {name}"));
Client::new(&Config { url: var("SUBSONIC_URL"), username: var("SUBSONIC_USER"), password: var("SUBSONIC_PASSWORD") })
.expect("server address")
}
#[tokio::test]
#[ignore = "network"]
async fn browses_and_streams_the_first_album() {
let client = client();
client.ping().await.expect("ping");
let albums = client.albums(AlbumSort::Newest, 0, 5).await.expect("albums");
let first = albums.first().expect("the library has an album");
let album = client.album(&first.id).await.expect("album");
let song = album.songs.first().expect("the album has a song");
let plan = StreamPlan::for_song(&song.suffix, song.bit_rate, Some(128), false);
let audio = client.stream(&song.id, plan).await.expect("stream");
assert!(audio.bytes.len() > 10_000);
if let Some(cover) = &first.cover_art {
assert!(!client.cover_art(cover, 100).await.expect("cover").is_empty());
}
client.artists().await.expect("artists");
client.playlists().await.expect("playlists");
client.starred().await.expect("starred");
}
#[tokio::test]
#[ignore = "network"]
async fn wrong_password_is_unauthorized() {
let url = std::env::var("SUBSONIC_URL").expect("set SUBSONIC_URL");
let client = Client::new(&Config { url, username: "musyx-nobody".into(), password: "wrong".into() }).unwrap();
assert!(matches!(client.ping().await, Err(subsonic_api::Error::Unauthorized(_))));
}