From 3d713e6056b61e1b28f64d5ea45319ff72869fe2 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 3 Dec 2026 14:52:04 -0600 Subject: [PATCH] Scrobbling: retry and log sends, keep listens on quit, Scrobbling settings in cards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - scrobble.log in the data folder records queued, sent and failed scrobbles (stdout goes nowhere, so failures were invisible) - Queued scrobbles retry every 2 minutes; maybe_periodic was never called - One flush at a time, so a listen is never sent twice - The playing track's listen is queued on quit and sent on the next start - Listen time keeps counting while the window is hidden (Wayland stops frames) - Last.fm: says nothing is sent while logged out; waiting scrobbles can be discarded - Settings › Scrobbling: one card per service with its own send checkbox, text left and buttons right on one centre line; row labels left-aligned - iOS: send the listen as soon as it counts (not only at track change), retry every 2 minutes, log sends - Android: retry queued scrobbles every 2 minutes while playing Co-Authored-By: Claude Opus 5.5 --- android/src/com/mulberry/player/LastFm.java | 14 ++ .../src/com/mulberry/player/MusicService.java | 3 + ios/App/Audio/Player.swift | 12 +- ios/App/Services/Scrobbler.swift | 17 ++- src/app.rs | 6 + src/player.rs | 18 ++- src/scrobble.rs | 89 +++++++++-- src/ui/dialogs.rs | 138 ++++++++++++------ tests/shots.rs | 31 ++++ 9 files changed, 266 insertions(+), 62 deletions(-) diff --git a/android/src/com/mulberry/player/LastFm.java b/android/src/com/mulberry/player/LastFm.java index 3654be7..0ad12c1 100644 --- a/android/src/com/mulberry/player/LastFm.java +++ b/android/src/com/mulberry/player/LastFm.java @@ -279,6 +279,20 @@ public final class LastFm { } } + /** Retry queued scrobbles this often while playing, so a failed send waits at most this long. */ + static final long RETRY_MS = 120000L; + private static long lastRetry = 0L; + + /** Called from the playback tick: flush now and then while something is queued. */ + public static void maybeRetry() { + long now = android.os.SystemClock.elapsedRealtime(); + if (now - lastRetry < RETRY_MS) { + return; + } + lastRetry = now; + flush(); + } + /** Send queued scrobbles. Each service goes on its own, so one failing never blocks the other. */ public static void flush() { if (!anyOn()) { diff --git a/android/src/com/mulberry/player/MusicService.java b/android/src/com/mulberry/player/MusicService.java index ec4e07e..bf9a71f 100644 --- a/android/src/com/mulberry/player/MusicService.java +++ b/android/src/com/mulberry/player/MusicService.java @@ -1288,6 +1288,9 @@ public class MusicService extends MediaBrowserService implements AudioManager.On LastFm.scrobble(songCurrent, this.startedSec); } } + if (isPlaying()) { + LastFm.maybeRetry(); + } } /* JADX INFO: Access modifiers changed from: private */ diff --git a/ios/App/Audio/Player.swift b/ios/App/Audio/Player.swift index 1c32b8b..7e6bdbb 100644 --- a/ios/App/Audio/Player.swift +++ b/ios/App/Audio/Player.swift @@ -36,6 +36,7 @@ final class Player: ObservableObject { private var crossfading = false private var listenStart = Date() private var listened: Double = 0 + private var scrobbled = false // this play was already sent as a listen private var lastTick = Date() private var resumeAfterInterruption = false @@ -361,6 +362,7 @@ final class Player: ObservableObject { error = nil listenStart = Date() listened = 0 + scrobbled = false lastTick = Date() loadArtAndLyrics(s) let e = engine(for: s) @@ -408,6 +410,7 @@ final class Player: ObservableObject { duration = queue[i].duration listenStart = Date() listened = 0 + scrobbled = false loadArtAndLyrics(queue[i]) planNext(force: true) updateNowPlaying() @@ -463,6 +466,7 @@ final class Player: ObservableObject { duration = s.duration listenStart = Date() listened = 0 + scrobbled = false loadArtAndLyrics(s) updateNowPlaying() publishWidget() @@ -494,6 +498,11 @@ final class Player: ObservableObject { let now = Date() listened += now.timeIntervalSince(lastTick) lastTick = now + // Send the listen as soon as it counts, so it isn't lost if the app is closed before the track ends. + if !scrobbled, let s = current, Scrobbler.countsAsListen(s, listened: listened) { + scrobbled = true + Scrobbler.shared.finished(s, listened: listened, started: listenStart) + } (eng as? UniversalEngine)?.pollAdvance() planNext() if prefs.crossfade > 0, !crossfading, !stopAfterCurrent, !sleepAtTrackEnd, duration > Double(prefs.crossfade) * 2, @@ -511,7 +520,8 @@ final class Player: ObservableObject { private func finishListen() { guard let s = current, listened > 0 else { return } if listened >= min(30, max(1, duration * 0.5)) { PlayStats.shared.played(s) } - Scrobbler.shared.finished(s, listened: listened, started: listenStart) + if !scrobbled { Scrobbler.shared.finished(s, listened: listened, started: listenStart) } + scrobbled = true listened = 0 } diff --git a/ios/App/Services/Scrobbler.swift b/ios/App/Services/Scrobbler.swift index 8227323..32a42c7 100644 --- a/ios/App/Services/Scrobbler.swift +++ b/ios/App/Services/Scrobbler.swift @@ -200,17 +200,24 @@ final class Scrobbler: NSObject, ObservableObject, ASWebAuthenticationPresentati } } + /// Retry queued scrobbles this often while playing (a failed send waits at most this long). + static let retrySeconds: TimeInterval = 120 + func progress(_ s: Song, listened: Double, duration: Double) { - if Date().timeIntervalSince(lastFlush) > 300 { lastFlush = Date(); flush() } + if Date().timeIntervalSince(lastFlush) > Scrobbler.retrySeconds { lastFlush = Date(); flush() } + } + + /// Last.fm / ListenBrainz rule: half the track or 4 minutes; tracks under 30 s never count. + nonisolated static func countsAsListen(_ s: Song, listened: Double) -> Bool { + s.isStream ? listened >= 30 : s.duration >= 30 && listened >= min(s.duration / 2, 240) } func finished(_ s: Song, listened: Double, started: Date) { - let dur = s.duration - let ok = s.isStream ? listened >= 30 : dur >= 30 && listened >= min(dur / 2, 240) - guard ok, !s.displayArtist.isEmpty, !s.displayTitle.isEmpty else { return } + guard Scrobbler.countsAsListen(s, listened: listened), !s.displayArtist.isEmpty, !s.displayTitle.isEmpty else { return } let ts = Int(started.timeIntervalSince1970) if lfmOn { pending.append(entry(s, svc: "lastfm", ts: ts)) } if lbOn { pending.append(entry(s, svc: "listenbrainz", ts: ts)) } + Log.i("scrobble queued (lastfm \(lfmOn), listenbrainz \(lbOn)): \(s.displayArtist) - \(s.displayTitle) at \(ts)") save() flush() } @@ -299,6 +306,8 @@ final class Scrobbler: NSObject, ObservableObject, ASWebAuthenticationPresentati sc.flushing = false sc.pending.removeAll { done.contains($0) } sc.save() + if sent > 0 { Log.i("scrobble sent \(sent)") } + if let err { Log.e("scrobble: \(err)") } if sent == 0, let err { sc.toast = "Scrobbling deferred: \(err)" } } } diff --git a/src/app.rs b/src/app.rs index 85449de..5ceb927 100644 --- a/src/app.rs +++ b/src/app.rs @@ -812,6 +812,7 @@ impl App { let _ = self.player.tick(&mut self.mgr, &self.lib); self.drain_notes(); self.mgr.save_if_due(&self.lib); + self.scrobbler.maybe_periodic(); self.maybe_notify(); self.publish_mpris(); if self.player.is_playing() && self.last_pos_save.elapsed() > Duration::from_secs(5) { @@ -855,6 +856,8 @@ impl App { self.lib.set_kv("resume_pos", &if self.player.song.is_some() { format!("{:.1}", self.player.pos()) } else { "0".into() }); self.mgr.save_all(&self.lib); self.lib.stop_scan(); + self.player.report_listen_on_quit(); + self.drain_notes(); self.player.shutdown(); self.ctx.send_viewport_cmd(egui::ViewportCommand::Close); // never hang on exit (mpv/D-Bus threads): leave for sure shortly after the window closes @@ -1080,6 +1083,7 @@ impl eframe::App for App { let _ = self.player.tick(&mut self.mgr, &self.lib); self.drain_notes(); self.mgr.save_if_due(&self.lib); + self.scrobbler.maybe_periodic(); if self.player.song.is_some() { let p = self.player.pos(); self.spectrum.set_position(p); @@ -1152,6 +1156,8 @@ impl App { self.lib.set_kv("resume_pos", &if self.player.song.is_some() { format!("{:.1}", self.player.pos()) } else { "0".into() }); self.mgr.save_all(&self.lib); self.lib.stop_scan(); + self.player.report_listen_on_quit(); + self.drain_notes(); self.player.shutdown(); } } diff --git a/src/player.rs b/src/player.rs index a2cb359..c3496b5 100644 --- a/src/player.rs +++ b/src/player.rs @@ -362,6 +362,10 @@ pub struct Player { next_engine_id: u8, } +/// Frames stall while the window is hidden (Wayland sends no frame callbacks), but the music keeps +/// playing, so long gaps between ticks still count as listening. Longer than this = the PC slept. +const MAX_TICK_GAP: f64 = 60.0; + fn now_ts() -> i64 { crate::library::now_secs() } @@ -796,6 +800,16 @@ impl Player { self.listen = 0.0; } + /// Report the playing track's listen before the app quits, so it is queued (and sent on the next start). + pub fn report_listen_on_quit(&mut self) { + if let Some(song) = &self.song { + if self.listen > 1.0 { + self.notes.push(Note::TrackFinished { song: song.clone(), listened: self.listen, start_ts: self.start_ts }); + } + } + self.listen = 0.0; + } + fn on_ended(&mut self, mgr: &mut Manager, lib: &Library) { if self.errors >= 5 { self.errors = 0; @@ -857,6 +871,8 @@ impl Player { self.xf_step(); } if self.state != "playing" { + // a pause must not count as listening when playback resumes + self.last_tick = None; return self.xf_t0.is_some(); } if now.duration_since(self.last_poll).as_millis() >= 40 { @@ -872,7 +888,7 @@ impl Player { } if let Some(t) = self.last_tick { let dt = now.duration_since(t).as_secs_f64(); - if dt > 0.0 && dt < 2.0 { + if dt > 0.0 && dt < MAX_TICK_GAP { self.listen += dt; } } diff --git a/src/scrobble.rs b/src/scrobble.rs index 7e219b6..83e98c8 100644 --- a/src/scrobble.rs +++ b/src/scrobble.rs @@ -6,12 +6,31 @@ use crate::library::{song_from_json, song_to_json}; use crate::online::{http_get_json_st, http_post_form_st, http_post_json_st, lastfm_key}; use crate::song::Song; use serde_json::{json, Value}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Instant; const LFM_API: &str = "https://ws.audioscrobbler.com/2.0/"; pub const CALLBACK_PORT: u16 = 47823; +/// Log of scrobble sends and errors (stdout/stderr go nowhere in the desktop app). +/// Rotated to scrobble.log.old past this size, so it never grows without bound. +const LOG_MAX_BYTES: u64 = 256 * 1024; + +pub fn log(line: &str) { + use std::io::Write; + let path = PATHS.data.join("scrobble.log"); + if std::fs::metadata(&path).map(|m| m.len() > LOG_MAX_BYTES).unwrap_or(false) { + let _ = std::fs::rename(&path, PATHS.data.join("scrobble.log.old")); + } + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) { + let _ = writeln!(f, "{} {line}", chrono::Utc::now().format("%Y-%m-%d %H:%M:%SZ")); + } +} + +/// Retry queued scrobbles this often after a failed send (also catches anything a crash left behind). +const RETRY_SECS: u64 = 120; + pub fn has_key() -> bool { let (k, s) = lastfm_key(); !k.is_empty() && !s.is_empty() @@ -276,12 +295,14 @@ pub struct Scrobbler { cache: Arc>>, announced: Option<(String, Instant)>, last_flush: Instant, + /// One flush at a time, so two threads never send the same queued listen. + busy: Arc, } impl Scrobbler { pub fn new(bus: Bus) -> Scrobbler { let cache: Vec = std::fs::read_to_string(PATHS.data.join("scrobble_cache.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default(); - let s = Scrobbler { bus, cache: Arc::new(Mutex::new(cache)), announced: None, last_flush: Instant::now() }; + let s = Scrobbler { bus, cache: Arc::new(Mutex::new(cache)), announced: None, last_flush: Instant::now(), busy: Default::default() }; s.flush_later(10); s } @@ -317,6 +338,7 @@ impl Scrobbler { let (bus, song) = (bus.clone(), song.clone()); std::thread::spawn(move || { if let Err(e) = lfm_call("track.updateNowPlaying", track_params(&song, None), true, true) { + log(&format!("lastfm now playing failed: {e}")); bus.toast(e); } }); @@ -324,6 +346,7 @@ impl Scrobbler { if lb_on() { std::thread::spawn(move || { if let Err((_, e)) = lb_submit("playing_now", vec![lb_payload(&song, None)]) { + log(&format!("listenbrainz now playing failed: {e}")); bus.toast(e); } }); @@ -341,9 +364,9 @@ impl Scrobbler { } pub fn track_finished(&mut self, s: &Song, listened: f64, started: i64) { - let dur = s.duration(); - let ok = if s.is_stream() { listened >= 30.0 } else { dur >= 30.0 && listened >= (dur / 2.0).min(240.0) }; - if !ok || s.display_artist().is_empty() || s.display_title().is_empty() { + let name = format!("{} - {}", s.display_artist(), s.display_title()); + if !counts_as_listen(s.is_stream(), s.duration(), listened) || s.display_artist().is_empty() || s.display_title().is_empty() { + log(&format!("not a listen ({listened:.0} of {:.0} s): {name}", s.duration())); return; } let mut entry = json!({"song": song_to_json(s), "ts": started, "stream_title": s.stream_title}); @@ -359,11 +382,12 @@ impl Scrobbler { } Self::save(&c); } + log(&format!("queued (lastfm {}, listenbrainz {}): {name} at {started}", lfm_on(), lb_on())); self.flush(); } fn flush_later(&self, secs: u64) { - let s = Scrobbler { bus: self.bus.clone(), cache: self.cache.clone(), announced: None, last_flush: Instant::now() }; + let s = Scrobbler { bus: self.bus.clone(), cache: self.cache.clone(), announced: None, last_flush: Instant::now(), busy: self.busy.clone() }; std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_secs(secs)); s.flush(); @@ -371,21 +395,25 @@ impl Scrobbler { } pub fn maybe_periodic(&mut self) { - if self.last_flush.elapsed().as_secs() > 300 { + if self.last_flush.elapsed().as_secs() > RETRY_SECS { self.last_flush = Instant::now(); self.flush(); } } pub fn flush(&self) { - if self.cache.lock().unwrap().is_empty() { + if self.cache.lock().unwrap().is_empty() || self.busy.swap(true, Ordering::SeqCst) { return; } - let (cache, bus) = (self.cache.clone(), self.bus.clone()); - std::thread::spawn(move || match flush_work(&cache) { - Ok(n) if n > 0 => bus.toast(format!("Scrobbled {n} track(s)")), - Ok(_) => {} - Err(e) => bus.toast(format!("Scrobbling deferred: {e}")), + let (cache, bus, busy) = (self.cache.clone(), self.bus.clone(), self.busy.clone()); + std::thread::spawn(move || { + let r = flush_work(&cache); + busy.store(false, Ordering::SeqCst); + match r { + Ok(n) if n > 0 => bus.toast(format!("Scrobbled {n} track(s)")), + Ok(_) => {} + Err(e) => bus.toast(format!("Scrobbling deferred: {e}")), + } }); } @@ -445,6 +473,7 @@ fn flush_work(cache: &Arc>>) -> Result { } match lfm_raw("track.scrobble", params, true, true) { Ok(_) => { + log(&format!("lastfm sent {}: {}", chunk.len(), titles(chunk))); sent += chunk.len(); done.extend(chunk.iter().map(|e| (*e).clone())); } @@ -471,6 +500,7 @@ fn flush_work(cache: &Arc>>) -> Result { let payload: Vec = chunk.iter().map(|e| lb_payload(&song_of(e), e["ts"].as_i64())).collect(); match lb_submit(if payload.len() > 1 { "import" } else { "single" }, payload.clone()) { Ok(_) => { + log(&format!("listenbrainz sent {}: {}", chunk.len(), titles(chunk))); sent += chunk.len(); done.extend(chunk.iter().map(|e| (*e).clone())); } @@ -505,22 +535,51 @@ fn flush_work(cache: &Arc>>) -> Result { } } + if !lfm.is_empty() && !lfm_on() { + log(&format!("lastfm: {} scrobble(s) wait for a login", lfm.len())); + } + if !lb.is_empty() && !lb_on() { + log(&format!("listenbrainz: {} listen(s) wait, ListenBrainz is off or has no token", lb.len())); + } + for e in &errors { + log(&format!("error: {e}")); + } let mut c = cache.lock().unwrap(); c.retain(|e| !done.contains(e)); Scrobbler::save(&c); if sent == 0 && !errors.is_empty() { return Err(errors.join("\n")); } - if let Some(e) = errors.first() { - eprintln!("scrobble: {e}"); - } Ok(sent) } +/// Last.fm / ListenBrainz rule: half the track or 4 minutes, and tracks under 30 s never count. +fn counts_as_listen(stream: bool, dur: f64, listened: f64) -> bool { + if stream { + listened >= 30.0 + } else { + dur >= 30.0 && listened >= (dur / 2.0).min(240.0) + } +} + +fn titles(chunk: &[&Value]) -> String { + let t: Vec = chunk.iter().take(5).map(|e| format!("{} at {}", e["song"]["title"].as_str().unwrap_or("?"), e["ts"])).collect(); + t.join(", ") + if chunk.len() > 5 { ", …" } else { "" } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn listen_rule() { + assert!(counts_as_listen(false, 300.0, 150.0)); + assert!(!counts_as_listen(false, 300.0, 149.0)); + assert!(counts_as_listen(false, 900.0, 240.0)); // 4 minutes is enough for long tracks + assert!(!counts_as_listen(false, 25.0, 25.0)); // under 30 s never counts + assert!(counts_as_listen(true, 0.0, 30.0)); + } + #[test] fn lb_payload_has_ids_and_info() { let mut s = Song::new("https://www.youtube.com/watch?v=x"); diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rs index c59e0c0..1310b4f 100644 --- a/src/ui/dialogs.rs +++ b/src/ui/dialogs.rs @@ -108,7 +108,7 @@ pub struct RipState { } pub struct SettingsState { - page: usize, + pub page: usize, folders: Vec, folder_sel: Option, scan_start: bool, @@ -1445,9 +1445,32 @@ fn lyrics_editor(app: &mut App, ctx: &Context, text: &mut String, to_file: &mut // ---------------------------------------------------------------------- settings const PAGES: &[(&str, &str)] = &[("library_music", "Library"), ("play_arrow", "Playback"), ("palette", "Appearance"), ("scrobble", "Scrobbling"), ("cloud_download", "Metadata"), ("album", "CD")]; +/// Height of one settings line: a button is 36 tall, so labels beside it centre on the same line. +const LINE_H: f32 = 36.0; + +/// A settings line whose items share one centre line, starting at the page's left edge. +fn line(ui: &mut Ui, add: impl FnOnce(&mut Ui)) { + ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), LINE_H), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_height(LINE_H); + add(ui); + }); +} + +/// A settings line with text on the left and controls on the right edge (add `right` items right to left). +fn split_line(ui: &mut Ui, left: impl FnOnce(&mut Ui), right: impl FnOnce(&mut Ui)) { + line(ui, |ui| { + left(ui); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), right); + }); +} + fn row(ui: &mut Ui, col: Color32, label: &str, add: impl FnOnce(&mut Ui)) { - ui.horizontal(|ui| { - ui.add_sized([170.0, 28.0], egui::Label::new(RichText::new(label).color(col))); + line(ui, |ui| { + // left-aligned in a fixed column (add_sized would centre the text and indent it) + ui.allocate_ui_with_layout(egui::vec2(170.0, LINE_H), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(170.0); + ui.label(RichText::new(label).color(col)); + }); add(ui); }); } @@ -1505,6 +1528,7 @@ fn settings_page(app: &mut App, ui: &mut Ui, s: &mut SettingsState) { let mut want_pick: Option<(&'static str, Pick)> = None; let mut login = false; let mut lfm_logout = false; + let mut lfm_discard = false; let mut lb_connect = false; let mut lb_disconnect = false; { @@ -1634,33 +1658,56 @@ fn settings_page(app: &mut App, ui: &mut Ui, s: &mut SettingsState) { }); } 3 => { + let small = |t: String| RichText::new(t).color(theme.on_surface_variant).size(12.5); + // ---- Last.fm: everything for it sits in its own card heading(ui, g, "Last.fm"); let user = settings().get_str("lastfm/user"); let logged = !settings().get_str("lastfm/session").is_empty(); - ui.horizontal(|ui| { - ui.label(RichText::new(if s.lfm_waiting { "Waiting for you to approve access in the browser…".to_string() } else if !s.lfm_msg.is_empty() { s.lfm_msg.clone() } else if logged { format!("Logged in as {user}") } else { "Not logged in".to_string() }).color(theme.on_surface_variant)); - if text_button(ui, g, Some("link"), if logged { "Log in again" } else { "Log in with Last.fm" }, true).clicked() { - login = true; + let lfm_queued = app.scrobbler.pending_for("lastfm"); + card(g).show(ui, |ui| { + ui.set_width(ui.available_width()); + split_line(ui, |ui| { + ui.label(RichText::new(if s.lfm_waiting { "Waiting for you to approve access in the browser…".to_string() } else if !s.lfm_msg.is_empty() { s.lfm_msg.clone() } else if logged { format!("Logged in as {user}") } else { "Not logged in".to_string() }).color(theme.on_surface)); + }, |ui| { + if logged && text_button(ui, g, None, "Log out", false).clicked() { + lfm_logout = true; + } + if text_button(ui, g, Some("link"), if logged { "Log in again" } else { "Log in with Last.fm" }, true).clicked() { + login = true; + } + }); + checkbox(ui, g, &mut s.lfm_on, "Scrobble to Last.fm and send “now playing”"); + if !logged && !s.lfm_waiting { + // nothing reaches Last.fm (and nothing new is queued) until you log in + let msg = if lfm_queued > 0 { format!("Nothing is sent while logged out. {lfm_queued} scrobble(s) wait for your next login.") } else { "Nothing is sent while logged out.".to_string() }; + split_line(ui, |ui| { + ui.label(small(msg)); + }, |ui| { + if lfm_queued > 0 && text_button(ui, g, None, "Discard", false).clicked() { + lfm_discard = true; + } + }); + } else if lfm_queued > 0 { + ui.label(small(format!("{lfm_queued} scrobble(s) waiting to be sent."))); } - if logged && text_button(ui, g, None, "Log out", false).clicked() { - lfm_logout = true; + checkbox(ui, g, &mut s.lfm_own, "Use my own API key instead of Mulberry's (advanced)"); + if s.lfm_own { + row(ui, theme.on_surface_variant, "API key", |ui| { + text_field(ui, g, &mut s.lfm_key, 360.0); + }); + row(ui, theme.on_surface_variant, "Shared secret", |ui| { + text_field(ui, g, &mut s.lfm_secret, 360.0); + }); + ui.label(small("Get a free key at last.fm/api/account/create. Any app name works; leave the callback empty.".into())); } }); - checkbox(ui, g, &mut s.lfm_on, "Scrobble what I play and send “now playing”"); - checkbox(ui, g, &mut s.lfm_own, "Use my own API key instead of Mulberry's (advanced)"); - if s.lfm_own { - row(ui, theme.on_surface_variant, "API key", |ui| { - text_field(ui, g, &mut s.lfm_key, 360.0); - }); - row(ui, theme.on_surface_variant, "Shared secret", |ui| { - text_field(ui, g, &mut s.lfm_secret, 360.0); - }); - ui.label(RichText::new("Get a free key at last.fm/api/account/create — any app name works, leave the callback empty.").color(theme.on_surface_variant).size(12.5)); - } + // ---- ListenBrainz heading(ui, g, "ListenBrainz"); let lb_user = settings().get_str("listenbrainz/user"); let lb_saved = !settings().get_str("listenbrainz/token").is_empty(); - ui.horizontal(|ui| { + let lb_queued = app.scrobbler.pending_for("listenbrainz"); + card(g).show(ui, |ui| { + ui.set_width(ui.available_width()); let status = if s.lb_checking { "Checking your token…".to_string() } else if !s.lb_msg.is_empty() { @@ -1672,28 +1719,33 @@ fn settings_page(app: &mut App, ui: &mut Ui, s: &mut SettingsState) { } else { "Not connected".to_string() }; - ui.label(RichText::new(status).color(theme.on_surface_variant)); - if lb_saved && text_button(ui, g, None, "Disconnect", false).clicked() { - lb_disconnect = true; + split_line(ui, |ui| { + ui.label(RichText::new(status).color(theme.on_surface)); + }, |ui| { + if lb_saved && text_button(ui, g, None, "Disconnect", false).clicked() { + lb_disconnect = true; + } + }); + split_line(ui, |ui| { + ui.label(RichText::new("User token").color(theme.on_surface_variant)); + }, |ui| { + if text_button(ui, g, Some("link"), if lb_saved { "Check" } else { "Connect" }, true).clicked() { + lb_connect = true; + } + secret_field(ui, g, &mut s.lb_token, 300.0); + }); + split_line(ui, |ui| { + ui.label(small("Copy your user token from listenbrainz.org/settings".into())); + }, |ui| { + if text_button(ui, g, None, "Open", false).clicked() { + crate::util::open_url("https://listenbrainz.org/settings/"); + } + }); + checkbox(ui, g, &mut s.lb_on, "Send listens and “now playing” to ListenBrainz"); + if lb_queued > 0 { + ui.label(small(format!("{lb_queued} listen(s) waiting to be sent."))); } }); - row(ui, theme.on_surface_variant, "User token", |ui| { - secret_field(ui, g, &mut s.lb_token, 300.0); - if text_button(ui, g, Some("link"), if lb_saved { "Check" } else { "Connect" }, true).clicked() { - lb_connect = true; - } - }); - ui.horizontal(|ui| { - ui.label(RichText::new("Copy your user token from listenbrainz.org/settings").color(theme.on_surface_variant).size(12.5)); - if text_button(ui, g, None, "Open", false).clicked() { - crate::util::open_url("https://listenbrainz.org/settings/"); - } - }); - checkbox(ui, g, &mut s.lb_on, "Submit listens and “now playing” to ListenBrainz"); - let (pl, pb) = (app.scrobbler.pending_for("lastfm"), app.scrobbler.pending_for("listenbrainz")); - if pl + pb > 0 { - ui.label(RichText::new(format!("Waiting to be sent: {pl} to Last.fm, {pb} to ListenBrainz.")).color(theme.on_surface_variant)); - } } 4 => { heading(ui, g, "Automatic fetching"); @@ -1744,6 +1796,10 @@ fn settings_page(app: &mut App, ui: &mut Ui, s: &mut SettingsState) { s.lfm_msg = "Logged out".into(); app.scrobbler.purge("lastfm"); } + if lfm_discard { + app.scrobbler.purge("lastfm"); + crate::scrobble::log("lastfm: queue discarded by the user"); + } if lb_disconnect { settings().set("listenbrainz/token", ""); settings().set("listenbrainz/user", ""); diff --git a/tests/shots.rs b/tests/shots.rs index 152e131..f88320d 100644 --- a/tests/shots.rs +++ b/tests/shots.rs @@ -137,3 +137,34 @@ fn dialogs_tour() { h.state_mut().dialog = Some(mulberry::ui::dialogs::Dialog::lyrics_editor("[00:01.00]hello\n[00:05.00]world".into())); shot(&mut h, &out, "d_lyrics"); } + +/// Settings › Scrobbling with Last.fm logged out (queue waiting) and ListenBrainz connected. +#[test] +fn scrobble_settings() { + let out = setup_env(); + let st = mulberry::config::settings(); + st.set("lastfm/enabled", true); + st.set("lastfm/session", ""); + st.set("listenbrainz/enabled", true); + st.set("listenbrainz/token", "test-token"); + st.set("listenbrainz/user", "tester"); + let mut h = new_harness(); + settle(&mut h, 20); + h.state_mut().do_action("settings"); + settle(&mut h, 3); + if let Some(mulberry::ui::dialogs::Dialog::Settings(s)) = h.state_mut().dialog.as_mut() { + s.page = 3; + } + shot(&mut h, &out, "scrobble_settings"); + if let Some(mulberry::ui::dialogs::Dialog::Settings(s)) = h.state_mut().dialog.as_mut() { + s.page = 1; + } + shot(&mut h, &out, "playback_settings"); + // the startup flush (10 s) writes the scrobble log; queued Last.fm scrobbles wait while logged out + std::fs::write(mulberry::config::PATHS.data.join("scrobble_cache.json"), r#"[{"svc":"lastfm","ts":1796000000,"song":{"url":"/x.mp3","title":"T","artist":"A"}}]"#).unwrap(); + let _ = std::fs::remove_file(mulberry::config::PATHS.data.join("scrobble.log")); + let _ = mulberry::scrobble::Scrobbler::new(h.state().bus.clone()); + std::thread::sleep(std::time::Duration::from_secs(12)); + let log = std::fs::read_to_string(mulberry::config::PATHS.data.join("scrobble.log")).unwrap_or_default(); + assert!(log.contains("lastfm: 1 scrobble(s) wait for a login"), "scrobble.log: {log}"); +}