Repository navigation
feat(scrobbling): custom ListenBrainz instance #644
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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<String, String> { | ||
| 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<String, String> { | ||
| async fn validate(token: &str, root: &str) -> Result<String, String> { | ||
| 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<AppState>, token: String) -> Result<(), String> { | ||
| pub async fn connect(state: Arc<AppState>, 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); | ||
|
Comment on lines
+199
to
+201
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Validate the URL beyond its scheme prefix.
Parse the value with
|
||
| 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<AppState>, 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<Profile> { | ||
| 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<Profile> { | |
| 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<String>) { | ||
| 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; | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Check the HTTP status before decoding the response body in
validate.validatedecodes the body as JSON before it checksstatus. A non-2xx response with a JSON body, such as a 401 or 500 from a self-hosted instance or a reverse proxy, passes through the decode step. The error text then comes from the body or from the generic "ListenBrainz rejected that token" fallback. A 5xx with{"valid":true,...}is unlikely, but the status is still ignored. The user also loses the status code in the message.Reject non-success statuses first. Include the status and a short body excerpt.
Proposed fix
ListenBrainz answers
validate-tokenwith a 200 andvalid:falsefor bad tokens. Some deployments return 401. The fix keeps 401 on the existing message path.Committable suggestion
Source: Learnings