diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index a41ff7552..3da3f36f3 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -2768,8 +2768,12 @@ pub async fn lastfm_preview( /// Validate `token` against ListenBrainz and store it. Returns the error rather than emitting /// it: a pasted token is validated synchronously, unlike Last.fm's browser round-trip. #[tauri::command] -pub async fn listenbrainz_connect(state: St<'_>, token: String) -> Result<(), String> { - crate::listenbrainz::connect(state.inner().clone(), token).await +pub async fn listenbrainz_connect( + state: St<'_>, + token: String, + url: Option, +) -> Result<(), String> { + crate::listenbrainz::connect(state.inner().clone(), token, url.unwrap_or_default()).await } #[tauri::command] diff --git a/src-tauri/src/lastfm.rs b/src-tauri/src/lastfm.rs index d5a5db52d..5418b228c 100644 --- a/src-tauri/src/lastfm.rs +++ b/src-tauri/src/lastfm.rs @@ -195,8 +195,9 @@ enum Msg { Position(f64), /// Session key set (connect) or cleared (disconnect). Session(Option), - /// ListenBrainz user token set (connect) or cleared (disconnect). - Token(Option), + /// ListenBrainz `(root, token)` set (connect) or cleared (disconnect). The root travels with + /// the token so a listen can never go to one server with the other's token. + Token(Option<(String, String)>), Config(Box), } @@ -269,7 +270,7 @@ impl LastfmHandle { /// ListenBrainz connect/disconnect writes here (see `crate::listenbrainz`): same task, same /// clock, second credential. - pub(crate) fn set_token(&self, token: Option) { + pub(crate) fn set_token(&self, token: Option<(String, String)>) { let _ = self.tx.send(Msg::Token(token)); } @@ -283,12 +284,12 @@ impl LastfmHandle { } /// Spawn the scrobbler task. `session_key` is the persisted Last.fm login and `lb_token` the -/// persisted ListenBrainz user token; `None` parks that half until the user connects. `app` is +/// persisted ListenBrainz `(root, user token)`; `None` parks that half until the user connects. `app` is /// for telling the UI when ListenBrainz refuses listens (see [`Scrobbler::lb_sent`]). pub fn spawn( app: tauri::AppHandle, session_key: Option, - lb_token: Option, + lb_token: Option<(String, String)>, cfg: ScrobbleConfig, ) -> LastfmHandle { let (tx, mut rx) = unbounded_channel::(); @@ -304,7 +305,7 @@ pub fn spawn( struct Scrobbler { app: tauri::AppHandle, session: Option, - lb_token: Option, + lb_token: Option<(String, String)>, /// What ListenBrainz last said is wrong with the token (`listenbrainz::problem`), so the UI /// hears about a change once instead of once per track. lb_problem: Option<&'static str>, @@ -320,7 +321,7 @@ impl Scrobbler { fn new( app: tauri::AppHandle, session: Option, - lb_token: Option, + lb_token: Option<(String, String)>, cfg: ScrobbleConfig, ) -> Self { Scrobbler { @@ -401,8 +402,8 @@ impl Scrobbler { if let Some(sk) = self.session.as_deref() { self.now_playing_lastfm(sk, &r).await; } - if let Some(token) = self.lb_token.clone() { - let sent = self.now_playing_listenbrainz(&token, &r).await; + if let Some((root, token)) = self.lb_token.clone() { + let sent = self.now_playing_listenbrainz(&root, &token, &r).await; self.lb_sent(sent); } } @@ -422,12 +423,12 @@ impl Scrobbler { } } - async fn now_playing_listenbrainz(&self, token: &str, r: &Resolved) -> LbSent { + async fn now_playing_listenbrainz(&self, root: &str, token: &str, r: &Resolved) -> LbSent { let video_id = self.track.as_ref().map(|t| t.video_id.as_str()).unwrap_or(""); let payload = serde_json::json!([{ "track_metadata": crate::listenbrainz::track_metadata(r, video_id, self.duration), }]); - let sent = crate::listenbrainz::submit(token, "playing_now", payload).await; + let sent = crate::listenbrainz::submit(root, token, "playing_now", payload).await; match &sent { Ok(_) => tracing::debug!(track = %r.title, "listenbrainz now playing sent"), Err(e) => tracing::debug!(error = %e, "listenbrainz now playing failed"), @@ -440,8 +441,8 @@ impl Scrobbler { if let Some(sk) = self.session.as_deref() { self.scrobble_lastfm(sk, &r).await; } - if let Some(token) = self.lb_token.clone() { - let sent = self.scrobble_listenbrainz(&token, &r).await; + if let Some((root, token)) = self.lb_token.clone() { + let sent = self.scrobble_listenbrainz(&root, &token, &r).await; self.lb_sent(sent); } } @@ -465,13 +466,13 @@ impl Scrobbler { } } - async fn scrobble_listenbrainz(&self, token: &str, r: &Resolved) -> LbSent { + async fn scrobble_listenbrainz(&self, root: &str, token: &str, r: &Resolved) -> LbSent { let video_id = self.track.as_ref().map(|t| t.video_id.as_str()).unwrap_or(""); let payload = serde_json::json!([{ "listened_at": self.started_at, "track_metadata": crate::listenbrainz::track_metadata(r, video_id, self.duration), }]); - let sent = crate::listenbrainz::submit(token, "single", payload).await; + let sent = crate::listenbrainz::submit(root, token, "single", payload).await; match &sent { Ok(_) => tracing::info!(track = %r.title, "submitted listen to listenbrainz"), Err(e) => tracing::warn!(error = %e, "listenbrainz listen failed"), diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 1ab98c781..31d43a117 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -890,7 +890,9 @@ pub fn run() { let lastfm = lastfm::spawn( handle.clone(), db.get_setting("lastfm_session_key").filter(|s| !s.is_empty()), - db.get_setting("listenbrainz_token").filter(|s| !s.is_empty()), + db.get_setting("listenbrainz_token").filter(|s| !s.is_empty()).map(|t| { + (db.get_setting("listenbrainz_url").unwrap_or_default(), t) + }), lastfm::ScrobbleConfig::load(&db), ); diff --git a/src-tauri/src/listenbrainz.rs b/src-tauri/src/listenbrainz.rs index 20952866a..df2847193 100644 --- a/src-tauri/src/listenbrainz.rs +++ b/src-tauri/src/listenbrainz.rs @@ -20,7 +20,31 @@ use tauri::Emitter; use crate::lastfm::Resolved; use crate::state::AppState; -const API_ROOT: &str = "https://api.listenbrainz.org"; +const DEFAULT_ROOT: &str = "https://api.listenbrainz.org"; + +/// Trimmed, no trailing slash, http(s) with a host and no query or fragment (endpoints are +/// appended as `{root}/1/...`). Empty = official server. +fn clean_root(url: &str) -> Result { + let url = url.trim().trim_end_matches('/'); + if url.is_empty() { + return Ok(String::new()); + } + let ok = reqwest::Url::parse(url).is_ok_and(|u| { + matches!(u.scheme(), "http" | "https") + && u.host_str().is_some() + && u.query().is_none() + && u.fragment().is_none() + }); + if !ok { + return Err("ListenBrainz: server URL must be http(s)://host[/path], without ? or #".into()); + } + Ok(url.to_owned()) +} + +fn root_or_default(root: &str) -> String { + if root.is_empty() { DEFAULT_ROOT } else { root }.to_owned() +} + const USER_AGENT: &str = concat!("Limusic/", env!("CARGO_PKG_VERSION"), " (https://github.com/SimoHypers/limusic)"); @@ -68,14 +92,16 @@ impl std::fmt::Display for SubmitError { } } +/// `root` is the `listenbrainz_url` the token was validated against (empty = official server). pub(crate) async fn submit( + root: &str, token: &str, listen_type: &str, payload: serde_json::Value, ) -> Result<(), SubmitError> { let body = serde_json::json!({ "listen_type": listen_type, "payload": payload }); let resp = crate::http::client() - .post(format!("{API_ROOT}/1/submit-listens")) + .post(format!("{}/1/submit-listens", root_or_default(root))) .header("Authorization", format!("Token {token}")) .header("User-Agent", USER_AGENT) .json(&body) @@ -116,16 +142,30 @@ pub(crate) fn emit_problem(app: &tauri::AppHandle, problem: Option<&str>) { let _ = app.emit("listenbrainz-problem", problem); } -async fn validate(token: &str) -> Result { +async fn validate(token: &str, root: &str) -> Result { let resp = crate::http::client() - .get(format!("{API_ROOT}/1/validate-token")) + .get(format!("{}/1/validate-token", root_or_default(root))) .header("Authorization", format!("Token {token}")) .header("User-Agent", USER_AGENT) .timeout(Duration::from_secs(15)) .send() .await .map_err(|e| e.to_string())?; - let body: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?; + let status = resp.status(); + // A bad token is a 200 with `valid:false` (some proxies answer 401); anything else is not + // this API talking. + if !status.is_success() && status != reqwest::StatusCode::UNAUTHORIZED { + return Err(format!( + "{status}: ListenBrainz at {} did not accept the request", + root_or_default(root) + )); + } + let body: serde_json::Value = resp.json().await.map_err(|_| { + format!( + "{status}: no ListenBrainz API answered at {} (is this the API address?)", + root_or_default(root) + ) + })?; if body.get("valid").and_then(|v| v.as_bool()) != Some(true) { let msg = body .get("message") @@ -154,13 +194,15 @@ fn emit_state( /// Connect with a user token pasted from ListenBrainz settings. Validates it first, so a typo /// is an error rather than a stored token that silently scrobbles nothing. -pub async fn connect(state: Arc, token: String) -> Result<(), String> { +pub async fn connect(state: Arc, token: String, url: String) -> Result<(), String> { let token = token.trim().to_owned(); - let username = validate(&token).await.map_err(|e| format!("ListenBrainz: {e}"))?; + let url = clean_root(&url)?; + let username = validate(&token, &url).await.map_err(|e| format!("ListenBrainz: {e}"))?; + state.db.set_setting("listenbrainz_url", &url); state.db.set_setting("listenbrainz_token", &token); state.db.set_setting("listenbrainz_username", &username); // Same task, same clock: the Last.fm scrobbler holds this token next to its session key. - state.lastfm.set_token(Some(token)); + state.lastfm.set_token(Some((url, token))); tracing::info!(user = %username, "listenbrainz connected"); emit_state(&state.app, true, Some(&username), None); Ok(()) @@ -169,6 +211,7 @@ pub async fn connect(state: Arc, token: String) -> Result<(), String> pub fn disconnect(state: &AppState) { state.db.set_setting("listenbrainz_token", ""); state.db.set_setting("listenbrainz_username", ""); + state.db.set_setting("listenbrainz_url", ""); state.lastfm.set_token(None); emit_state(&state.app, false, None, None); } @@ -183,9 +226,10 @@ pub fn status(state: &AppState) -> serde_json::Value { /// is connected or ListenBrainz didn't answer. pub async fn profile(state: &AppState) -> Option { let username = state.db.get_setting("listenbrainz_username").filter(|s| !s.is_empty())?; + let root = root_or_default(&state.db.get_setting("listenbrainz_url").unwrap_or_default()); // Listen counts are public: no token needed. let body: serde_json::Value = crate::http::client() - .get(format!("{API_ROOT}/1/user/{username}/listen-count")) + .get(format!("{root}/1/user/{username}/listen-count")) .header("User-Agent", USER_AGENT) .timeout(Duration::from_secs(15)) .send() @@ -197,7 +241,12 @@ pub async fn profile(state: &AppState) -> Option { let count = body.pointer("/payload/count").and_then(|v| v.as_u64()).unwrap_or(0); Some(Profile { username: username.clone(), - url: format!("https://listenbrainz.org/user/{username}/"), + // Custom instances serve the web UI from the same root as the API. + url: if root == DEFAULT_ROOT { + format!("https://listenbrainz.org/user/{username}/") + } else { + format!("{root}/user/{username}/") + }, listens: count, }) } @@ -245,6 +294,50 @@ mod tests { assert!(m["additional_info"].get("origin_url").is_none()); } + /// One-shot stand-in server: answers `body` to the first request and returns that request's + /// head (request line + headers). + async fn stand_in(body: &'static str) -> (String, tokio::task::JoinHandle) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let root = format!("http://{}/lb", listener.local_addr().unwrap()); + let task = tokio::spawn(async move { + let (mut sock, _) = listener.accept().await.unwrap(); + let mut buf = vec![0; 8192]; + let n = sock.read(&mut buf).await.unwrap(); + let head = String::from_utf8_lossy(&buf[..n]).to_string(); + let resp = format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ); + sock.write_all(resp.as_bytes()).await.unwrap(); + head + }); + (root, task) + } + + #[tokio::test] + async fn calls_go_to_the_root_they_are_given() { + let (root, req) = stand_in(r#"{"status":"ok"}"#).await; + assert!(submit(&root, "tok-custom", "single", serde_json::json!([])).await.is_ok()); + let head = req.await.unwrap().to_lowercase(); + assert!(head.starts_with("post /lb/1/submit-listens "), "{head}"); + assert!(head.contains("authorization: token tok-custom"), "{head}"); + + let (root, req) = stand_in(r#"{"valid":true,"user_name":"eve"}"#).await; + assert_eq!(validate("tok-custom", &root).await.unwrap(), "eve"); + assert!(req.await.unwrap().starts_with("GET /lb/1/validate-token ")); + } + + #[test] + fn custom_root_is_normalized_and_validated() { + assert_eq!(clean_root(" https://lb.example.com/ ").unwrap(), "https://lb.example.com"); + assert_eq!(clean_root("").unwrap(), ""); + assert_eq!(clean_root("http://10.0.0.2:8080/lb/").unwrap(), "http://10.0.0.2:8080/lb"); + for bad in ["lb.example.com", "https://", "https://h/p?x=1", "https://h/#f", "ftp://h"] { + assert!(clean_root(bad).is_err(), "{bad}"); + } + } + #[test] fn a_refused_listen_names_what_the_user_has_to_fix() { use reqwest::StatusCode; diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 6c5101642..33f72b9cf 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -1272,8 +1272,8 @@ export interface ListenBrainzState { } export const listenbrainzStatus = () => invoke('listenbrainz_status'); /** Validates the pasted user token and stores it. Rejects on a bad token or no network. */ -export const listenbrainzConnect = (token: string) => - invoke('listenbrainz_connect', { token }); +export const listenbrainzConnect = (token: string, url?: string) => + invoke('listenbrainz_connect', { token, url }); export const listenbrainzDisconnect = () => invoke('listenbrainz_disconnect'); export const onListenBrainzState = (cb: (s: ListenBrainzState) => void): Promise => listen('listenbrainz-state', (e) => cb(e.payload)); diff --git a/ui/src/lib/components/ScrobbleSettings.svelte b/ui/src/lib/components/ScrobbleSettings.svelte index 0720b2ed5..2b2349464 100644 --- a/ui/src/lib/components/ScrobbleSettings.svelte +++ b/ui/src/lib/components/ScrobbleSettings.svelte @@ -103,6 +103,8 @@ // (same as Last.fm's `watchLastfm`): a second subscription here would double the toasts. let lbProfile = $state(null); let lbToken = $state(''); + let lbCustom = $state(false); // the URL field only exists while this is on + let lbUrl = $state(''); $effect(() => { const name = listenbrainz.connected ? listenbrainz.username : null; lbProfile = null; @@ -111,11 +113,17 @@ .then((p) => listenbrainz.username === name && (lbProfile = p)) .catch(() => {}); }); + // Keep the token while connecting so a wrong address doesn't mean pasting it again. + $effect(() => { + if (listenbrainz.connected) lbToken = ''; + }); + // The button and the token field's Enter both go through here, so both get the checks. + const lbReady = $derived( + !!lbToken.trim() && !(lbCustom && !lbUrl.trim()) && !listenbrainz.connecting + ); function connectLb() { - const token = lbToken.trim(); - if (!token) return; - lbToken = ''; - connectListenBrainz(token); + if (!lbReady) return; + connectListenBrainz(lbToken.trim(), lbCustom ? lbUrl.trim() : ''); } const num = (n: number) => n.toLocaleString(currentLocale.id); const since = $derived( @@ -503,6 +511,19 @@ {t('settings.scrobbling.lb_open_settings')} + + {#if lbCustom} + + {/if}