From b8e078b3e8e0c41a1d19a0e228fab51f219bc519 Mon Sep 17 00:00:00 2001 From: zoltrons <18362677+zoltrons@users.noreply.github.com> Date: Sun, 8 Nov 2026 12:08:21 +0300 Subject: [PATCH 1/3] feat(scrobbling): custom ListenBrainz instance Lets users scrobble to a self-hosted ListenBrainz server. Settings gets a "Custom ListenBrainz instance" switch that reveals an API address field. Off keeps api.listenbrainz.org. The address is checked together with the token before it is used, so an existing token is never sent to a server that was not accepted. Co-Authored-By: Claude Sonnet 5.5 --- src-tauri/src/commands.rs | 8 ++- src-tauri/src/lib.rs | 1 + src-tauri/src/listenbrainz.rs | 67 ++++++++++++++++--- ui/src/lib/api.ts | 4 +- ui/src/lib/components/ScrobbleSettings.svelte | 19 +++++- ui/src/lib/listenbrainz.svelte.ts | 4 +- ui/src/lib/locales/en.json | 2 + 7 files changed, 88 insertions(+), 17 deletions(-) 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/lib.rs b/src-tauri/src/lib.rs index 1ab98c781..0f933cd6b 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -887,6 +887,7 @@ pub fn run() { // Scrobbler — one task, one clock for Last.fm + ListenBrainz. Each half parks until // its own credential exists (session key via the titlebar flow, user token via settings). + listenbrainz::set_root(&db.get_setting("listenbrainz_url").unwrap_or_default()); let lastfm = lastfm::spawn( handle.clone(), db.get_setting("lastfm_session_key").filter(|s| !s.is_empty()), diff --git a/src-tauri/src/listenbrainz.rs b/src-tauri/src/listenbrainz.rs index 20952866a..ff8f455ac 100644 --- a/src-tauri/src/listenbrainz.rs +++ b/src-tauri/src/listenbrainz.rs @@ -20,7 +20,32 @@ 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"; +/// Custom instance root (`listenbrainz_url` setting); empty = official server. Process-wide so the +/// scrobbler task, which only holds the token, reaches the same server as connect/profile. +static ROOT: std::sync::RwLock = std::sync::RwLock::new(String::new()); + +/// Trimmed, no trailing slash, http(s) only. Empty = official server. +fn clean_root(url: &str) -> Result { + let url = url.trim().trim_end_matches('/'); + if !url.is_empty() && !url.starts_with("http://") && !url.starts_with("https://") { + return Err("ListenBrainz: server URL must start with http:// or https://".into()); + } + Ok(url.to_owned()) +} + +pub fn set_root(url: &str) { + *ROOT.write().unwrap() = url.to_owned(); +} + +fn root_or_default(root: &str) -> String { + if root.is_empty() { DEFAULT_ROOT } else { root }.to_owned() +} + +fn api_root() -> String { + root_or_default(&ROOT.read().unwrap()) +} + const USER_AGENT: &str = concat!("Limusic/", env!("CARGO_PKG_VERSION"), " (https://github.com/SimoHypers/limusic)"); @@ -75,7 +100,7 @@ pub(crate) async fn submit( ) -> 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", api_root())) .header("Authorization", format!("Token {token}")) .header("User-Agent", USER_AGENT) .json(&body) @@ -116,16 +141,22 @@ 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(); + 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,9 +185,14 @@ 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)?; + // Validate against the typed URL, but only switch the shared root once it passes: the + // scrobbler must not send an existing token to a server that was never accepted. + let username = validate(&token, &url).await.map_err(|e| format!("ListenBrainz: {e}"))?; + set_root(&url); + 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. @@ -169,6 +205,8 @@ 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", ""); + set_root(""); state.lastfm.set_token(None); emit_state(&state.app, false, None, None); } @@ -185,7 +223,7 @@ pub async fn profile(state: &AppState) -> Option { let username = state.db.get_setting("listenbrainz_username").filter(|s| !s.is_empty())?; // 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!("{}/1/user/{username}/listen-count", api_root())) .header("User-Agent", USER_AGENT) .timeout(Duration::from_secs(15)) .send() @@ -197,7 +235,11 @@ 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: match api_root() { + r if r == DEFAULT_ROOT => format!("https://listenbrainz.org/user/{username}/"), + r => format!("{r}/user/{username}/"), + }, listens: count, }) } @@ -245,6 +287,13 @@ mod tests { assert!(m["additional_info"].get("origin_url").is_none()); } + #[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!(clean_root("lb.example.com").is_err()); + } + #[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..af2cd6b34 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; @@ -115,7 +117,7 @@ const token = lbToken.trim(); if (!token) return; lbToken = ''; - connectListenBrainz(token); + connectListenBrainz(token, lbCustom ? lbUrl.trim() : ''); } const num = (n: number) => n.toLocaleString(currentLocale.id); const since = $derived( @@ -503,6 +505,19 @@ {t('settings.scrobbling.lb_open_settings')} + + {#if lbCustom} + + {/if}