From 052112e900cfa66cb8055ff38020426edb7dea45 Mon Sep 17 00:00:00 2001 From: Sandro Date: Sun, 22 Nov 2026 13:04:24 +0100 Subject: [PATCH] feat: added listenbrainz scrobbling --- GLOSSARY.md | 18 +- README.md | 6 +- docs/adr/0003-stats-read-one-account.md | 13 + src-tauri/src/commands/library.rs | 8 +- src-tauri/src/commands/mixes.rs | 4 +- src-tauri/src/commands/mod.rs | 1 + src-tauri/src/commands/services.rs | 288 +++++++++ src-tauri/src/commands/settings.rs | 6 +- src-tauri/src/commands/stats.rs | 491 +++++++-------- src-tauri/src/events.rs | 85 +-- src-tauri/src/lib.rs | 30 +- src-tauri/src/mixes/store.rs | 4 +- src-tauri/src/persistence/settings.rs | 103 ++-- src-tauri/src/stats/lastfm.rs | 126 +--- src-tauri/src/stats/listenbrainz.rs | 314 ++++++++++ src-tauri/src/stats/mod.rs | 59 ++ src-tauri/src/stats/scrobble.rs | 205 +++++++ src-tauri/src/stats/store.rs | 498 ++++++++++++++-- src/components/layout/Sidebar.tsx | 34 +- src/lib/i18n/messages/de.ts | 98 ++- src/lib/i18n/messages/en.ts | 100 +++- src/lib/i18n/messages/es.ts | 99 +++- src/lib/i18n/messages/fr.ts | 99 +++- src/lib/ipc/commands.ts | 32 +- src/lib/ipc/events.ts | 2 +- src/lib/playback/engineBridge.ts | 23 +- src/lib/scrobbleServices.test.ts | 37 ++ src/lib/scrobbleServices.ts | 38 ++ src/lib/subsonic/types.ts | 63 +- src/stores/prefsStore.ts | 8 +- src/stores/uiStore.ts | 3 +- src/views/settings/SettingsView.tsx | 756 ++++++++++++++++-------- src/views/stats/StatsView.tsx | 31 +- 33 files changed, 2672 insertions(+), 1010 deletions(-) create mode 100644 docs/adr/0003-stats-read-one-account.md create mode 100644 src-tauri/src/commands/services.rs create mode 100644 src-tauri/src/stats/listenbrainz.rs create mode 100644 src-tauri/src/stats/scrobble.rs create mode 100644 src/lib/scrobbleServices.test.ts create mode 100644 src/lib/scrobbleServices.ts diff --git a/GLOSSARY.md b/GLOSSARY.md index 2555cdd..bbe8b14 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -25,5 +25,19 @@ The newest Plays of the signed-in account on this computer, newest first. Shown _Avoid_: Recently listened, listening history, history **Scrobble**: -A listening as recorded by Last.fm or Navidrome, which may come from any device or client. A Play becomes a Scrobble only if it is sent there. -_Avoid_: Play (for plays recorded elsewhere) +A listening as recorded by Last.fm, ListenBrainz or Navidrome, which may come from any device or client. A Play becomes a Scrobble only if it is sent there. +_Avoid_: Play (for plays recorded elsewhere), listen (ListenBrainz's own word for the same thing) + +**Scrobbling account**: +The Last.fm or ListenBrainz account Reverb sends Plays to itself. A ListenBrainz account can live on listenbrainz.org or on another server that speaks its API. +_Avoid_: Scrobble service, integration + +**Direct scrobbling**: +Sending Plays straight to the Scrobbling account instead of to Navidrome, which then hears nothing of them: no play count, no now-playing entry. +_Avoid_: Last.fm only + +### Stats + +**Stats source**: +The account whose Scrobbles Reverb imports for the Stats page and the mixes: the Scrobbling account by default, or a separate Last.fm or ListenBrainz account. There is one at a time, and its imported history goes when the Stats source becomes a different account. +_Avoid_: Integration, account (on its own) diff --git a/README.md b/README.md index 7e77bb5..185e5f2 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,11 @@ engine and a Roon-style **parametric EQ**. presets, auto/manual preamp headroom, click-free live adjustment while music plays - **OS integration** — media keys via MPRIS (Linux), SMTC (Windows), - Now Playing (macOS); scrobbling to Navidrome; queue restore across restarts + Now Playing (macOS); scrobbling to Navidrome, or straight to Last.fm or + ListenBrainz (including self-hosted and ListenBrainz-compatible servers); + queue restore across restarts +- **Stats** — listening history imported from Last.fm or ListenBrainz: the + account you scrobble to, or a separate one - **Settings** — output device selection, streaming quality (original / MP3 320/192/128 transcoding), ReplayGain (track/album, pre-amp, clip protection), scrobbling toggle, library rescan, accent color, startup view, diff --git a/docs/adr/0003-stats-read-one-account.md b/docs/adr/0003-stats-read-one-account.md new file mode 100644 index 0000000..7eb3f2d --- /dev/null +++ b/docs/adr/0003-stats-read-one-account.md @@ -0,0 +1,13 @@ +--- +status: accepted +--- + +# The Stats page reads one account, chosen in settings + +Scrobbling and stats each have an account of their own, Last.fm or ListenBrainz. By default the Stats page follows the Scrobbling account; turning that off gives it a separate one: another service, another account, or another ListenBrainz server. Stats never merge two accounts. The same Plays usually reach every service a listener uses, through Navidrome forwarding to each or a client scrobbling to both, so a merged history would count most listening twice. Telling the copies apart is guesswork: the services store slightly different timestamps and spellings for the same Play, and a merge that dropped near-duplicates would also drop real repeats. + +The two roles are separate because they often want different things. Plenty of scrobble servers (Maloja, Koito, multi-scrobbler) accept ListenBrainz submissions but hand no history back, so a listener who scrobbles to one still needs listenbrainz.org or Last.fm for stats. + +## Consequences + +Only one imported history is kept: `stats/.jsonl` plus its sync cursor in `sources.json`, belonging to one service, account and server. When the Stats source becomes a different account, that history is deleted and the new one imported from scratch. When there is briefly no Stats source, for example while switching "use the scrobbling account" off before connecting another, the history stays untouched, so switching back resumes instead of re-importing. Disconnecting the Scrobbling account hands it to stats when stats were following it, so dropping scrobbling never takes the imported history with it. If a merged view is ever wanted, it needs a deliberate deduplication rule rather than a concatenation. diff --git a/src-tauri/src/commands/library.rs b/src-tauri/src/commands/library.rs index 8b1dccc..dbece67 100644 --- a/src-tauri/src/commands/library.rs +++ b/src-tauri/src/commands/library.rs @@ -157,13 +157,13 @@ pub async fn library_get_artist_info( let mut biography = nav.biography.as_deref().and_then(clean_biography); let mut last_fm_url = nav.last_fm_url.clone(); - // Fall back to the user's Last.fm key (from stats sources) when the - // server has no biography. + // Fall back to the user's Last.fm key (from a connected Last.fm account) + // when the server has no biography. if biography.is_none() { - if let Some(config) = state.stats.config().lastfm { + if let Some(api_key) = state.stats.config().lastfm_api_key() { let client = reqwest::Client::new(); if let Ok(Some((raw, url))) = - crate::stats::lastfm::fetch_artist_bio(&client, &name, &config.api_key).await + crate::stats::lastfm::fetch_artist_bio(&client, &name, &api_key).await { biography = clean_biography(&raw); if last_fm_url.is_none() { diff --git a/src-tauri/src/commands/mixes.rs b/src-tauri/src/commands/mixes.rs index 4855783..ed1ef45 100644 --- a/src-tauri/src/commands/mixes.rs +++ b/src-tauri/src/commands/mixes.rs @@ -49,7 +49,7 @@ async fn ensure_mixes(app: &AppHandle, refresh: bool) -> Result<(Vec, bool) let now = Local::now(); let date = now.format("%Y-%m-%d").to_string(); let week = now.format("%G-W%V").to_string(); - let has_history = state.stats.config().lastfm.is_some_and(|c| c.track_count > 0); + let has_history = state.stats.config().active_history().is_some_and(|h| h.track_count > 0); let cached = state .mixes @@ -60,7 +60,7 @@ async fn ensure_mixes(app: &AppHandle, refresh: bool) -> Result<(Vec, bool) } let songs = fetch_library(&state.subsonic).await?; - let scrobbles = state.stats.all_scrobbles()?; + let scrobbles = state.stats.scrobbles()?; let profile = build_profile(songs, &scrobbles, now.timestamp()); let (library, unplayed) = profile.coverage(); log::info!( diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 943bad4..ab84e2d 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -4,5 +4,6 @@ pub mod library; pub mod mixes; pub mod play_history; pub mod player; +pub mod services; pub mod settings; pub mod stats; diff --git a/src-tauri/src/commands/services.rs b/src-tauri/src/commands/services.rs new file mode 100644 index 0000000..6cdf347 --- /dev/null +++ b/src-tauri/src/commands/services.rs @@ -0,0 +1,288 @@ +//! Connecting the accounts Reverb scrobbles to and imports stats from — one +//! per role, Last.fm or ListenBrainz each (see `stats::store`). + +use chrono::Utc; +use serde::Serialize; +use tauri::{AppHandle, State}; + +use crate::error::ReverbError; +use crate::state::AppState; +use crate::stats::store::{Account, SourcesConfig}; +use crate::stats::{ + lastfm, listenbrainz, listenbrainz_token_key, Role, Source, LASTFM_SECRET_KEY, + LASTFM_SESSION_KEY, +}; + +#[derive(Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct AccountStatus { + service: Source, + username: String, + /// The server's API root when it is not listenbrainz.org. + api_url: Option, + /// The Stats page can import from it (always so for Last.fm). + history: bool, +} + +impl From<&Account> for AccountStatus { + fn from(account: &Account) -> Self { + Self { + service: account.source(), + username: account.username().to_owned(), + api_url: account.api_url().map(str::to_owned), + history: account.has_history(), + } + } +} + +#[derive(Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct ServicesStatus { + scrobble: Option, + stats_same_as_scrobble: bool, + stats_account: Option, + /// The service the Stats page reads, after following the scrobbling + /// account; `None` while no account can supply history. + stats_source: Option, + track_count: u64, + last_sync_at: Option, + importing: bool, +} + +#[tauri::command] +pub fn services_get(state: State<'_, AppState>) -> ServicesStatus { + let config = state.stats.config(); + let history = config.active_history(); + ServicesStatus { + scrobble: config.scrobble.as_ref().map(Into::into), + stats_same_as_scrobble: config.stats_same_as_scrobble, + stats_account: config.stats_account.as_ref().map(Into::into), + stats_source: config.stats_source().map(|(_, a)| a.source()), + track_count: history.map_or(0, |h| h.track_count), + last_sync_at: history.and_then(|h| h.last_sync_at.clone()), + importing: state.stats.importing.load(std::sync::atomic::Ordering::Relaxed), + } +} + +/// Forget the secrets `account` keeps under `role`. +fn clear_secrets(state: &AppState, role: Role, account: &Account) { + match account { + Account::Lastfm { .. } if role == Role::Scrobble => { + state.keychain.clear_secret(LASTFM_SECRET_KEY); + state.keychain.clear_secret(LASTFM_SESSION_KEY); + } + // Last.fm's import needs only the API key, kept with the account. + Account::Lastfm { .. } => {} + Account::Listenbrainz { .. } => state.keychain.clear_secret(listenbrainz_token_key(role)), + } +} + +fn set_account(config: &mut SourcesConfig, role: Role, account: Account) { + match role { + Role::Scrobble => config.scrobble = Some(account), + Role::Stats => { + config.stats_account = Some(account); + config.stats_same_as_scrobble = false; + } + } +} + +/// Apply a change to the accounts, and sync the history when the Stats page +/// now reads another account than before. +fn apply( + app: &AppHandle, + state: &AppState, + mutate: impl FnOnce(&mut SourcesConfig), +) -> Result<(), ReverbError> { + let change = state.stats.update(mutate)?; + if change.stats_source_changed && change.config.stats_source().is_some() { + tauri::async_runtime::spawn(crate::commands::stats::run_import(app.clone())); + } + Ok(()) +} + +/// Connect a Last.fm account for `role`. Scrobbling needs the API account's +/// shared secret and the user's password, which is traded once for a session +/// key and never stored; the Stats page's import needs only the username and +/// API key. Everything is checked against Last.fm before anything is saved. +#[tauri::command] +pub async fn services_connect_lastfm( + role: Role, + username: String, + api_key: String, + shared_secret: Option, + password: Option, + app: AppHandle, + state: State<'_, AppState>, +) -> Result<(), ReverbError> { + let mut username = username.trim().to_owned(); + let api_key = api_key.trim().to_owned(); + if username.is_empty() || api_key.is_empty() { + return Err(ReverbError::State("Enter your Last.fm username and API key.".into())); + } + lastfm::check_credential_shape("API key", &api_key).map_err(ReverbError::State)?; + let client = reqwest::Client::new(); + let previous = state.stats.config().account(role).cloned(); + + match role { + Role::Scrobble => { + let secret = shared_secret.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()); + let password = password.filter(|p| !p.is_empty()); + let (Some(secret), Some(password)) = (secret, password) else { + return Err(ReverbError::State( + "Scrobbling needs the shared secret and your Last.fm password.".into(), + )); + }; + lastfm::check_credential_shape("shared secret", &secret) + .map_err(ReverbError::State)?; + let session = + lastfm::get_mobile_session(&client, &api_key, &secret, &username, &password) + .await + .map_err(ReverbError::State)?; + // The sign-in takes other spellings of the name; the import + // (should stats follow this account) wants Last.fm's own. + if let Some(canonical) = session.username.filter(|n| !n.is_empty()) { + username = canonical; + } + if let Some(previous) = &previous { + clear_secrets(&state, role, previous); + } + state.keychain.store_secret(LASTFM_SECRET_KEY, &secret)?; + state.keychain.store_secret(LASTFM_SESSION_KEY, &session.key)?; + } + Role::Stats => { + // One scrobble is enough to prove the name and key. + lastfm::fetch_recent(&client, &username, &api_key, 0, None, 1) + .await + .map_err(ReverbError::State)?; + if let Some(previous) = &previous { + clear_secrets(&state, role, previous); + } + } + } + + let account = Account::Lastfm { username, api_key }; + apply(&app, &state, |c| set_account(c, role, account)) +} + +/// Connect ListenBrainz, or a server that speaks its API, for `role`. +/// `api_url` is blank for listenbrainz.org; a blank `token` keeps the role's +/// current one, so the server can be changed without pasting it again. The +/// token is checked before anything is saved. +#[tauri::command] +pub async fn services_connect_listenbrainz( + role: Role, + token: Option, + api_url: Option, + app: AppHandle, + state: State<'_, AppState>, +) -> Result<(), ReverbError> { + let key = listenbrainz_token_key(role); + let previous = state.stats.config().account(role).cloned(); + let stored = || match previous { + Some(Account::Listenbrainz { .. }) => state.keychain.retrieve_secret(key), + _ => None, + }; + let token = token + .map(|t| t.trim().to_owned()) + .filter(|t| !t.is_empty()) + .or_else(stored) + .ok_or_else(|| ReverbError::State("Enter your ListenBrainz user token.".into()))?; + let api_root = listenbrainz::normalize_api_root(api_url.as_deref().unwrap_or_default()) + .map_err(ReverbError::State)?; + let client = reqwest::Client::new(); + let username = listenbrainz::validate_token(&client, &api_root, &token) + .await + .map_err(ReverbError::State)?; + + // Does this server hand listen history back? listenbrainz.org always does. + // For any other, asking for the listens after "now" costs nothing and + // answers it: an empty page means yes, an error means a server that only + // takes submissions. Imports also need to know whose listens to ask for. + let api_url = (api_root != listenbrainz::DEFAULT_API_ROOT).then(|| api_root.clone()); + let history = !username.is_empty() + && (api_url.is_none() + || listenbrainz::fetch_listens( + &client, + &api_root, + &token, + &username, + Utc::now().timestamp(), + ) + .await + .inspect_err(|e| log::info!("listenbrainz: no history to import from {api_root}: {e}")) + .is_ok()); + if role == Role::Stats && !history { + return Err(ReverbError::State( + "This server does not share listening history, so the Stats page cannot import \ + from it. It can still be scrobbled to." + .into(), + )); + } + + if let Some(previous @ Account::Lastfm { .. }) = &previous { + clear_secrets(&state, role, previous); + } + state.keychain.store_secret(key, &token)?; + let account = Account::Listenbrainz { username, api_url, history }; + apply(&app, &state, |c| set_account(c, role, account)) +} + +/// Disconnect `role`'s account. +/// +/// Dropping the scrobbling account never takes the Stats page's history with +/// it: when stats follow that account, it moves over to stats instead and +/// keeps importing. Disconnecting the stats account deletes its history. +#[tauri::command] +pub fn services_disconnect(role: Role, state: State<'_, AppState>) -> Result<(), ReverbError> { + let config = state.stats.config(); + match role { + Role::Scrobble => { + let Some(account) = config.scrobble.clone() else { return Ok(()) }; + let stats_follow = config.stats_same_as_scrobble && account.has_history(); + if stats_follow { + if let Some(old) = &config.stats_account { + clear_secrets(&state, Role::Stats, old); + } + if let Account::Listenbrainz { .. } = account { + let token = state.keychain.retrieve_secret(listenbrainz_token_key(role)); + if let Some(token) = token { + state.keychain.store_secret(listenbrainz_token_key(Role::Stats), &token)?; + } + } + } + clear_secrets(&state, role, &account); + state.stats.update(|c| { + let account = c.scrobble.take(); + if stats_follow { + c.stats_account = account; + c.stats_same_as_scrobble = false; + } + })?; + } + Role::Stats => { + if let Some(account) = &config.stats_account { + clear_secrets(&state, role, account); + } + state.stats.update(|c| { + c.stats_account = None; + // Its history goes too, unless the Stats page reads the + // scrobbling account's. + if !c.stats_same_as_scrobble { + c.history = None; + } + })?; + } + } + Ok(()) +} + +/// Whether the Stats page reads the scrobbling account or one of its own. +#[tauri::command] +pub fn services_set_stats_same_as_scrobble( + same: bool, + app: AppHandle, + state: State<'_, AppState>, +) -> Result<(), ReverbError> { + apply(&app, &state, |c| c.stats_same_as_scrobble = same) +} diff --git a/src-tauri/src/commands/settings.rs b/src-tauri/src/commands/settings.rs index ce34fc3..43484b3 100644 --- a/src-tauri/src/commands/settings.rs +++ b/src-tauri/src/commands/settings.rs @@ -55,11 +55,11 @@ pub fn settings_set_prefs( // Toggling scrobbling adjusts the server's now-playing display right away: // off clears the entry, on re-announces the current track. Switching - // Last.fm-only mode does the same thing for the same reason — turning it + // direct scrobbling does the same thing for the same reason — turning it // on stops reporting to the server, so the entry it left behind has to be // cleared rather than left to go stale. if old.scrobble_enabled != prefs.scrobble_enabled - || old.lastfm_scrobble_only != prefs.lastfm_scrobble_only + || old.direct_scrobble != prefs.direct_scrobble { let (track_id, position_ms, playback_state) = { let snapshot = state.player.lock().unwrap(); @@ -67,7 +67,7 @@ pub fn settings_set_prefs( }; if let Some(track_id) = track_id { let subsonic = state.subsonic.clone(); - let enabling = prefs.scrobble_enabled && !prefs.lastfm_scrobble_only; + let enabling = prefs.scrobble_enabled && !prefs.direct_scrobble; tauri::async_runtime::spawn(async move { if enabling { let _ = subsonic.scrobble(&track_id, false, None).await; diff --git a/src-tauri/src/commands/stats.rs b/src-tauri/src/commands/stats.rs index ddc802c..f4910ef 100644 --- a/src-tauri/src/commands/stats.rs +++ b/src-tauri/src/commands/stats.rs @@ -1,3 +1,9 @@ +//! The Stats page: importing the history of the account it reads, and the +//! numbers computed over it. The accounts themselves are connected in +//! `commands::services`. + +use std::future::Future; + use chrono::Utc; use serde::Serialize; use tauri::{AppHandle, Emitter, Manager, State}; @@ -5,35 +11,13 @@ use tauri::{AppHandle, Emitter, Manager, State}; use crate::error::ReverbError; use crate::state::AppState; use crate::stats::compute::{compute, StatsQuery, StatsRange, StatsSummary}; -use crate::stats::lastfm; -use crate::stats::store::LastfmConfig; - -#[derive(Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct LastfmStatus { - pub username: String, - pub track_count: u64, - pub last_sync_at: Option, - /// An authenticated session for submitting plays exists. Importing works - /// without one, so this is reported separately from being connected. - pub scrobbling: bool, -} - -/// Keychain entry names for the Last.fm scrobbling credentials. -pub const LASTFM_SECRET_KEY: &str = "lastfm-shared-secret"; -pub const LASTFM_SESSION_KEY: &str = "lastfm-session-key"; - -#[derive(Serialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct SourcesStatus { - pub lastfm: Option, - pub importing: bool, -} +use crate::stats::store::{Account, HistoryId}; +use crate::stats::{lastfm, listenbrainz, listenbrainz_token_key, Source}; #[derive(Serialize, Clone)] #[serde(rename_all = "camelCase")] struct ImportProgress { - source: &'static str, + source: Source, state: &'static str, // "running" | "done" | "error" imported: u64, total: Option, @@ -41,232 +25,201 @@ struct ImportProgress { } #[tauri::command] -pub fn stats_get_sources(state: State<'_, AppState>) -> SourcesStatus { - let config = state.stats.config(); - SourcesStatus { - lastfm: config.lastfm.map(|c| LastfmStatus { - username: c.username, - track_count: c.track_count, - last_sync_at: c.last_sync_at, - scrobbling: c.scrobbling, - }), - importing: state.stats.importing.load(std::sync::atomic::Ordering::Relaxed), - } +pub fn stats_import(app: AppHandle) { + tauri::async_runtime::spawn(run_import(app)); } -/// Connect Last.fm. `shared_secret` and `password` are optional and only -/// needed to enable *submitting* plays: with both, the password is traded once -/// for a session key (`auth.getMobileSession`) and then discarded — only the -/// session key and shared secret are kept, in the keychain. Without them the -/// source is import-only, exactly as before. +/// `from`/`to` are unix seconds and only used for the custom range; `to` is +/// exclusive. #[tauri::command] -pub async fn stats_configure_lastfm( - username: String, - api_key: String, - shared_secret: Option, - password: Option, +pub fn stats_get( + range: StatsRange, + from: Option, + to: Option, state: State<'_, AppState>, -) -> Result<(), ReverbError> { - // Validate credentials with a one-item probe before saving. - let client = reqwest::Client::new(); - lastfm::fetch_recent(&client, &username, &api_key, 0, None, 1) - .await - .map_err(ReverbError::State)?; - - // Authenticate for scrobbling when a secret and password were supplied. - // Done before anything is persisted, so a rejected password leaves the - // existing configuration untouched. - let secret = shared_secret.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()); - let password = password.filter(|p| !p.is_empty()); - let session = match (&secret, &password) { - (Some(secret), Some(password)) => { - lastfm::check_credential_shape("shared secret", secret) - .map_err(ReverbError::State)?; - Some( - lastfm::get_mobile_session(&client, &api_key, secret, &username, password) - .await - .map_err(ReverbError::State)?, - ) - } - _ => None, - }; - - let previous = state.stats.config().lastfm; - let changed_user = previous.as_ref().is_some_and(|c| c.username != username); - if changed_user { - state.stats.clear_source("lastfm"); - } - - // A new session replaces any stored one; a re-connect without a password - // keeps whatever was there, unless the account changed — those credentials - // belong to the old account. - let scrobbling = match (&session, &secret) { - (Some(session), Some(secret)) => { - state.keychain.store_secret(LASTFM_SECRET_KEY, secret)?; - state.keychain.store_secret(LASTFM_SESSION_KEY, session)?; - true - } - _ if changed_user => { - state.keychain.clear_secret(LASTFM_SECRET_KEY); - state.keychain.clear_secret(LASTFM_SESSION_KEY); - false - } - _ => previous.as_ref().is_some_and(|p| p.scrobbling), - }; +) -> Result { + let scrobbles = state.stats.scrobbles()?; + Ok(compute(&scrobbles, StatsQuery { range, from, to })) +} - state.stats.update_config(|c| { - let keep = previous.filter(|_| !changed_user); - c.lastfm = Some(LastfmConfig { - username, - api_key, - scrobbling, - last_sync_ts: keep.as_ref().map_or(0, |k| k.last_sync_ts), - last_sync_at: keep.as_ref().and_then(|k| k.last_sync_at.clone()), - track_count: keep.as_ref().map_or(0, |k| k.track_count), - }); - })?; - Ok(()) +/// One import, resolved from the account the Stats page reads. +enum Plan { + Lastfm { from: HistoryId, username: String, api_key: String, cursor: i64 }, + Listenbrainz { from: HistoryId, root: String, token: String, username: String, cursor: i64 }, } -/// Add scrobbling to an already-connected Last.fm source. `api_key` overrides -/// the stored one: a signature is only valid when the key and the shared secret -/// come from the *same* Last.fm application, so the pair has to be enterable -/// together — reusing a stored key the user cannot see invites a mismatch that -/// surfaces as an opaque "invalid method signature". The password is traded for -/// a session key and dropped. -#[tauri::command] -pub async fn stats_enable_lastfm_scrobbling( - shared_secret: String, - password: String, - api_key: Option, - state: State<'_, AppState>, -) -> Result<(), ReverbError> { - let config = state - .stats - .config() - .lastfm - .ok_or_else(|| ReverbError::State("Last.fm is not connected".into()))?; - let secret = shared_secret.trim(); - let api_key = api_key - .map(|k| k.trim().to_owned()) - .filter(|k| !k.is_empty()) - .unwrap_or(config.api_key); - lastfm::check_credential_shape("API key", &api_key).map_err(ReverbError::State)?; - lastfm::check_credential_shape("shared secret", secret).map_err(ReverbError::State)?; - let client = reqwest::Client::new(); - let session = - lastfm::get_mobile_session(&client, &api_key, secret, &config.username, &password) - .await - .map_err(ReverbError::State)?; - state.keychain.store_secret(LASTFM_SECRET_KEY, secret)?; - state.keychain.store_secret(LASTFM_SESSION_KEY, &session)?; - state.stats.update_config(|c| { - if let Some(lastfm) = c.lastfm.as_mut() { - lastfm.scrobbling = true; - // A replacement key has just proven itself against Last.fm; keep - // it so imports and scrobbles stay on one application. - lastfm.api_key = api_key; +impl Plan { + fn source(&self) -> Source { + match self { + Plan::Lastfm { .. } => Source::Lastfm, + Plan::Listenbrainz { .. } => Source::Listenbrainz, } - })?; - Ok(()) + } } -/// Drop the submission credentials, leaving the source connected for imports. -/// The counterpart to `stats_enable_lastfm_scrobbling` — without it the only -/// way to stop scrobbling would be a full disconnect, which also deletes the -/// imported history. -#[tauri::command] -pub fn stats_disable_lastfm_scrobbling(state: State<'_, AppState>) -> Result<(), ReverbError> { - state.keychain.clear_secret(LASTFM_SECRET_KEY); - state.keychain.clear_secret(LASTFM_SESSION_KEY); - state.stats.update_config(|c| { - if let Some(lastfm) = c.lastfm.as_mut() { - lastfm.scrobbling = false; +/// What to import, `Ok(None)` when the Stats page reads no account. +fn plan(state: &AppState) -> Result, (Source, String)> { + let config = state.stats.config(); + let Some((role, account)) = config.stats_source() else { return Ok(None) }; + // `update` keeps the history pointed at the stats source. + let Some(history) = config.active_history() else { return Ok(None) }; + let from = history.from.clone(); + let cursor = history.last_sync_ts; + Ok(Some(match account.clone() { + Account::Lastfm { username, api_key } => Plan::Lastfm { from, username, api_key, cursor }, + Account::Listenbrainz { username, api_url, .. } => { + let token = state.keychain.retrieve_secret(listenbrainz_token_key(role)).ok_or(( + Source::Listenbrainz, + "The ListenBrainz token is missing — connect ListenBrainz again".to_owned(), + ))?; + let root = api_url.unwrap_or_else(|| listenbrainz::DEFAULT_API_ROOT.to_owned()); + Plan::Listenbrainz { from, root, token, username, cursor } } - })?; - Ok(()) + })) } -#[tauri::command] -pub fn stats_disconnect(source: String, state: State<'_, AppState>) -> Result<(), ReverbError> { - if source == "lastfm" { - state.stats.clear_source("lastfm"); - state.keychain.clear_secret(LASTFM_SECRET_KEY); - state.keychain.clear_secret(LASTFM_SESSION_KEY); - state.stats.update_config(|c| c.lastfm = None)?; - } - Ok(()) +enum Outcome { + Done { imported: u64 }, + Failed { imported: u64, total: Option, message: String }, + /// The Stats page moved to another account mid-import. + Superseded, } -#[tauri::command] -pub fn stats_import(source: String, app: AppHandle) { - if source == "lastfm" { - tauri::async_runtime::spawn(run_lastfm_import(app)); +/// Pull new scrobbles into the history of the account the Stats page reads. +/// Imports take turns: one already running makes this a no-op — and if the +/// account changes under a running import, that import starts over for the +/// new one rather than finishing the old. +pub async fn run_import(app: AppHandle) { + let state = app.state::(); + let Some(guard) = state.stats.try_begin_import() else { return }; + let finished = loop { + let plan = match plan(&state) { + Ok(Some(plan)) => plan, + Ok(None) => break None, + Err((source, message)) => { + break Some((source, Outcome::Failed { imported: 0, total: None, message })) + } + }; + let source = plan.source(); + emit_progress( + &app, + ImportProgress { source, state: "running", imported: 0, total: None, message: None }, + ); + let outcome = match plan { + Plan::Lastfm { from, username, api_key, cursor } => { + import_lastfm(&app, &from, &username, &api_key, cursor).await + } + Plan::Listenbrainz { from, root, token, username, cursor } => { + import_listenbrainz(&app, &from, &root, &token, &username, cursor).await + } + }; + match outcome { + Outcome::Superseded => continue, + outcome => break Some((source, outcome)), + } + }; + // Release the lock BEFORE announcing completion, so the refetch the + // listeners fire cannot observe a stale importing=true. + drop(guard); + match finished { + None => {} + Some((source, Outcome::Done { imported })) => emit_progress( + &app, + ImportProgress { + source, + state: "done", + imported, + total: Some(imported), + message: None, + }, + ), + Some((source, Outcome::Failed { imported, total, message })) => { + let message = if imported > 0 { + format!("{message} — kept {imported} scrobbles; refresh to resume") + } else { + message + }; + emit_progress( + &app, + ImportProgress { source, state: "error", imported, total, message: Some(message) }, + ); + } + Some((_, Outcome::Superseded)) => unreachable!("superseded imports start over"), } } -/// `from`/`to` are unix seconds and only used for the custom range; `to` is -/// exclusive. -#[tauri::command] -pub fn stats_get( - range: StatsRange, - from: Option, - to: Option, - state: State<'_, AppState>, -) -> Result { - let scrobbles = state.stats.all_scrobbles()?; - Ok(compute(&scrobbles, StatsQuery { range, from, to })) -} - fn emit_progress(app: &AppHandle, progress: ImportProgress) { let _ = app.emit("stats:import", progress); } -/// Terminal error event. Callers drop the import guard first: listeners -/// refetch the importing flag immediately on receiving the event. -fn emit_import_error(app: &AppHandle, imported: u64, total: Option, message: String) { - let message = if imported > 0 { - format!("{message} — kept {imported} scrobbles; refresh to resume") - } else { - message - }; +/// Store one page and announce it. `Err` carries the outcome that ends the +/// import: a failed write, or the history having moved to another account. +fn save_page( + app: &AppHandle, + from: &HistoryId, + scrobbles: &[crate::stats::store::StatScrobble], + imported: &mut u64, + total: Option, +) -> Result<(), Outcome> { + let state = app.state::(); + match state.stats.append_history(from, scrobbles) { + Ok(true) => {} + Ok(false) => return Err(Outcome::Superseded), + Err(e) => { + return Err(Outcome::Failed { imported: *imported, total, message: e.to_string() }) + } + } + *imported += scrobbles.len() as u64; emit_progress( app, ImportProgress { - source: "lastfm", - state: "error", - imported, + source: from.source, + state: "running", + imported: *imported, total, - message: Some(message), + message: None, }, ); + Ok(()) +} + +fn finish(app: &AppHandle, from: &HistoryId, imported: u64) -> Outcome { + let state = app.state::(); + match state.stats.finish_sync(from, Utc::now().to_rfc3339()) { + Ok(()) => Outcome::Done { imported }, + Err(e) => Outcome::Failed { imported, total: None, message: e.to_string() }, + } } /// Incremental Last.fm import: fetch the [cursor, now] window oldest-first /// (highest page number first), persisting one page at a time and advancing /// the cursor after each — an interrupted import (flaky API, app quit) keeps /// everything fetched so far and the next run resumes instead of restarting. -pub async fn run_lastfm_import(app: AppHandle) { - let state = app.state::(); - let Some(guard) = state.stats.try_begin_import() else { return }; - let Some(config) = state.stats.config().lastfm else { return }; - +async fn import_lastfm( + app: &AppHandle, + from: &HistoryId, + username: &str, + api_key: &str, + from_ts: i64, +) -> Outcome { let client = reqwest::Client::new(); - let from_ts = config.last_sync_ts; // Fixed upper bound: keeps page numbering stable during the walk; anything // scrobbled after this moment is picked up by the next sync. let to_ts = Utc::now().timestamp(); let mut imported = 0u64; let mut newest_saved = from_ts; + let fetch = |page: u32| { + let client = &client; + retrying(format!("last.fm page {page}"), move || { + lastfm::fetch_recent(client, username, api_key, from_ts, Some(to_ts), page) + }) + }; // Page 1 reveals the window's page count; its content is reused when the // backwards walk arrives back at it. - let first = match fetch_recent_retrying(&client, &config, from_ts, to_ts, 1).await { + let first = match fetch(1).await { Ok(page) => page, - Err(message) => { - drop(guard); - return emit_import_error(&app, imported, None, message); - } + Err(message) => return Outcome::Failed { imported, total: None, message }, }; let total = Some(first.total); let total_pages = @@ -277,12 +230,9 @@ pub async fn run_lastfm_import(app: AppHandle) { let fetched = if page == 1 { first.take().expect("page 1 is visited exactly once") } else { - match fetch_recent_retrying(&client, &config, from_ts, to_ts, page).await { + match fetch(page).await { Ok(fetched) => fetched, - Err(message) => { - drop(guard); - return emit_import_error(&app, imported, total, message); - } + Err(message) => return Outcome::Failed { imported, total, message }, } }; @@ -292,76 +242,95 @@ pub async fn run_lastfm_import(app: AppHandle) { let mut scrobbles = fetched.scrobbles; scrobbles.retain(|s| s.ts > newest_saved); scrobbles.sort_by_key(|s| s.ts); - if let Some(newest) = scrobbles.last().map(|s| s.ts) { - if let Err(e) = state.stats.append("lastfm", &scrobbles) { - drop(guard); - return emit_import_error(&app, imported, total, e.to_string()); + if let Err(outcome) = save_page(app, from, &scrobbles, &mut imported, total) { + return outcome; } newest_saved = newest; - let count = scrobbles.len() as u64; - imported += count; - let _ = state.stats.update_config(|c| { - if let Some(lastfm) = c.lastfm.as_mut() { - lastfm.last_sync_ts = newest_saved; - lastfm.track_count += count; - } - }); } - - emit_progress( - &app, - ImportProgress { source: "lastfm", state: "running", imported, total, message: None }, - ); if page > 1 { // Stay well within Last.fm's rate limits. tokio_sleep(250).await; } } + finish(app, from, imported) +} + +/// Incremental ListenBrainz import. The API pages forward from a timestamp, so +/// this walks from the cursor towards now, persisting each page and advancing +/// the cursor after it — like the Last.fm import, an interrupted run keeps +/// what it fetched and the next one carries on from there. +async fn import_listenbrainz( + app: &AppHandle, + from: &HistoryId, + root: &str, + token: &str, + username: &str, + mut cursor: i64, +) -> Outcome { + let client = reqwest::Client::new(); + let mut imported = 0u64; + // The account's whole count is only the size of the job on a first import; + // later ones fetch an unknown slice of it. + let total = if cursor == 0 { + listenbrainz::fetch_listen_count(&client, root, token, username).await.ok() + } else { + None + }; + + loop { + let fetched = retrying("listenbrainz listens".to_owned(), || { + listenbrainz::fetch_listens(&client, root, token, username, cursor) + }) + .await; + let page = match fetched { + Ok(page) => page, + Err(message) => return Outcome::Failed { imported, total, message }, + }; - let _ = state.stats.update_config(|c| { - if let Some(lastfm) = c.lastfm.as_mut() { - lastfm.last_sync_at = Some(Utc::now().to_rfc3339()); + // Newest-first from the API; store chronologically. The ts filter + // guards against a server that ignores `min_ts` and sends the same + // newest listens every time — nothing new means the walk is over. + let mut scrobbles = page.scrobbles; + scrobbles.retain(|s| s.ts > cursor); + scrobbles.sort_by_key(|s| s.ts); + let Some(newest) = scrobbles.last().map(|s| s.ts) else { break }; + if let Err(outcome) = save_page(app, from, &scrobbles, &mut imported, total) { + return outcome; } - }); - // Release the lock BEFORE announcing completion, so the refetch the - // listeners fire cannot observe a stale importing=true. - drop(guard); - emit_progress( - &app, - ImportProgress { - source: "lastfm", - state: "done", - imported, - total: Some(imported), - message: None, - }, - ); + cursor = newest; + + // A short page is the last one. + if page.returned < listenbrainz::PAGE_SIZE { + break; + } + // ListenBrainz rate-limits per token; this stays far below it. + tokio_sleep(250).await; + } + finish(app, from, imported) } -/// Fetch one page, retrying transient failures (Last.fm's "backend service -/// failed" errors are routine on deep pagination) with growing backoff. -async fn fetch_recent_retrying( - client: &reqwest::Client, - config: &LastfmConfig, - from_ts: i64, - to_ts: i64, - page: u32, -) -> Result { +/// Run an import call, retrying transient failures with growing backoff. +/// Both services fail now and then on deep pagination (Last.fm's "backend +/// service failed", ListenBrainz's rate limit), and a retry is usually all it +/// takes. +async fn retrying(label: String, mut call: F) -> Result +where + F: FnMut() -> Fut, + Fut: Future>, +{ const ATTEMPTS: u32 = 4; let mut delay_ms = 1_000; for attempt in 1..=ATTEMPTS { - match lastfm::fetch_recent(client, &config.username, &config.api_key, from_ts, Some(to_ts), page) - .await - { - Ok(fetched) => return Ok(fetched), + match call().await { + Ok(value) => return Ok(value), Err(message) if attempt < ATTEMPTS => { - log::warn!("last.fm page {page} failed (attempt {attempt}/{ATTEMPTS}): {message}"); + log::warn!("{label} failed (attempt {attempt}/{ATTEMPTS}): {message}"); tokio_sleep(delay_ms).await; delay_ms *= 3; } Err(message) => { - log::warn!("last.fm import failed on page {page}: {message}"); + log::warn!("{label} failed, giving up: {message}"); return Err(message); } } diff --git a/src-tauri/src/events.rs b/src-tauri/src/events.rs index ccff1a1..ea3e3c4 100644 --- a/src-tauri/src/events.rs +++ b/src-tauri/src/events.rs @@ -10,9 +10,8 @@ use reverb_core::subsonic::SubsonicClient; use serde::Serialize; use tauri::{AppHandle, Emitter, Manager}; -use crate::commands::stats::{LASTFM_SECRET_KEY, LASTFM_SESSION_KEY}; use crate::state::PlayerSnapshot; -use crate::stats::lastfm::{self, ScrobbleTrack}; +use crate::stats::scrobble::{self, ScrobbleTrack}; /// One connection pool for the scrobble traffic, rather than a fresh client /// (and TLS handshake) per play. @@ -21,32 +20,10 @@ fn http_client() -> &'static reqwest::Client { CLIENT.get_or_init(reqwest::Client::new) } -/// Credentials for submitting plays straight to Last.fm. -struct LastfmTarget { - api_key: String, - secret: String, - session_key: String, -} - -/// Resolve the Last.fm-only target, or `None` to fall back to the Subsonic -/// server. Deliberately strict: the mode applies only when the preference is -/// on *and* a full set of submission credentials exists. A half-configured -/// Last.fm would otherwise route plays away from Navidrome and then drop -/// them, which is worse than ignoring the preference. -fn lastfm_target(app: &AppHandle) -> Option { - let state = app.state::(); - if !state.settings.get().prefs.lastfm_scrobble_only { - return None; - } - let config = state.stats.config().lastfm?; - if !config.scrobbling { - return None; - } - Some(LastfmTarget { - api_key: config.api_key, - secret: state.keychain.retrieve_secret(LASTFM_SECRET_KEY)?, - session_key: state.keychain.retrieve_secret(LASTFM_SESSION_KEY)?, - }) +/// Whether plays go straight to a service rather than to the Subsonic server +/// (see [`scrobble::direct_target`] for when that holds). +fn scrobbling_direct(app: &AppHandle) -> bool { + scrobble::direct_target(&app.state::()).is_some() } /// Feeds the server's live now-playing display (OpenSubsonic playbackReport): @@ -81,9 +58,9 @@ impl PlaybackReporter { if !enabled { return; } - // Last.fm-only mode means the server hears nothing at all — the + // Direct scrobbling means the server hears nothing at all — the // now-playing entry is part of what the user asked us not to send. - if lastfm_target(app).is_some() { + if scrobbling_direct(app) { return; } self.last_sent = Some(Instant::now()); @@ -298,60 +275,40 @@ fn forward( let scrobble_enabled = app.state::().settings.get().prefs.scrobble_enabled; if scrobble_enabled { - match lastfm_target(app) { + let state = app.state::(); + match scrobble::direct_target(&state) { Some(target) => { - // Last.fm-only: the server is skipped entirely. + // Straight to the service: the server is skipped + // entirely. // - // Last.fm identifies a play by artist *name*, and a + // The services identify a play by artist *name*, and a // joined credit ("A feat. B") matches no artist there, // so the preference trades the featured names for the // play landing on the main one. Only possible when the // server enumerated the credit; otherwise the full // string is all there is and it goes as-is. - let first_artist_only = app - .state::() - .settings - .get() - .prefs - .lastfm_scrobble_first_artist_only; + let first_artist_only = + state.settings.get().prefs.scrobble_first_artist_only; let artist = - lastfm::scrobble_artist(artist, first_artist, first_artist_only); + scrobble::scrobble_artist(artist, first_artist, first_artist_only); let Some(track) = ScrobbleTrack::from_parts(artist, title, album, duration_ms) else { log::debug!("no artist/title for {track_id}; nothing to scrobble"); return; }; - // `time_ms` is only computed for submissions; for a - // now-playing update Last.fm wants no timestamp. + // `time_ms` is only computed for submissions; a + // now-playing update carries no timestamp. let started_secs = time_ms.map(|ms| (ms / 1000) as i64); tauri::async_runtime::spawn(async move { let client = http_client(); let result = match started_secs { - Some(ts) => { - lastfm::scrobble( - client, - &target.api_key, - &target.secret, - &target.session_key, - &track, - ts, - ) - .await - } - None => { - lastfm::update_now_playing( - client, - &target.api_key, - &target.secret, - &target.session_key, - &track, - ) - .await - } + Some(ts) => target.scrobble(client, &track, ts).await, + None => target.now_playing(client, &track).await, }; if let Err(e) = result { - log::debug!("last.fm scrobble failed for {track_id}: {e}"); + let service = target.source().label(); + log::debug!("{service} scrobble failed for {track_id}: {e}"); } }); } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index fd1ac6f..fbc3624 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -39,14 +39,14 @@ pub fn run() { let config_dir = app.path().app_config_dir()?; let settings = SettingsStore::load(config_dir.clone())?; - // "Last.fm scrobble only" can be asked to last for one session - // only. Clear it here, before anything else reads preferences, so - // the engine and the webview both start from the reset value. + // Direct scrobbling can be asked to last for one session only. + // Clear it here, before anything else reads preferences, so the + // engine and the webview both start from the reset value. { let prefs = settings.get().prefs; - if prefs.lastfm_scrobble_only && prefs.lastfm_scrobble_only_reset_on_start { - if let Err(e) = settings.update(|s| s.prefs.lastfm_scrobble_only = false) { - log::warn!("could not reset Last.fm-only scrobbling: {e}"); + if prefs.direct_scrobble && prefs.direct_scrobble_reset_on_start { + if let Err(e) = settings.update(|s| s.prefs.direct_scrobble = false) { + log::warn!("could not reset direct scrobbling: {e}"); } } } @@ -116,13 +116,7 @@ pub fn run() { }) .await .ok(); - let configured = { - use tauri::Manager; - app_handle.state::().stats.config().lastfm.is_some() - }; - if configured { - commands::stats::run_lastfm_import(app_handle.clone()).await; - } + commands::stats::run_import(app_handle.clone()).await; commands::mixes::warm_up(app_handle).await; }); } @@ -192,11 +186,11 @@ pub fn run() { commands::eq::eq_load_preset, commands::eq::eq_delete_preset, commands::eq::eq_rename_preset, - commands::stats::stats_get_sources, - commands::stats::stats_configure_lastfm, - commands::stats::stats_enable_lastfm_scrobbling, - commands::stats::stats_disable_lastfm_scrobbling, - commands::stats::stats_disconnect, + commands::services::services_get, + commands::services::services_connect_lastfm, + commands::services::services_connect_listenbrainz, + commands::services::services_disconnect, + commands::services::services_set_stats_same_as_scrobble, commands::stats::stats_import, commands::stats::stats_get, commands::settings::settings_get, diff --git a/src-tauri/src/mixes/store.rs b/src-tauri/src/mixes/store.rs index 3748a51..27dbe31 100644 --- a/src-tauri/src/mixes/store.rs +++ b/src-tauri/src/mixes/store.rs @@ -20,8 +20,8 @@ pub struct MixSet { pub date: String, /// ISO week Discover was made for, `%G-W%V`. pub week: String, - /// Whether scrobbles fed them. Connecting Last.fm changes the picture - /// enough to rebuild before tomorrow. + /// Whether scrobbles fed them. Connecting Last.fm or ListenBrainz + /// changes the picture enough to rebuild before tomorrow. pub has_history: bool, pub mixes: Vec, } diff --git a/src-tauri/src/persistence/settings.rs b/src-tauri/src/persistence/settings.rs index e6a9c9d..422f591 100644 --- a/src-tauri/src/persistence/settings.rs +++ b/src-tauri/src/persistence/settings.rs @@ -84,23 +84,29 @@ pub struct Preferences { pub scrobble_enabled: bool, /// Percentage of a song to play before it counts as played (10–100). pub scrobble_at_percent: u32, - /// Send plays to Last.fm directly and leave the Subsonic server out of it - /// — no scrobble, no now-playing entry. Needs Last.fm scrobbling to be - /// connected; without a session key it is ignored (see `events.rs`), so - /// turning it on can never silently stop plays being recorded anywhere. - pub lastfm_scrobble_only: bool, - /// Clear `lastfm_scrobble_only` on the next launch, making it a + /// Send plays straight to the scrobbling account (Last.fm or + /// ListenBrainz) and leave the Subsonic server out of it — no scrobble, no + /// now-playing entry. Without a scrobbling account it is ignored (see + /// `stats::scrobble::direct_target`), so turning it on can never silently + /// stop plays being recorded anywhere. Was Last.fm-only before ListenBrainz + /// existed, hence the alias. + #[serde(alias = "lastfmScrobbleOnly")] + pub direct_scrobble: bool, + /// Clear `direct_scrobble` on the next launch, making it a /// this-session-only switch rather than a persistent mode. - pub lastfm_scrobble_only_reset_on_start: bool, - /// Show a `lastfm_scrobble_only` toggle in the sidebar. - pub lastfm_scrobble_only_pinned: bool, - /// Submit only the first credited artist to Last.fm, rather than the whole - /// credit string ("A feat. B"). Last.fm matches a play by artist name, and - /// a joined credit usually matches nothing — so this trades the featured + #[serde(alias = "lastfmScrobbleOnlyResetOnStart")] + pub direct_scrobble_reset_on_start: bool, + /// Show a `direct_scrobble` toggle in the sidebar. + #[serde(alias = "lastfmScrobbleOnlyPinned")] + pub direct_scrobble_pinned: bool, + /// Submit only the first credited artist rather than the whole credit + /// string ("A feat. B"). The services match a play by artist name, and a + /// joined credit usually matches nothing — so this trades the featured /// artists for the play landing on the main one. Applies to the plays - /// Reverb sends to Last.fm itself; what the Subsonic server forwards is the - /// server's own business (Navidrome has the same option). - pub lastfm_scrobble_first_artist_only: bool, + /// Reverb sends to a service itself; what the Subsonic server forwards is + /// the server's own business (Navidrome has the same option). + #[serde(alias = "lastfmScrobbleFirstArtistOnly")] + pub scrobble_first_artist_only: bool, /// Visible columns in the songs table (canonical ids, see frontend). pub song_columns: Vec, /// Playlist ids pinned by the user, in pin order. @@ -150,10 +156,10 @@ impl Default for Preferences { seek_bar_thickness: "medium".into(), scrobble_enabled: true, scrobble_at_percent: 80, - lastfm_scrobble_only: false, - lastfm_scrobble_only_reset_on_start: false, - lastfm_scrobble_only_pinned: false, - lastfm_scrobble_first_artist_only: false, + direct_scrobble: false, + direct_scrobble_reset_on_start: false, + direct_scrobble_pinned: false, + scrobble_first_artist_only: false, song_columns: vec!["artist".into(), "album".into(), "duration".into()], pinned_playlists: Vec::new(), show_pinned_in_sidebar: true, @@ -260,12 +266,12 @@ mod tests { /// that exists only on the TS side fails to persist without any error. /// Pin the names of the fields most recently added. #[test] - fn lastfm_only_prefs_survive_a_camel_case_round_trip() { + fn scrobbling_prefs_survive_a_camel_case_round_trip() { let raw = r#"{ - "lastfmScrobbleOnly": true, - "lastfmScrobbleOnlyResetOnStart": true, - "lastfmScrobbleOnlyPinned": true, - "lastfmScrobbleFirstArtistOnly": true, + "directScrobble": true, + "directScrobbleResetOnStart": true, + "directScrobblePinned": true, + "scrobbleFirstArtistOnly": true, "seekBarStyle": "wave", "seekBarAnimated": false, "seekBarThickness": "thick", @@ -273,10 +279,10 @@ mod tests { "checkForUpdates": false }"#; let prefs: Preferences = serde_json::from_str(raw).expect("camelCase names must match"); - assert!(prefs.lastfm_scrobble_only); - assert!(prefs.lastfm_scrobble_only_reset_on_start); - assert!(prefs.lastfm_scrobble_only_pinned); - assert!(prefs.lastfm_scrobble_first_artist_only); + assert!(prefs.direct_scrobble); + assert!(prefs.direct_scrobble_reset_on_start); + assert!(prefs.direct_scrobble_pinned); + assert!(prefs.scrobble_first_artist_only); assert_eq!(prefs.seek_bar_style, "wave"); assert!(!prefs.seek_bar_animated); assert_eq!(prefs.seek_bar_thickness, "thick"); @@ -285,10 +291,10 @@ mod tests { // ...and come back out under the same names. let back = serde_json::to_value(&prefs).unwrap(); - assert_eq!(back["lastfmScrobbleOnly"], serde_json::json!(true)); - assert_eq!(back["lastfmScrobbleOnlyResetOnStart"], serde_json::json!(true)); - assert_eq!(back["lastfmScrobbleOnlyPinned"], serde_json::json!(true)); - assert_eq!(back["lastfmScrobbleFirstArtistOnly"], serde_json::json!(true)); + assert_eq!(back["directScrobble"], serde_json::json!(true)); + assert_eq!(back["directScrobbleResetOnStart"], serde_json::json!(true)); + assert_eq!(back["directScrobblePinned"], serde_json::json!(true)); + assert_eq!(back["scrobbleFirstArtistOnly"], serde_json::json!(true)); assert_eq!(back["seekBarStyle"], serde_json::json!("wave")); assert_eq!(back["seekBarAnimated"], serde_json::json!(false)); assert_eq!(back["seekBarThickness"], serde_json::json!("thick")); @@ -296,6 +302,33 @@ mod tests { assert_eq!(back["checkForUpdates"], serde_json::json!(false)); } + /// Before ListenBrainz, direct scrobbling was "Last.fm only". A settings + /// file from then has to come through with the same switches set (the + /// Last.fm connection itself carries over in `stats::store`) — read + /// through the whole `Settings`, since prefs are flattened into it and + /// that is the path a real file takes. + #[test] + fn last_fm_only_settings_become_direct_scrobbling() { + let raw = r#"{ + "serverUrl": "https://music.example.com/", + "lastfmScrobbleOnly": true, + "lastfmScrobbleOnlyResetOnStart": true, + "lastfmScrobbleOnlyPinned": true, + "lastfmScrobbleFirstArtistOnly": true + }"#; + let settings: Settings = serde_json::from_str(raw).expect("old names must still parse"); + let prefs = settings.prefs; + assert!(prefs.direct_scrobble); + assert!(prefs.direct_scrobble_reset_on_start); + assert!(prefs.direct_scrobble_pinned); + assert!(prefs.scrobble_first_artist_only); + + // Written back under the new names only. + let back = serde_json::to_value(Settings { prefs, ..Settings::default() }).unwrap(); + assert_eq!(back["directScrobble"], serde_json::json!(true)); + assert!(back.get("lastfmScrobbleOnly").is_none()); + } + /// Every `settings.json.bak-*` file in `dir`. fn backups(dir: &Path) -> Vec { let mut found: Vec<_> = fs::read_dir(dir) @@ -373,9 +406,9 @@ mod tests { assert_eq!(s.prefs.accent, "coral"); assert_eq!(s.prefs.streaming_format, "raw"); assert!(s.prefs.scrobble_enabled); - assert!(!s.prefs.lastfm_scrobble_only); - assert!(!s.prefs.lastfm_scrobble_only_reset_on_start); - assert!(!s.prefs.lastfm_scrobble_only_pinned); + assert!(!s.prefs.direct_scrobble); + assert!(!s.prefs.direct_scrobble_reset_on_start); + assert!(!s.prefs.direct_scrobble_pinned); assert!(s.prefs.audio_device.is_none()); assert!(s.prefs.check_for_updates, "update checks default to on"); // And the new shape round-trips. diff --git a/src-tauri/src/stats/lastfm.rs b/src-tauri/src/stats/lastfm.rs index 5371e20..ce36a87 100644 --- a/src-tauri/src/stats/lastfm.rs +++ b/src-tauri/src/stats/lastfm.rs @@ -4,6 +4,7 @@ use serde_json::Value; +use super::scrobble::ScrobbleTrack; use super::store::StatScrobble; const API_ROOT: &str = "https://ws.audioscrobbler.com/2.0/"; @@ -153,58 +154,6 @@ use std::fmt::Write as _; use md5::{Digest, Md5}; -/// One play, as Last.fm identifies it. `track` and `artist` are the only -/// fields it requires; a submission missing either is rejected outright. -#[derive(Debug, Clone)] -pub struct ScrobbleTrack { - pub artist: String, - pub track: String, - pub album: Option, - /// Track length in seconds; omitted when the engine never learned it. - pub duration_secs: Option, -} - -/// The artist name to submit for a play. -/// -/// Last.fm identifies a play by artist *name*, so a joined credit like -/// "A feat. B" usually matches no artist there and the play is filed under -/// nothing useful. `first_artist_only` trades the featured names for a play -/// that lands on the main artist — which is only possible where the server -/// enumerated the credit, so without a first artist the full string still goes. -pub fn scrobble_artist( - artist: Option, - first_artist: Option, - first_artist_only: bool, -) -> Option { - if !first_artist_only { - return artist; - } - // A blank first artist would otherwise beat a perfectly good credit and - // lose the scrobble entirely (`from_parts` drops empty artists). - first_artist.filter(|name| !name.trim().is_empty()).or(artist) -} - -impl ScrobbleTrack { - /// Build a submission from the engine's (all-optional) track metadata. - /// Returns `None` when artist or title is missing — Last.fm would only - /// reject it, and a play it cannot attribute is not worth a round trip. - pub fn from_parts( - artist: Option, - title: Option, - album: Option, - duration_ms: u64, - ) -> Option { - let artist = artist.filter(|s| !s.trim().is_empty())?; - let track = title.filter(|s| !s.trim().is_empty())?; - Some(Self { - artist, - track, - album: album.filter(|s| !s.trim().is_empty()), - duration_secs: (duration_ms > 0).then_some(duration_ms / 1000), - }) - } -} - fn md5_hex(input: &str) -> String { let digest = Md5::digest(input.as_bytes()); let mut out = String::with_capacity(32); @@ -286,6 +235,13 @@ pub async fn verify_key_pair( post_signed(client, params, secret).await.map(|_| ()) } +/// A scrobbling session: the key, and the account name as Last.fm spells it +/// (the sign-in accepts other spellings, the import does not). +pub struct Session { + pub key: String, + pub username: Option, +} + /// Trade a username and password for a long-lived session key /// (`auth.getMobileSession`). The password is used for this one call and never /// stored — the session key it returns is what gets kept. @@ -295,7 +251,7 @@ pub async fn get_mobile_session( secret: &str, username: &str, password: &str, -) -> Result { +) -> Result { let params = vec![ ("method", "auth.getMobileSession".to_string()), ("username", username.to_string()), @@ -322,10 +278,12 @@ pub async fn get_mobile_session( } Err(message) => return Err(message), }; - body["session"]["key"] + let key = body["session"]["key"] .as_str() .map(str::to_owned) - .ok_or_else(|| "Last.fm did not return a session key".to_string()) + .ok_or_else(|| "Last.fm did not return a session key".to_string())?; + let username = body["session"]["name"].as_str().map(str::to_owned); + Ok(Session { key, username }) } /// Announce the track as now playing. Last.fm expires the entry on its own @@ -384,42 +342,6 @@ pub async fn scrobble( mod tests { use super::*; - #[test] - fn scrobble_artist_sends_the_whole_credit_by_default() { - let artist = || Some("A feat. B".to_owned()); - let first = || Some("A".to_owned()); - assert_eq!(scrobble_artist(artist(), first(), false).as_deref(), Some("A feat. B")); - } - - #[test] - fn scrobble_artist_sends_only_the_first_when_asked() { - let artist = || Some("A feat. B".to_owned()); - assert_eq!( - scrobble_artist(artist(), Some("A".to_owned()), true).as_deref(), - Some("A") - ); - } - - #[test] - fn scrobble_artist_falls_back_when_the_first_artist_is_unknown() { - // Servers without the OpenSubsonic artists extension send the credit as - // one opaque string: there is nothing to take the first artist from, and - // guessing at separators would split "Simon & Garfunkel". - let artist = || Some("Simon & Garfunkel".to_owned()); - assert_eq!( - scrobble_artist(artist(), None, true).as_deref(), - Some("Simon & Garfunkel") - ); - // A blank one must not win, or the play is dropped rather than filed. - assert_eq!( - scrobble_artist(artist(), Some(" ".to_owned()), true).as_deref(), - Some("Simon & Garfunkel") - ); - // Nothing at all stays nothing, whichever way the preference is set. - assert_eq!(scrobble_artist(None, None, true), None); - assert_eq!(scrobble_artist(None, None, false), None); - } - #[test] fn parses_recent_tracks_with_quirks() { // Now-playing entry (no date), string numbers, "#text" fields. @@ -503,26 +425,4 @@ mod tests { fn md5_hex_matches_a_known_digest() { assert_eq!(md5_hex("sesamec19b2d"), "26719a1196d2a940705a59634eb18eab"); } - - #[test] - fn submissions_need_an_artist_and_a_title() { - assert!(ScrobbleTrack::from_parts(None, Some("T".into()), None, 0).is_none()); - assert!(ScrobbleTrack::from_parts(Some("A".into()), None, None, 0).is_none()); - // Whitespace-only metadata is as unusable as none at all. - assert!(ScrobbleTrack::from_parts(Some(" ".into()), Some("T".into()), None, 0).is_none()); - } - - #[test] - fn submissions_carry_album_and_duration_when_known() { - let track = - ScrobbleTrack::from_parts(Some("A".into()), Some("T".into()), Some("Al".into()), 245_000) - .expect("artist and title are present"); - assert_eq!(track.album.as_deref(), Some("Al")); - assert_eq!(track.duration_secs, Some(245)); - // An unknown duration is omitted rather than sent as zero. - let unknown = ScrobbleTrack::from_parts(Some("A".into()), Some("T".into()), None, 0) - .expect("artist and title are present"); - assert_eq!(unknown.duration_secs, None); - assert_eq!(unknown.album, None); - } } diff --git a/src-tauri/src/stats/listenbrainz.rs b/src-tauri/src/stats/listenbrainz.rs new file mode 100644 index 0000000..ce915b0 --- /dev/null +++ b/src-tauri/src/stats/listenbrainz.rs @@ -0,0 +1,314 @@ +//! ListenBrainz: importing listens for the stats page and submitting Plays. +//! +//! Every call authenticates with a user token (`Authorization: Token …`) from +//! the account's settings page — there is no password exchange or request +//! signing as with Last.fm. The API root is configurable, because servers +//! other than listenbrainz.org speak the same protocol: a self-hosted +//! ListenBrainz, or scrobble servers such as Maloja and Koito that accept +//! ListenBrainz submissions under a path of their own. Those often accept +//! submissions without serving listen history back, which is why importing is +//! probed separately from validating the token. + +use std::time::Duration; + +use reqwest::Url; +use serde_json::{json, Value}; + +use super::scrobble::ScrobbleTrack; +use super::store::StatScrobble; + +pub const DEFAULT_API_ROOT: &str = "https://api.listenbrainz.org"; +/// The most listens one `GET …/listens` returns (`MAX_ITEMS_PER_GET`). +pub const PAGE_SIZE: usize = 1000; +/// Self-hosted servers can sit behind slow links, but a request that has not +/// answered in this long is not going to. +const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); + +/// Turn whatever the user pasted into an API root: blank means +/// listenbrainz.org, a missing scheme means https (as for the server address +/// at sign-in), and the version or endpoint suffix some guides quote along with +/// the address (`…/1`, `…/1/submit-listens`) is dropped, since every call +/// appends its own. The result has no trailing slash. +pub fn normalize_api_root(raw: &str) -> Result { + let raw = raw.trim(); + if raw.is_empty() { + return Ok(DEFAULT_API_ROOT.to_owned()); + } + let with_scheme = if raw.contains("://") { raw.to_owned() } else { format!("https://{raw}") }; + let url = Url::parse(&with_scheme) + .map_err(|_| format!("“{raw}” is not a valid address."))?; + if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() { + return Err(format!("“{raw}” is not an http(s) address.")); + } + let mut root = url.as_str().split(['?', '#']).next().unwrap_or_default().to_owned(); + loop { + let trimmed = root.trim_end_matches('/'); + let stripped = ["/1/submit-listens", "/1/validate-token", "/1"] + .iter() + .find_map(|suffix| trimmed.strip_suffix(suffix)); + match stripped { + Some(shorter) => root = shorter.to_owned(), + None => { + root = trimmed.to_owned(); + break; + } + } + } + Ok(root) +} + +/// `{api_root}/1/{segments…}`, with each segment percent-encoded — a user name +/// can hold characters that mean something in a path. +fn endpoint(api_root: &str, segments: &[&str]) -> Result { + let mut url = Url::parse(api_root).map_err(|e| format!("Invalid ListenBrainz address: {e}"))?; + url.path_segments_mut() + .map_err(|_| "Invalid ListenBrainz address".to_owned())? + .pop_if_empty() + .push("1") + .extend(segments); + Ok(url) +} + +fn authorized(request: reqwest::RequestBuilder, token: &str) -> reqwest::RequestBuilder { + request.header("Authorization", format!("Token {token}")).timeout(REQUEST_TIMEOUT) +} + +/// The parsed body of a successful call, or the server's own explanation of a +/// failed one (`{"code": 401, "error": "…"}`), falling back to the HTTP status. +async fn read_body(response: Result) -> Result { + let response = response.map_err(|e| format!("ListenBrainz request failed: {e}"))?; + let status = response.status(); + let body: Value = response.json().await.unwrap_or(Value::Null); + if status.is_success() { + return Ok(body); + } + let detail = body["error"].as_str().or_else(|| body["message"].as_str()); + Err(match detail { + Some(detail) => format!("ListenBrainz: {detail}"), + None => format!("ListenBrainz answered {status}"), + }) +} + +/// Check a token and learn whose it is. ListenBrainz answers an unknown token +/// with 200 and `"valid": false` rather than an error status. +pub async fn validate_token( + client: &reqwest::Client, + api_root: &str, + token: &str, +) -> Result { + let url = endpoint(api_root, &["validate-token"])?; + let body = read_body(authorized(client.get(url), token).send().await).await?; + if body["valid"].as_bool() != Some(true) { + return Err("ListenBrainz did not accept this user token. Copy it again from your \ + ListenBrainz settings page." + .to_owned()); + } + // Servers that only mimic the API may not name the user; imports need the + // name, submissions do not. + Ok(body["user_name"].as_str().unwrap_or_default().to_owned()) +} + +/// The submission body: `playing_now` without a timestamp, `single` with the +/// unix second the play started. +fn listen_payload(track: &ScrobbleTrack, listened_at: Option) -> Value { + let mut additional_info = json!({ + "media_player": "Reverb", + "submission_client": "Reverb", + "submission_client_version": env!("CARGO_PKG_VERSION"), + }); + if let Some(secs) = track.duration_secs { + additional_info["duration_ms"] = json!(secs * 1000); + } + let mut metadata = json!({ + "artist_name": track.artist, + "track_name": track.track, + "additional_info": additional_info, + }); + if let Some(album) = &track.album { + metadata["release_name"] = json!(album); + } + let mut listen = json!({ "track_metadata": metadata }); + if let Some(ts) = listened_at { + listen["listened_at"] = json!(ts.max(0)); + } + json!({ + "listen_type": if listened_at.is_some() { "single" } else { "playing_now" }, + "payload": [listen], + }) +} + +/// Submit a finished play (`listened_at` = when it started) or, with `None`, +/// announce it as now playing. +pub async fn submit( + client: &reqwest::Client, + api_root: &str, + token: &str, + track: &ScrobbleTrack, + listened_at: Option, +) -> Result<(), String> { + let url = endpoint(api_root, &["submit-listens"])?; + let request = authorized(client.post(url), token).json(&listen_payload(track, listened_at)); + read_body(request.send().await).await.map(|_| ()) +} + +#[derive(Debug)] +pub struct ListensPage { + /// The usable listens, in whatever order the server sent them. + pub scrobbles: Vec, + /// How many listens the server returned, usable or not. A page shorter + /// than requested is the last one. + pub returned: usize, +} + +/// The oldest `PAGE_SIZE` listens *after* `min_ts` (exclusive). With `min_ts` +/// set ListenBrainz walks forward in time, so an import can page from its +/// cursor towards now and stop anywhere without leaving a gap behind. +pub async fn fetch_listens( + client: &reqwest::Client, + api_root: &str, + token: &str, + user: &str, + min_ts: i64, +) -> Result { + let mut url = endpoint(api_root, &["user", user, "listens"])?; + url.query_pairs_mut() + .append_pair("min_ts", &min_ts.max(0).to_string()) + .append_pair("count", &PAGE_SIZE.to_string()); + parse_listens(&read_body(authorized(client.get(url), token).send().await).await?) +} + +/// The account's total number of listens, for the import's progress display. +pub async fn fetch_listen_count( + client: &reqwest::Client, + api_root: &str, + token: &str, + user: &str, +) -> Result { + let url = endpoint(api_root, &["user", user, "listen-count"])?; + let body = read_body(authorized(client.get(url), token).send().await).await?; + body["payload"]["count"].as_u64().ok_or_else(|| "ListenBrainz sent no listen count".into()) +} + +fn parse_listens(body: &Value) -> Result { + let Some(listens) = body["payload"]["listens"].as_array() else { + return Err("ListenBrainz sent no listens".into()); + }; + let text = |value: &Value| { + value.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned) + }; + let scrobbles = listens + .iter() + .filter_map(|listen| { + let ts = listen["listened_at"] + .as_i64() + .or_else(|| listen["listened_at"].as_str()?.parse().ok())?; + let metadata = &listen["track_metadata"]; + Some(StatScrobble { + ts, + artist: text(&metadata["artist_name"])?, + track: text(&metadata["track_name"])?, + album: text(&metadata["release_name"]), + }) + }) + .collect(); + Ok(ListensPage { scrobbles, returned: listens.len() }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blank_api_root_means_listenbrainz_org() { + assert_eq!(normalize_api_root(" ").unwrap(), DEFAULT_API_ROOT); + } + + #[test] + fn api_root_drops_trailing_slashes_and_endpoint_suffixes() { + let cases = [ + ("https://api.listenbrainz.org/", "https://api.listenbrainz.org"), + ("https://api.listenbrainz.org/1/", "https://api.listenbrainz.org"), + ( + "https://maloja.example/apis/listenbrainz/1/submit-listens", + "https://maloja.example/apis/listenbrainz", + ), + ("http://192.168.1.5:42010/apis/listenbrainz", "http://192.168.1.5:42010/apis/listenbrainz"), + ("koito.example/apis/listenbrainz/", "https://koito.example/apis/listenbrainz"), + ]; + for (raw, root) in cases { + assert_eq!(normalize_api_root(raw).unwrap(), root, "{raw}"); + } + } + + #[test] + fn api_root_rejects_what_is_not_a_web_address() { + assert!(normalize_api_root("ftp://example.com").is_err()); + assert!(normalize_api_root("https://").is_err()); + } + + #[test] + fn endpoints_append_to_a_root_with_a_path_and_encode_segments() { + let url = endpoint("https://maloja.example/apis/listenbrainz", &["submit-listens"]).unwrap(); + assert_eq!(url.as_str(), "https://maloja.example/apis/listenbrainz/1/submit-listens"); + let url = endpoint(DEFAULT_API_ROOT, &["user", "a b/c", "listens"]).unwrap(); + assert_eq!(url.as_str(), "https://api.listenbrainz.org/1/user/a%20b%2Fc/listens"); + } + + fn track() -> ScrobbleTrack { + ScrobbleTrack { + artist: "Artist".into(), + track: "Song".into(), + album: Some("Album".into()), + duration_secs: Some(245), + } + } + + #[test] + fn a_finished_play_is_a_single_listen_with_its_start_time() { + let body = listen_payload(&track(), Some(1_700_000_000)); + assert_eq!(body["listen_type"], "single"); + let listen = &body["payload"][0]; + assert_eq!(listen["listened_at"], 1_700_000_000); + assert_eq!(listen["track_metadata"]["artist_name"], "Artist"); + assert_eq!(listen["track_metadata"]["track_name"], "Song"); + assert_eq!(listen["track_metadata"]["release_name"], "Album"); + assert_eq!(listen["track_metadata"]["additional_info"]["duration_ms"], 245_000); + } + + #[test] + fn now_playing_carries_no_timestamp_and_omits_unknowns() { + let bare = ScrobbleTrack { album: None, duration_secs: None, ..track() }; + let body = listen_payload(&bare, None); + assert_eq!(body["listen_type"], "playing_now"); + let listen = &body["payload"][0]; + assert!(listen.get("listened_at").is_none()); + assert!(listen["track_metadata"].get("release_name").is_none()); + assert!(listen["track_metadata"]["additional_info"].get("duration_ms").is_none()); + } + + #[test] + fn parses_listens_and_skips_unusable_ones() { + let body: Value = serde_json::from_str( + r#"{"payload": {"count": 3, "listens": [ + {"listened_at": 1700000100, + "track_metadata": {"artist_name": "B", "track_name": "Two", "release_name": "Alb"}}, + {"listened_at": 1700000050, + "track_metadata": {"artist_name": "", "track_name": "No artist"}}, + {"listened_at": 1700000000, + "track_metadata": {"artist_name": "A", "track_name": "One"}} + ]}}"#, + ) + .unwrap(); + let page = parse_listens(&body).unwrap(); + assert_eq!(page.returned, 3, "the short-page check counts what was sent"); + assert_eq!(page.scrobbles.len(), 2); + assert_eq!(page.scrobbles[0].album.as_deref(), Some("Alb")); + assert_eq!(page.scrobbles[1].ts, 1_700_000_000); + assert_eq!(page.scrobbles[1].album, None); + } + + #[test] + fn a_body_without_listens_is_an_error() { + assert!(parse_listens(&json!({"code": 404, "error": "Cannot find user"})).is_err()); + } +} diff --git a/src-tauri/src/stats/mod.rs b/src-tauri/src/stats/mod.rs index 78d5602..0847e90 100644 --- a/src-tauri/src/stats/mod.rs +++ b/src-tauri/src/stats/mod.rs @@ -1,3 +1,62 @@ pub mod compute; pub mod lastfm; +pub mod listenbrainz; +pub mod scrobble; pub mod store; + +use serde::{Deserialize, Serialize}; + +/// A listening service Reverb can send Plays to and import Scrobbles from. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Source { + Lastfm, + Listenbrainz, +} + +impl Source { + /// The wire and file name ("lastfm", "listenbrainz"). + pub fn id(self) -> &'static str { + match self { + Source::Lastfm => "lastfm", + Source::Listenbrainz => "listenbrainz", + } + } + + /// The service's own spelling, for messages shown to the user. + pub fn label(self) -> &'static str { + match self { + Source::Lastfm => "Last.fm", + Source::Listenbrainz => "ListenBrainz", + } + } +} + +/// What an account is connected for. Each role has an account of its own, so +/// plays can go to one service (or server) while the Stats page reads another. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Role { + /// Takes Plays when direct scrobbling is on. + Scrobble, + /// Supplies the history for the Stats page and the mixes. + Stats, +} + +/// Keychain entry names for the accounts' secrets. The scrobbling ones keep +/// the names they had when Last.fm was the only service, so connections made +/// back then still find their session. +pub const LASTFM_SECRET_KEY: &str = "lastfm-shared-secret"; +pub const LASTFM_SESSION_KEY: &str = "lastfm-session-key"; +const SCROBBLE_LISTENBRAINZ_TOKEN_KEY: &str = "listenbrainz-token"; +const STATS_LISTENBRAINZ_TOKEN_KEY: &str = "stats-listenbrainz-token"; + +/// Where a role's ListenBrainz token is kept. Separate per role, since the two +/// can be different accounts on different servers. (Last.fm's import needs no +/// secret, so only the scrobbling role keeps Last.fm credentials.) +pub fn listenbrainz_token_key(role: Role) -> &'static str { + match role { + Role::Scrobble => SCROBBLE_LISTENBRAINZ_TOKEN_KEY, + Role::Stats => STATS_LISTENBRAINZ_TOKEN_KEY, + } +} diff --git a/src-tauri/src/stats/scrobble.rs b/src-tauri/src/stats/scrobble.rs new file mode 100644 index 0000000..9af49bf --- /dev/null +++ b/src-tauri/src/stats/scrobble.rs @@ -0,0 +1,205 @@ +//! Sending Plays straight to a listening service, leaving the Subsonic server +//! out of it. Which service is a preference; this module resolves it to a +//! [`Target`] carrying the credentials, and sends through whichever API that +//! service speaks. + +use super::store::Account; +use super::{ + lastfm, listenbrainz, listenbrainz_token_key, Role, Source, LASTFM_SECRET_KEY, + LASTFM_SESSION_KEY, +}; +use crate::state::AppState; + +/// One play, as the services identify it. `track` and `artist` are the only +/// fields they require; a submission missing either is rejected outright. +#[derive(Debug, Clone)] +pub struct ScrobbleTrack { + pub artist: String, + pub track: String, + pub album: Option, + /// Track length in seconds; omitted when the engine never learned it. + pub duration_secs: Option, +} + +/// The artist name to submit for a play. +/// +/// Last.fm and ListenBrainz identify a play by artist *name*, so a joined +/// credit like "A feat. B" usually matches no artist there and the play is +/// filed under nothing useful. `first_artist_only` trades the featured names +/// for a play that lands on the main artist — which is only possible where the +/// server enumerated the credit, so without a first artist the full string +/// still goes. +pub fn scrobble_artist( + artist: Option, + first_artist: Option, + first_artist_only: bool, +) -> Option { + if !first_artist_only { + return artist; + } + // A blank first artist would otherwise beat a perfectly good credit and + // lose the scrobble entirely (`from_parts` drops empty artists). + first_artist.filter(|name| !name.trim().is_empty()).or(artist) +} + +impl ScrobbleTrack { + /// Build a submission from the engine's (all-optional) track metadata. + /// Returns `None` when artist or title is missing — the service would only + /// reject it, and a play it cannot attribute is not worth a round trip. + pub fn from_parts( + artist: Option, + title: Option, + album: Option, + duration_ms: u64, + ) -> Option { + let artist = artist.filter(|s| !s.trim().is_empty())?; + let track = title.filter(|s| !s.trim().is_empty())?; + Some(Self { + artist, + track, + album: album.filter(|s| !s.trim().is_empty()), + duration_secs: (duration_ms > 0).then_some(duration_ms / 1000), + }) + } +} + +/// A service ready to take submissions, with everything needed to send one. +pub enum Target { + Lastfm { api_key: String, secret: String, session_key: String }, + Listenbrainz { api_root: String, token: String }, +} + +impl Target { + pub fn source(&self) -> Source { + match self { + Target::Lastfm { .. } => Source::Lastfm, + Target::Listenbrainz { .. } => Source::Listenbrainz, + } + } + + /// Announce the track as now playing. Both services expire the entry on + /// their own after roughly the track's length. + pub async fn now_playing( + &self, + client: &reqwest::Client, + track: &ScrobbleTrack, + ) -> Result<(), String> { + match self { + Target::Lastfm { api_key, secret, session_key } => { + lastfm::update_now_playing(client, api_key, secret, session_key, track).await + } + Target::Listenbrainz { api_root, token } => { + listenbrainz::submit(client, api_root, token, track, None).await + } + } + } + + /// Submit a finished play. `started_at` is unix seconds at which the track + /// *started*, which is what both services record as the play time. + pub async fn scrobble( + &self, + client: &reqwest::Client, + track: &ScrobbleTrack, + started_at: i64, + ) -> Result<(), String> { + match self { + Target::Lastfm { api_key, secret, session_key } => { + lastfm::scrobble(client, api_key, secret, session_key, track, started_at).await + } + Target::Listenbrainz { api_root, token } => { + listenbrainz::submit(client, api_root, token, track, Some(started_at)).await + } + } + } +} + +/// The scrobbling account as a submission target, or `None` while there is +/// none or its secrets are missing from the keychain. +pub fn scrobble_target(state: &AppState) -> Option { + match state.stats.config().scrobble? { + Account::Lastfm { api_key, .. } => Some(Target::Lastfm { + api_key, + secret: state.keychain.retrieve_secret(LASTFM_SECRET_KEY)?, + session_key: state.keychain.retrieve_secret(LASTFM_SESSION_KEY)?, + }), + Account::Listenbrainz { api_url, .. } => Some(Target::Listenbrainz { + api_root: api_url.unwrap_or_else(|| listenbrainz::DEFAULT_API_ROOT.to_owned()), + token: state.keychain.retrieve_secret(listenbrainz_token_key(Role::Scrobble))?, + }), + } +} + +/// Resolve the direct-scrobbling target, or `None` to fall back to the +/// Subsonic server. Deliberately strict: the mode applies only when the +/// preference is on *and* the scrobbling account is fully set up. A +/// half-configured account would otherwise route plays away from Navidrome +/// and then drop them, which is worse than ignoring the preference. +pub fn direct_target(state: &AppState) -> Option { + if !state.settings.get().prefs.direct_scrobble { + return None; + } + scrobble_target(state) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scrobble_artist_sends_the_whole_credit_by_default() { + let artist = || Some("A feat. B".to_owned()); + let first = || Some("A".to_owned()); + assert_eq!(scrobble_artist(artist(), first(), false).as_deref(), Some("A feat. B")); + } + + #[test] + fn scrobble_artist_sends_only_the_first_when_asked() { + let artist = || Some("A feat. B".to_owned()); + assert_eq!( + scrobble_artist(artist(), Some("A".to_owned()), true).as_deref(), + Some("A") + ); + } + + #[test] + fn scrobble_artist_falls_back_when_the_first_artist_is_unknown() { + // Servers without the OpenSubsonic artists extension send the credit as + // one opaque string: there is nothing to take the first artist from, and + // guessing at separators would split "Simon & Garfunkel". + let artist = || Some("Simon & Garfunkel".to_owned()); + assert_eq!( + scrobble_artist(artist(), None, true).as_deref(), + Some("Simon & Garfunkel") + ); + // A blank one must not win, or the play is dropped rather than filed. + assert_eq!( + scrobble_artist(artist(), Some(" ".to_owned()), true).as_deref(), + Some("Simon & Garfunkel") + ); + // Nothing at all stays nothing, whichever way the preference is set. + assert_eq!(scrobble_artist(None, None, true), None); + assert_eq!(scrobble_artist(None, None, false), None); + } + + #[test] + fn submissions_need_an_artist_and_a_title() { + assert!(ScrobbleTrack::from_parts(None, Some("T".into()), None, 0).is_none()); + assert!(ScrobbleTrack::from_parts(Some("A".into()), None, None, 0).is_none()); + // Whitespace-only metadata is as unusable as none at all. + assert!(ScrobbleTrack::from_parts(Some(" ".into()), Some("T".into()), None, 0).is_none()); + } + + #[test] + fn submissions_carry_album_and_duration_when_known() { + let track = + ScrobbleTrack::from_parts(Some("A".into()), Some("T".into()), Some("Al".into()), 245_000) + .expect("artist and title are present"); + assert_eq!(track.album.as_deref(), Some("Al")); + assert_eq!(track.duration_secs, Some(245)); + // An unknown duration is omitted rather than sent as zero. + let unknown = ScrobbleTrack::from_parts(Some("A".into()), Some("T".into()), None, 0) + .expect("artist and title are present"); + assert_eq!(unknown.duration_secs, None); + assert_eq!(unknown.album, None); + } +} diff --git a/src-tauri/src/stats/store.rs b/src-tauri/src/stats/store.rs index fde421f..f369f37 100644 --- a/src-tauri/src/stats/store.rs +++ b/src-tauri/src/stats/store.rs @@ -1,15 +1,22 @@ -//! Scrobble storage for the stats page. Each source appends to its own -//! JSONL file (one scrobble per line, chronological), which makes -//! incremental imports a cheap append; sync cursors live in sources.json. +//! The connected accounts and the imported history behind the Stats page. +//! +//! There are two accounts, one per [`Role`]: the scrobbling account takes Plays +//! when direct scrobbling is on, and the stats account supplies the history — +//! or, by default, the Stats page follows the scrobbling account instead of +//! having one of its own. Secrets live in the keychain; the rest is +//! `sources.json`. The imported history is a single JSONL file (one scrobble +//! per line, chronological), which makes incremental imports a cheap append. use std::fs; use std::io::{BufRead, BufReader, Write}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Mutex, RwLock}; use serde::{Deserialize, Serialize}; +use serde_json::Value; +use super::{Role, Source}; use crate::error::ReverbError; #[derive(Debug, Clone, Serialize, Deserialize)] @@ -23,34 +30,224 @@ pub struct StatScrobble { pub album: Option, } -#[derive(Debug, Clone, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase", default)] -pub struct LastfmConfig { +/// A connected account, minus its secrets (those are in the keychain). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "service", rename_all = "lowercase", rename_all_fields = "camelCase")] +pub enum Account { + Lastfm { + username: String, + api_key: String, + }, + Listenbrainz { + /// As the server reported it. Can be empty for a server that only + /// mimics the API, which then cannot supply history. + username: String, + /// API root of a server other than listenbrainz.org (normalized, no + /// trailing slash); `None` means listenbrainz.org. + api_url: Option, + /// Whether the server hands listening history back. listenbrainz.org + /// does; scrobble servers that merely accept ListenBrainz submissions + /// often do not, and can then only be scrobbled to. + history: bool, + }, +} + +impl Account { + pub fn source(&self) -> Source { + match self { + Account::Lastfm { .. } => Source::Lastfm, + Account::Listenbrainz { .. } => Source::Listenbrainz, + } + } + + pub fn username(&self) -> &str { + match self { + Account::Lastfm { username, .. } | Account::Listenbrainz { username, .. } => username, + } + } + + pub fn api_url(&self) -> Option<&str> { + match self { + Account::Lastfm { .. } => None, + Account::Listenbrainz { api_url, .. } => api_url.as_deref(), + } + } + + /// Whether the Stats page can import from this account. + pub fn has_history(&self) -> bool { + match self { + Account::Lastfm { .. } => true, + Account::Listenbrainz { history, .. } => *history, + } + } + + pub fn history_id(&self) -> HistoryId { + HistoryId { + source: self.source(), + username: self.username().to_owned(), + api_url: self.api_url().map(str::to_owned), + } + } +} + +/// Whose history it is. The same service, account and server is the same +/// history, however the account got connected — which is what lets "use the +/// scrobbling account" be switched off and on without importing again. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HistoryId { + pub source: Source, pub username: String, - pub api_key: String, - /// Whether an authenticated session for *submitting* plays exists. The - /// session key and shared secret themselves live in the keychain, not - /// here — this is only the flag the UI reads. Importing needs neither, so - /// a source connected before scrobbling existed stays valid with `false`. - pub scrobbling: bool, + pub api_url: Option, +} + +/// The imported history and how far it has been synced. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct History { + pub from: HistoryId, /// Unix ts of the newest imported scrobble (sync cursor). + #[serde(default)] pub last_sync_ts: i64, - /// ISO timestamp of the last successful sync. + /// ISO timestamp of the last completed sync. + #[serde(default)] pub last_sync_at: Option, + #[serde(default)] pub track_count: u64, } -#[derive(Debug, Clone, Serialize, Deserialize, Default)] +impl History { + fn fresh(from: HistoryId) -> Self { + Self { from, last_sync_ts: 0, last_sync_at: None, track_count: 0 } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct SourcesConfig { - pub lastfm: Option, + /// Where direct scrobbling sends Plays. + pub scrobble: Option, + /// Read the scrobbling account's history rather than `stats_account`'s. + pub stats_same_as_scrobble: bool, + /// The Stats page's own account, used while `stats_same_as_scrobble` is + /// off — another service, account or server than the one scrobbled to. + pub stats_account: Option, + /// The imported history. It belongs to whichever account the Stats page + /// reads; while that is none it is kept as it was, so it picks up where it + /// left off when that account comes back. + pub history: Option, +} + +impl Default for SourcesConfig { + fn default() -> Self { + Self { scrobble: None, stats_same_as_scrobble: true, stats_account: None, history: None } + } +} + +impl SourcesConfig { + pub fn account(&self, role: Role) -> Option<&Account> { + match role { + Role::Scrobble => self.scrobble.as_ref(), + Role::Stats => self.stats_account.as_ref(), + } + } + + /// The account the Stats page reads, and the role whose secrets it uses. + /// `None` when the chosen account is missing or cannot supply history. + pub fn stats_source(&self) -> Option<(Role, &Account)> { + let role = if self.stats_same_as_scrobble { Role::Scrobble } else { Role::Stats }; + self.account(role).filter(|a| a.has_history()).map(|a| (role, a)) + } + + /// The history of the account the Stats page reads, if any. + pub fn active_history(&self) -> Option<&History> { + let (_, account) = self.stats_source()?; + let id = account.history_id(); + self.history.as_ref().filter(|h| h.from == id) + } + + /// An API key for Last.fm's read-only calls (artist biographies), from + /// whichever account has one. + pub fn lastfm_api_key(&self) -> Option { + [&self.scrobble, &self.stats_account].into_iter().flatten().find_map(|a| match a { + Account::Lastfm { api_key, .. } => Some(api_key.clone()), + Account::Listenbrainz { .. } => None, + }) + } + + /// Point the history at the account the Stats page now reads. Another + /// account's history is replaced by an empty one; with no account to + /// read, the history is left alone. + fn reconcile(&mut self) { + let Some(id) = self.stats_source().map(|(_, a)| a.history_id()) else { return }; + if self.history.as_ref().map(|h| &h.from) != Some(&id) { + self.history = Some(History::fresh(id)); + } + } +} + +/// `sources.json` as Reverb 1.0 wrote it: one Last.fm connection that +/// imported history and, with `scrobbling`, also took Plays. +#[derive(Deserialize, Default)] +#[serde(rename_all = "camelCase", default)] +struct LegacyLastfm { + username: String, + api_key: String, + scrobbling: bool, + last_sync_ts: i64, + last_sync_at: Option, + track_count: u64, +} + +/// Read `sources.json`, carrying a 1.0 file over: a Last.fm connection that +/// scrobbled becomes the scrobbling account with stats following it, an +/// import-only one becomes the stats account. Either way its history (still +/// `lastfm.jsonl`) and sync cursor stay, so nothing is imported again. +fn parse_sources(raw: &str) -> SourcesConfig { + let Ok(value) = serde_json::from_str::(raw) else { return SourcesConfig::default() }; + let legacy = value["lastfm"].is_object() + && ["scrobble", "statsAccount", "history"].iter().all(|key| value.get(key).is_none()); + if !legacy { + return serde_json::from_value(value).unwrap_or_default(); + } + let old: LegacyLastfm = serde_json::from_value(value["lastfm"].clone()).unwrap_or_default(); + let account = Account::Lastfm { username: old.username, api_key: old.api_key }; + let history = Some(History { + from: account.history_id(), + last_sync_ts: old.last_sync_ts, + last_sync_at: old.last_sync_at, + track_count: old.track_count, + }); + if old.scrobbling { + SourcesConfig { + scrobble: Some(account), + stats_same_as_scrobble: true, + stats_account: None, + history, + } + } else { + SourcesConfig { + scrobble: None, + stats_same_as_scrobble: false, + stats_account: Some(account), + history, + } + } +} + +/// What a configuration change did. +pub struct Change { + pub config: SourcesConfig, + /// The Stats page reads a different account than before, or now reads one + /// at all — its history wants a sync. + pub stats_source_changed: bool, } pub struct StatsStore { dir: PathBuf, config: RwLock, - /// In-memory scrobble cache, invalidated by imports. - cache: Mutex>>, + /// The active history in memory, invalidated by imports. + cache: Mutex)>>, pub importing: AtomicBool, } @@ -59,7 +256,7 @@ impl StatsStore { let dir = data_dir.join("stats"); fs::create_dir_all(&dir)?; let config = match fs::read_to_string(dir.join("sources.json")) { - Ok(raw) => serde_json::from_str(&raw).unwrap_or_default(), + Ok(raw) => parse_sources(&raw), Err(_) => SourcesConfig::default(), }; Ok(Self { @@ -74,57 +271,102 @@ impl StatsStore { self.config.read().unwrap().clone() } - pub fn update_config( - &self, - mutate: impl FnOnce(&mut SourcesConfig), - ) -> Result { - let snapshot = { - let mut guard = self.config.write().unwrap(); - mutate(&mut guard); - guard.clone() - }; - let raw = serde_json::to_string_pretty(&snapshot) - .map_err(|e| ReverbError::Io(e.to_string()))?; + fn history_file(&self, source: Source) -> PathBuf { + history_file(&self.dir, source) + } + + /// Written while the config lock is held, so writes land in the order the + /// changes were made. + fn persist(&self, config: &SourcesConfig) -> Result<(), ReverbError> { + let raw = + serde_json::to_string_pretty(config).map_err(|e| ReverbError::Io(e.to_string()))?; let tmp = self.dir.join("sources.json.tmp"); fs::write(&tmp, raw)?; fs::rename(tmp, self.dir.join("sources.json"))?; - Ok(snapshot) + Ok(()) } - fn source_file(&self, source: &str) -> PathBuf { - self.dir.join(format!("{source}.jsonl")) + /// Change the accounts. The history follows: when the Stats page ends up + /// reading another account, the old history's file is deleted and an + /// empty one takes its place. Setting `history` to `None` in `mutate` + /// deletes it outright. + pub fn update(&self, mutate: impl FnOnce(&mut SourcesConfig)) -> Result { + let mut config = self.config.write().unwrap(); + let source_before = config.stats_source().map(|(_, a)| a.history_id()); + let history_before = config.history.as_ref().map(|h| h.from.clone()); + mutate(&mut config); + config.reconcile(); + let history_after = config.history.as_ref().map(|h| h.from.clone()); + if history_before != history_after { + // The old history's file goes with it, and a new one starts from + // an empty file rather than from whatever an earlier one left. + for id in [&history_before, &history_after].into_iter().flatten() { + let _ = fs::remove_file(self.history_file(id.source)); + } + *self.cache.lock().unwrap() = None; + } + self.persist(&config)?; + let source_after = config.stats_source().map(|(_, a)| a.history_id()); + Ok(Change { + config: config.clone(), + stats_source_changed: source_before != source_after, + }) } - /// Append scrobbles (callers pass them in chronological order). - pub fn append(&self, source: &str, scrobbles: &[StatScrobble]) -> Result<(), ReverbError> { - let mut file = fs::OpenOptions::new() - .create(true) - .append(true) - .open(self.source_file(source))?; + /// Append scrobbles (chronological) to the history of `from` and move its + /// cursor past them. Returns `false`, appending nothing, when the history + /// now belongs to another account — the import fetching them has been + /// overtaken by a change of account. + pub fn append_history( + &self, + from: &HistoryId, + scrobbles: &[StatScrobble], + ) -> Result { + let mut config = self.config.write().unwrap(); + let Some(history) = config.history.as_mut().filter(|h| &h.from == from) else { + return Ok(false); + }; + let Some(newest) = scrobbles.last().map(|s| s.ts) else { return Ok(true) }; let mut buf = String::new(); for s in scrobbles { buf.push_str(&serde_json::to_string(s).map_err(|e| ReverbError::Io(e.to_string()))?); buf.push('\n'); } - file.write_all(buf.as_bytes())?; + fs::OpenOptions::new() + .create(true) + .append(true) + .open(self.history_file(from.source))? + .write_all(buf.as_bytes())?; + history.last_sync_ts = newest; + history.track_count += scrobbles.len() as u64; *self.cache.lock().unwrap() = None; - Ok(()) + self.persist(&config)?; + Ok(true) } - pub fn clear_source(&self, source: &str) { - let _ = fs::remove_file(self.source_file(source)); - *self.cache.lock().unwrap() = None; + /// Stamp a completed sync of `from`'s history. + pub fn finish_sync(&self, from: &HistoryId, at: String) -> Result<(), ReverbError> { + let mut config = self.config.write().unwrap(); + if let Some(history) = config.history.as_mut().filter(|h| &h.from == from) { + history.last_sync_at = Some(at); + self.persist(&config)?; + } + Ok(()) } - /// All scrobbles from all sources, cached in memory between imports. - pub fn all_scrobbles(&self) -> Result, ReverbError> { - if let Some(cached) = self.cache.lock().unwrap().as_ref() { - return Ok(cached.clone()); + /// The scrobbles of the account the Stats page reads, chronological, + /// cached in memory between imports. Empty while it reads none. + pub fn scrobbles(&self) -> Result, ReverbError> { + let Some(id) = self.config().active_history().map(|h| h.from.clone()) else { + return Ok(Vec::new()); + }; + if let Some((cached_id, cached)) = self.cache.lock().unwrap().as_ref() { + if *cached_id == id { + return Ok(cached.clone()); + } } let mut all = Vec::new(); - for source in ["lastfm"] { - let path = self.source_file(source); - let Ok(file) = fs::File::open(&path) else { continue }; + if let Ok(file) = fs::File::open(self.history_file(id.source)) { for line in BufReader::new(file).lines() { let Ok(line) = line else { break }; if let Ok(s) = serde_json::from_str::(&line) { @@ -133,11 +375,16 @@ impl StatsStore { } } all.sort_by_key(|s| s.ts); - *self.cache.lock().unwrap() = Some(all.clone()); + *self.cache.lock().unwrap() = Some((id, all.clone())); Ok(all) } } +/// Named by service, as in 1.0, so its Last.fm history file carries over. +fn history_file(dir: &Path, source: Source) -> PathBuf { + dir.join(format!("{}.jsonl", source.id())) +} + /// RAII guard for the single-import lock. pub struct ImportGuard<'a>(&'a AtomicBool); @@ -156,3 +403,150 @@ impl Drop for ImportGuard<'_> { self.0.store(false, Ordering::SeqCst); } } + +#[cfg(test)] +mod tests { + use super::*; + + fn lastfm(username: &str) -> Account { + Account::Lastfm { username: username.into(), api_key: "k".into() } + } + + fn listenbrainz(api_url: Option<&str>, history: bool) -> Account { + Account::Listenbrainz { + username: "lb".into(), + api_url: api_url.map(str::to_owned), + history, + } + } + + fn scrobble(ts: i64) -> StatScrobble { + StatScrobble { ts, artist: "A".into(), track: "T".into(), album: None } + } + + #[test] + fn a_last_fm_connection_that_scrobbled_becomes_the_scrobbling_account() { + let config = parse_sources( + r#"{"lastfm": {"username": "u", "apiKey": "k", "scrobbling": true, + "lastSyncTs": 1700000000, "lastSyncAt": "2026-01-01T00:00:00Z", "trackCount": 42}}"#, + ); + assert_eq!(config.scrobble, Some(lastfm("u"))); + assert!(config.stats_same_as_scrobble); + assert_eq!(config.stats_account, None); + let history = config.active_history().expect("stats read the scrobbling account"); + assert_eq!(history.last_sync_ts, 1_700_000_000); + assert_eq!(history.track_count, 42); + } + + #[test] + fn an_import_only_last_fm_connection_becomes_the_stats_account() { + let config = parse_sources( + r#"{"lastfm": {"username": "u", "apiKey": "k", "scrobbling": false, "trackCount": 7}}"#, + ); + assert_eq!(config.scrobble, None); + assert!(!config.stats_same_as_scrobble); + assert_eq!(config.stats_account, Some(lastfm("u"))); + assert_eq!(config.active_history().map(|h| h.track_count), Some(7)); + } + + #[test] + fn a_file_without_accounts_reads_as_defaults() { + for raw in ["", "{}", r#"{"lastfm": null}"#] { + assert_eq!(parse_sources(raw), SourcesConfig::default(), "{raw:?}"); + } + } + + #[test] + fn the_current_layout_round_trips() { + let config = SourcesConfig { + scrobble: Some(listenbrainz(Some("https://maloja.example/apis/listenbrainz"), false)), + stats_same_as_scrobble: false, + stats_account: Some(lastfm("u")), + history: Some(History::fresh(lastfm("u").history_id())), + }; + let raw = serde_json::to_string(&config).unwrap(); + assert!(raw.contains(r#""service":"listenbrainz""#), "{raw}"); + assert!(raw.contains(r#""apiUrl":"https://maloja.example/apis/listenbrainz""#), "{raw}"); + assert_eq!(parse_sources(&raw), config); + } + + #[test] + fn stats_follow_the_scrobbling_account_only_where_it_has_history() { + let mut config = SourcesConfig { scrobble: Some(lastfm("u")), ..SourcesConfig::default() }; + assert_eq!(config.stats_source().map(|(role, _)| role), Some(Role::Scrobble)); + + // A scrobble-only server has nothing to show. + config.scrobble = Some(listenbrainz(Some("https://maloja.example"), false)); + assert!(config.stats_source().is_none()); + + // Its own account is read once stats stop following. + config.stats_same_as_scrobble = false; + config.stats_account = Some(listenbrainz(None, true)); + assert_eq!(config.stats_source().map(|(role, _)| role), Some(Role::Stats)); + } + + #[test] + fn the_history_belongs_to_whichever_account_stats_read() { + let mut config = SourcesConfig { scrobble: Some(lastfm("u")), ..SourcesConfig::default() }; + config.reconcile(); + config.history.as_mut().unwrap().track_count = 10; + + // No account to read: the history waits rather than going. + config.stats_same_as_scrobble = false; + config.reconcile(); + assert_eq!(config.history.as_ref().map(|h| h.track_count), Some(10)); + assert!(config.active_history().is_none()); + + // The same account again, under the other role: same history. + config.stats_account = Some(lastfm("u")); + config.reconcile(); + assert_eq!(config.active_history().map(|h| h.track_count), Some(10)); + + // Another server is another history. + config.stats_account = Some(listenbrainz(Some("https://lb.example"), true)); + config.reconcile(); + assert_eq!(config.active_history().map(|h| h.track_count), Some(0)); + } + + #[test] + fn switching_accounts_deletes_the_old_history_and_overtakes_its_import() { + let dir = tempfile::tempdir().unwrap(); + let store = StatsStore::load(dir.path().to_path_buf()).unwrap(); + let change = store.update(|c| c.scrobble = Some(lastfm("u"))).unwrap(); + assert!(change.stats_source_changed, "stats now read an account"); + + let from = lastfm("u").history_id(); + assert!(store.append_history(&from, &[scrobble(1), scrobble(2)]).unwrap()); + assert_eq!(store.scrobbles().unwrap().len(), 2); + assert_eq!(store.config().active_history().unwrap().last_sync_ts, 2); + let file = dir.path().join("stats/lastfm.jsonl"); + assert!(file.exists()); + + let change = store.update(|c| c.scrobble = Some(listenbrainz(None, true))).unwrap(); + assert!(change.stats_source_changed); + assert!(!file.exists(), "the Last.fm history went with the account"); + assert!(store.scrobbles().unwrap().is_empty()); + // An import still fetching for Last.fm finds its history gone. + assert!(!store.append_history(&from, &[scrobble(3)]).unwrap()); + assert!(store.scrobbles().unwrap().is_empty()); + } + + #[test] + fn toggling_without_another_account_keeps_the_history() { + let dir = tempfile::tempdir().unwrap(); + let store = StatsStore::load(dir.path().to_path_buf()).unwrap(); + store.update(|c| c.scrobble = Some(lastfm("u"))).unwrap(); + let from = lastfm("u").history_id(); + store.append_history(&from, &[scrobble(1)]).unwrap(); + + store.update(|c| c.stats_same_as_scrobble = false).unwrap(); + assert!(store.scrobbles().unwrap().is_empty(), "nothing to read meanwhile"); + let change = store.update(|c| c.stats_same_as_scrobble = true).unwrap(); + assert!(change.stats_source_changed); + assert_eq!(store.scrobbles().unwrap().len(), 1, "back without importing again"); + + // Reloading from disk gives the same picture. + let reloaded = StatsStore::load(dir.path().to_path_buf()).unwrap(); + assert_eq!(reloaded.scrobbles().unwrap().len(), 1); + } +} diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsx index 01da70e..3af71df 100644 --- a/src/components/layout/Sidebar.tsx +++ b/src/components/layout/Sidebar.tsx @@ -1,43 +1,43 @@ -import { useQuery } from "@tanstack/react-query"; import { ListMusic, Pin, Radio, Settings } from "lucide-react"; import { NavLink } from "react-router"; import { Logo } from "../ui/Logo"; import { UpdateMarker } from "../update/UpdateMarker"; import { visibleNavItems } from "./navItems"; import { useT } from "../../lib/i18n"; -import { cmd } from "../../lib/ipc/commands"; +import { SERVICE_NAMES, useServices } from "../../lib/scrobbleServices"; import { usePlaylists } from "../../lib/subsonic/queries"; import { usePrefsStore } from "../../stores/prefsStore"; /** - * The pinned "Last.fm only" switch. Hidden unless the user pinned it *and* - * Last.fm scrobbling is still set up — the preference outlives the credentials - * it depends on, and a switch that silently does nothing is worse than none. + * The pinned direct-scrobbling switch, named after the scrobbling account's + * service ("Last.fm only", "ListenBrainz only"). Hidden unless the user pinned + * it *and* a scrobbling account is connected — the preference outlives the + * account it depends on, and a switch that silently does nothing is worse than + * none. */ -function LastfmOnlySwitch() { +function DirectScrobbleSwitch() { const t = useT(); - const pinned = usePrefsStore((s) => s.prefs.lastfmScrobbleOnlyPinned); - const active = usePrefsStore((s) => s.prefs.lastfmScrobbleOnly); + const pinned = usePrefsStore((s) => s.prefs.directScrobblePinned); + const active = usePrefsStore((s) => s.prefs.directScrobble); const set = usePrefsStore((s) => s.set); - const { data: sources } = useQuery({ - queryKey: ["stats-sources"], - queryFn: () => cmd("stats_get_sources"), - enabled: pinned, - }); + const { data: services } = useServices({ enabled: pinned }); + const account = services?.scrobble; - if (!pinned || !sources?.lastfm?.scrobbling) return null; + if (!pinned || !account) return null; return ( + ))} + + ); +} + +/** Connect a Last.fm account: with the shared secret and password to scrobble. */ +function LastfmForm({ role }: { role: AccountRole }) { const t = useT(); const queryClient = useQueryClient(); const showToast = useUiStore((s) => s.showToast); - const statsImport = useUiStore((s) => s.statsImport); const [username, setUsername] = useState(""); const [apiKey, setApiKey] = useState(""); const [sharedSecret, setSharedSecret] = useState(""); const [password, setPassword] = useState(""); const [connecting, setConnecting] = useState(false); - const [disconnectOpen, setDisconnectOpen] = useState(false); - /** The add-scrobbling form, shown for an already-connected source. */ - const [scrobbleFormOpen, setScrobbleFormOpen] = useState(false); - - const sources = useQuery({ - queryKey: ["stats-sources"], - queryFn: () => cmd("stats_get_sources"), - }); - - // Progress + completion toasts come from the global stats:import listener. - const importing = statsImport !== null || Boolean(sources.data?.importing); - const progress = !statsImport - ? null - : statsImport.total - ? t("settings.importingOfTotal", { n: statsImport.imported, total: statsImport.total }) - : t("settings.importingCount", { n: statsImport.imported }); + const scrobbling = role === "scrobble"; + const ready = + username.trim() && apiKey.trim() && (!scrobbling || (sharedSecret.trim() && password)); async function connect(e: React.FormEvent) { e.preventDefault(); setConnecting(true); try { - await cmd("stats_configure_lastfm", { + await cmd("services_connect_lastfm", { + role, username: username.trim(), apiKey: apiKey.trim(), - sharedSecret: sharedSecret.trim() || null, - password: password || null, + sharedSecret: scrobbling ? sharedSecret.trim() : null, + password: scrobbling ? password : null, }); setUsername(""); setApiKey(""); setSharedSecret(""); setPassword(""); - void queryClient.invalidateQueries({ queryKey: ["stats-sources"] }); - markStatsImportStarted(); - void cmd("stats_import", { source: "lastfm" }); - showToast(t("toast.lastfmConnected")); + invalidateServices(queryClient); + showToast(t("toast.connected", { service: SERVICE_NAMES.lastfm })); } catch (err) { showToast(errorMessage(err), "error"); } finally { @@ -971,22 +920,85 @@ function StatsSourcesSection() { } } - /** Add scrobbling to a source that is already connected for imports. */ - async function enableScrobbling(e: React.FormEvent) { + return ( +
+

+ {scrobbling + ? `${t("settings.lastfmScrobbleLead")} ${t("settings.lastfmPairHint")} ${t("settings.lastfmScrobbleIntro")}` + : t("settings.lastfmIntro")} +

+ setUsername(e.target.value)} + placeholder={t("settings.lastfmUsername")} + spellCheck={false} + /> + setApiKey(e.target.value)} + placeholder={t("settings.apiKey")} + spellCheck={false} + /> + {scrobbling && ( + <> + setSharedSecret(e.target.value)} + placeholder={t("settings.lastfmSharedSecret")} + spellCheck={false} + /> + setPassword(e.target.value)} + placeholder={t("settings.lastfmPassword")} + /> + + )} + +
+ ); +} + +/** + * Connect ListenBrainz, or a server that speaks its API. Given the role's + * current ListenBrainz connection, it edits that one instead, and a blank + * token keeps the stored one. + */ +function ListenbrainzForm({ + role, + current, + onDone, +}: { + role: AccountRole; + current?: AccountStatus | null; + onDone?: () => void; +}) { + const t = useT(); + const queryClient = useQueryClient(); + const showToast = useUiStore((s) => s.showToast); + const editing = current?.service === "listenbrainz"; + const [token, setToken] = useState(""); + const [apiUrl, setApiUrl] = useState(editing ? (current?.apiUrl ?? "") : ""); + const [connecting, setConnecting] = useState(false); + + async function connect(e: React.FormEvent) { e.preventDefault(); setConnecting(true); try { - await cmd("stats_enable_lastfm_scrobbling", { - sharedSecret: sharedSecret.trim(), - password, - apiKey: apiKey.trim() || null, + await cmd("services_connect_listenbrainz", { + role, + token: token.trim() || null, + apiUrl: apiUrl.trim() || null, }); - setSharedSecret(""); - setPassword(""); - setApiKey(""); - setScrobbleFormOpen(false); - void queryClient.invalidateQueries({ queryKey: ["stats-sources"] }); - showToast(t("toast.lastfmScrobblingOn")); + setToken(""); + invalidateServices(queryClient); + showToast(t("toast.connected", { service: SERVICE_NAMES.listenbrainz })); + onDone?.(); } catch (err) { showToast(errorMessage(err), "error"); } finally { @@ -994,138 +1006,371 @@ function StatsSourcesSection() { } } - const lastfm = sources.data?.lastfm; + return ( +
+ {!editing && ( +

+ {role === "scrobble" + ? t("settings.listenbrainzScrobbleIntro") + : t("settings.listenbrainzStatsIntro")} +

+ )} + setToken(e.target.value)} + placeholder={ + editing ? t("settings.listenbrainzTokenKeep") : t("settings.listenbrainzToken") + } + spellCheck={false} + autoComplete="off" + /> + setApiUrl(e.target.value)} + placeholder={t("settings.listenbrainzServer")} + spellCheck={false} + /> +

+ {role === "scrobble" + ? t("settings.listenbrainzServerHint") + : t("settings.listenbrainzStatsServerHint")} +

+ +
+ ); +} +/** Disconnect button plus its confirmation. */ +function DisconnectButton({ + role, + service, + body, +}: { + role: AccountRole; + service: ServiceId; + body: string; +}) { + const t = useT(); + const queryClient = useQueryClient(); + const [open, setOpen] = useState(false); return ( - - {lastfm ? ( - <> -
- Last.fm - {t("settings.lastfmConnectedAs")} - {lastfm.username} - {lastfm.scrobbling && ( - {t("settings.lastfmScrobblingOn")} - )} + <> + + { + void cmd("services_disconnect", { role }).then(() => invalidateServices(queryClient)); + }} + onClose={() => setOpen(false)} + /> + + ); +} + +/** + * One role's account. Shows the connection when the picked service is the + * connected one; otherwise the form to connect the picked service, which + * replaces the current account (`replaceNote` says what that does). + */ +function AccountPanel({ + role, + account, + service, + replaceNote, + disconnectBody, +}: { + role: AccountRole; + account: AccountStatus | null; + service: ServiceId; + replaceNote: string; + disconnectBody: string; +}) { + const t = useT(); + const [editing, setEditing] = useState(false); + + if (!account || account.service !== service) { + return ( + <> + {account &&

{replaceNote}

} + {service === "lastfm" ? : } + + ); + } + + return ( + <> +
+ {account.username ? ( + <> + {t("settings.connectedAs")} + {account.username} + + ) : ( + {t("settings.connected")} + )} +
+ {account.apiUrl && ( +
+ {t("settings.listenbrainzVia", { url: account.apiUrl })} +
+ )} + {!account.history && ( +
{t("settings.listenbrainzNoHistory")}
+ )} +
+ {account.service === "listenbrainz" && ( + + )} + +
+ {editing && ( +
+ setEditing(false)} /> +
+ )} + + ); +} + +function ScrobblingSection() { + const t = useT(); + const prefs = usePrefsStore((s) => s.prefs); + const set = usePrefsStore((s) => s.set); + const { data } = useServices(); + const account = data?.scrobble ?? null; + /** The picker's choice, until the user makes one: the connected service. */ + const [picked, setPicked] = useState(null); + const service = picked ?? account?.service ?? "lastfm"; + // Named after the account plays actually go to, not the picker's choice. + const name = SERVICE_NAMES[account?.service ?? service]; + // The Stats page reads this account, so changing it changes theirs too. + const statsFollow = Boolean(data?.statsSameAsScrobble && account?.history); + + return ( + + + set({ scrobbleEnabled })} + /> + + {prefs.scrobbleEnabled && ( + +
+ set({ scrobbleAtPercent: Number(e.target.value) })} + className="w-36 accent-(--color-accent)" + /> + {prefs.scrobbleAtPercent}%
- {!lastfm.scrobbling && ( -
{t("settings.lastfmImportOnly")}
- )} -
- {t("settings.scrobblesImported", { n: lastfm.trackCount })} - {lastfm.lastSyncAt - ? t("settings.lastSync", { - date: t.d(lastfm.lastSyncAt, { dateStyle: "medium", timeStyle: "short" }), + + )} + + + + +
+ +
+ + {prefs.scrobbleEnabled && ( + <> + + set({ directScrobble })} + /> + + {/* Shown whether or not the mode is currently on: "turn off on + restart" means the switch above is off every time settings is + opened fresh, and its two companions would blink out with it. */} + + set({ directScrobbleResetOnStart })} + /> + + + set({ directScrobblePinned })} + /> + + {/* Only bites on the plays Reverb sends to the service itself, i.e. + in the mode above — what the server forwards is the server's own + setting. Grouped here for that reason. */} + + set({ scrobbleFirstArtistOnly })} + /> + + + )} + + ); +} + +/** How much history there is, and the button to pull more. */ +function HistoryStatus({ status, source }: { status: ServicesStatus; source: ServiceId }) { + const t = useT(); + const statsImport = useUiStore((s) => s.statsImport); + // Progress + completion toasts come from the global stats:import listener. + const importing = statsImport !== null || status.importing; + const progress = !statsImport + ? null + : statsImport.total + ? t("settings.importingOfTotal", { n: statsImport.imported, total: statsImport.total }) + : t("settings.importingCount", { n: statsImport.imported }); + + return ( +
+
+ {t("settings.scrobblesImported", { n: status.trackCount })} + {status.lastSyncAt + ? t("settings.lastSync", { + date: t.d(status.lastSyncAt, { dateStyle: "medium", timeStyle: "short" }), + }) + : ""} +
+ {progress &&
{progress}
} + +
+ ); +} + +function StatsSection() { + const t = useT(); + const queryClient = useQueryClient(); + const showToast = useUiStore((s) => s.showToast); + const { data } = useServices(); + const same = data?.statsSameAsScrobble ?? true; + const scrobble = data?.scrobble ?? null; + const own = data?.statsAccount ?? null; + const [picked, setPicked] = useState(null); + const service = picked ?? own?.service ?? "lastfm"; + const reads = statsReadsFrom(data); + + function setSame(value: boolean) { + cmd("services_set_stats_same_as_scrobble", { same: value }).then( + () => invalidateServices(queryClient), + (err: unknown) => showToast(errorMessage(err), "error"), + ); + } + + return ( + + + + + {same ? ( +

+ {!scrobble + ? t("settings.statsNoScrobbleAccount") + : scrobble.history + ? t("settings.statsFollows", { + service: SERVICE_NAMES[scrobble.service], + username: scrobble.username, }) - : ""} -

- {progress &&
{progress}
} -
- - {!lastfm.scrobbling && ( - - )} - + : t("settings.statsScrobbleNoHistory")} +

+ ) : ( + <> + + + +
+
- {scrobbleFormOpen && !lastfm.scrobbling && ( -
-

{t("settings.lastfmPairHint")}

- setApiKey(e.target.value)} - placeholder={t("settings.lastfmApiKeyReplace")} - spellCheck={false} - /> - setSharedSecret(e.target.value)} - placeholder={t("settings.lastfmSharedSecret")} - spellCheck={false} - /> - setPassword(e.target.value)} - placeholder={t("settings.lastfmPassword")} - /> - -
- )} - { - void cmd("stats_disconnect", { source: "lastfm" }).then(() => { - void queryClient.invalidateQueries({ queryKey: ["stats-sources"] }); - void queryClient.invalidateQueries({ queryKey: ["stats"] }); - }); - }} - onClose={() => setDisconnectOpen(false)} - /> - ) : ( -
-

{t("settings.lastfmIntro")}

- setUsername(e.target.value)} - placeholder={t("settings.lastfmUsername")} - spellCheck={false} - /> - setApiKey(e.target.value)} - placeholder={t("settings.apiKey")} - spellCheck={false} - /> -

- {t("settings.optionalForScrobbling")} {t("settings.lastfmPairHint")}{" "} - {t("settings.lastfmScrobbleIntro")} -

- setSharedSecret(e.target.value)} - placeholder={t("settings.lastfmSharedSecret")} - spellCheck={false} - /> - setPassword(e.target.value)} - placeholder={t("settings.lastfmPassword")} - /> - -
)} + {reads && data && } ); } @@ -1232,7 +1477,12 @@ export function SettingsView() {
- +
+ +
+
+ +
diff --git a/src/views/stats/StatsView.tsx b/src/views/stats/StatsView.tsx index 15fd290..81ae73b 100644 --- a/src/views/stats/StatsView.tsx +++ b/src/views/stats/StatsView.tsx @@ -2,6 +2,7 @@ import { useQuery } from "@tanstack/react-query"; import { BarChart3, RefreshCw } from "lucide-react"; import { Link, useSearchParams } from "react-router"; import { markStatsImportStarted } from "../../lib/playback/engineBridge"; +import { SERVICE_NAMES, STATS_SETTINGS_PATH, useServices } from "../../lib/scrobbleServices"; import { useUiStore } from "../../stores/uiStore"; import { AreaChart, @@ -150,21 +151,21 @@ export function StatsView() { setParams({ range: "custom", from: next.from, to: next.to }, { replace: true }); } - // Import completion invalidates these globally (engine bridge). - const sources = useQuery({ - queryKey: ["stats-sources"], - queryFn: () => cmd("stats_get_sources"), - }); + // Import completion and account changes invalidate these globally. + const services = useServices(); + // The one account settings chose for stats, if it can supply history. + const source = services.data?.statsSource ?? null; const stats = useQuery({ - queryKey: ["stats", range, from, to], + queryKey: ["stats", source, range, from, to], queryFn: () => cmd("stats_get", { range, from, to }), + enabled: source !== null, staleTime: 60_000, }); - const connected = Boolean(sources.data?.lastfm); + const connected = source !== null; const summary = stats.data; const importProgress = useUiStore((s) => s.statsImport); - const importing = importProgress !== null || Boolean(sources.data?.importing); + const importing = importProgress !== null || Boolean(services.data?.importing); return (
@@ -207,7 +208,7 @@ export function StatsView() { />
)} - {connected && ( + {source && (
{importing && ( @@ -218,7 +219,9 @@ export function StatsView() { total: importProgress.total, }) : t("stats.scrobblesProgress", { n: importProgress.imported }) - : t("stats.contactingLastfm")} + : t("stats.contacting", { + service: SERVICE_NAMES[importProgress?.source ?? source], + })} )}
)}
- {!connected && !sources.isPending ? ( + {!connected && !services.isPending ? (

{t("stats.noSourcesLead")}{" "} - + {t("stats.noSourcesLink")} {" "} {t("stats.noSourcesTail")}