feat(slint): Last.fm and ListenBrainz scrobblers wired to player and settings
Re-implements the parked scrobblers-wip stash intent on the current tree (the stash no longer applied; it remains untouched in the stash list) with three corrections: the Last.fm offline queue uses the SHARED per-user offline_settings.db scrobble_queue (byte-identical SQL to Tauri - queues flush from either frontend) instead of a private table; the ListenBrainz cache opens Tauri's per-user path so LB creds and listen_queue are truly shared (a Tauri LB sign-in pre-seeds Slint); and the queue flush is driven by the offline engine's online edge (plus initial flush), not login-only. New frontend-agnostic qbz_app::settings::scrobblers store (master enable, Last.fm session/username, LB token/username; tests) and the shared scrobble-queue API on OfflineModeStore. Player wiring hooks the de-duped track-change edge inside the QConnect remote gate: now-playing fires on change (skipped offline), the scrobble arms at min(50%, 240s) with a generation counter cancelling stale timers, all sources scrobble (Tauri parity incl. the #360 version-enriched title). Offline or call failure queues; Last.fm flush honors the 50-batch and 14-day cutoff. Settings gains an Integrations section (Plex-section idiom): Last.fm browser-auth connect/finish/disconnect, ListenBrainz token field + validate, per-service enable toggles. Known gap documented: Last.fm creds cannot be shared with Tauri (webview localStorage); LB creds and both queues are shared. cc
This commit is contained in:
12 files changed
+1945
-2
No files matched your search
@@ -23,7 +23,7 @@ pub mod connectivity;
|
||||
pub mod store;
|
||||
|
||||
pub use connectivity::{Connectivity, ConnectivityActor, ConnectivitySnapshot};
|
||||
pub use store::{OfflineModeSettings, OfflineModeStore};
|
||||
pub use store::{OfflineModeSettings, OfflineModeStore, QueuedScrobble};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
|
||||
@@ -28,6 +28,21 @@ pub struct OfflineModeSettings {
|
||||
pub show_network_folders_in_manual_offline: bool,
|
||||
}
|
||||
|
||||
/// One row of the Last.fm offline scrobble queue (`scrobble_queue`). Mirrors
|
||||
/// Tauri's `offline::QueuedScrobble` — same table, same per-user file, so
|
||||
/// scrobbles queued by one frontend flush from the other.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct QueuedScrobble {
|
||||
pub id: i64,
|
||||
pub artist: String,
|
||||
pub track: String,
|
||||
pub album: Option<String>,
|
||||
pub timestamp: i64,
|
||||
pub created_at: i64,
|
||||
pub sent: bool,
|
||||
}
|
||||
|
||||
pub struct OfflineModeStore {
|
||||
conn: Connection,
|
||||
}
|
||||
@@ -162,6 +177,121 @@ impl OfflineModeStore {
|
||||
.map_err(|e| format!("Failed to set pre_offline_stream_first_track: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// === Last.fm scrobble queue ===
|
||||
//
|
||||
// Minimal API over the `scrobble_queue` table the base schema already
|
||||
// creates. SQL kept IDENTICAL to Tauri's `src-tauri/src/offline/mod.rs`
|
||||
// scrobble-queue methods so both frontends interoperate on the same rows.
|
||||
|
||||
/// Queue a scrobble for later submission to Last.fm.
|
||||
pub fn queue_scrobble(
|
||||
&self,
|
||||
artist: &str,
|
||||
track: &str,
|
||||
album: Option<&str>,
|
||||
timestamp: i64,
|
||||
) -> Result<i64, String> {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0);
|
||||
|
||||
self.conn
|
||||
.execute(
|
||||
"INSERT INTO scrobble_queue (artist, track, album, timestamp, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![artist, track, album, timestamp, now],
|
||||
)
|
||||
.map_err(|e| format!("Failed to queue scrobble: {}", e))?;
|
||||
|
||||
Ok(self.conn.last_insert_rowid())
|
||||
}
|
||||
|
||||
/// Unsent scrobbles, oldest first (cap at 50 — the Last.fm batch limit).
|
||||
pub fn get_queued_scrobbles(&self, limit: u32) -> Result<Vec<QueuedScrobble>, String> {
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT id, artist, track, album, timestamp, created_at, sent
|
||||
FROM scrobble_queue WHERE sent = 0 ORDER BY timestamp ASC LIMIT ?1",
|
||||
)
|
||||
.map_err(|e| format!("Failed to prepare statement: {}", e))?;
|
||||
|
||||
let scrobbles = stmt
|
||||
.query_map(params![limit], |row| {
|
||||
Ok(QueuedScrobble {
|
||||
id: row.get(0)?,
|
||||
artist: row.get(1)?,
|
||||
track: row.get(2)?,
|
||||
album: row.get(3)?,
|
||||
timestamp: row.get(4)?,
|
||||
created_at: row.get(5)?,
|
||||
sent: row.get::<_, i64>(6)? != 0,
|
||||
})
|
||||
})
|
||||
.map_err(|e| format!("Failed to query queued scrobbles: {}", e))?;
|
||||
|
||||
scrobbles
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| format!("Failed to collect queued scrobbles: {}", e))
|
||||
}
|
||||
|
||||
/// Batch mark scrobbles as sent.
|
||||
pub fn mark_scrobbles_sent(&self, ids: &[i64]) -> Result<(), String> {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let placeholders: Vec<String> = ids.iter().map(|_| "?".to_string()).collect();
|
||||
let sql = format!(
|
||||
"UPDATE scrobble_queue SET sent = 1 WHERE id IN ({})",
|
||||
placeholders.join(",")
|
||||
);
|
||||
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare(&sql)
|
||||
.map_err(|e| format!("Failed to prepare statement: {}", e))?;
|
||||
|
||||
let sql_params: Vec<&dyn rusqlite::ToSql> =
|
||||
ids.iter().map(|id| id as &dyn rusqlite::ToSql).collect();
|
||||
stmt.execute(sql_params.as_slice())
|
||||
.map_err(|e| format!("Failed to mark scrobbles as sent: {}", e))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete sent scrobbles older than `older_than_days` (post-flush cleanup).
|
||||
pub fn cleanup_sent_scrobbles(&self, older_than_days: u32) -> Result<u32, String> {
|
||||
let cutoff = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
- (older_than_days as i64 * 24 * 60 * 60);
|
||||
|
||||
let deleted = self
|
||||
.conn
|
||||
.execute(
|
||||
"DELETE FROM scrobble_queue WHERE sent = 1 AND created_at < ?1",
|
||||
params![cutoff],
|
||||
)
|
||||
.map_err(|e| format!("Failed to cleanup sent scrobbles: {}", e))?;
|
||||
|
||||
Ok(deleted as u32)
|
||||
}
|
||||
|
||||
/// Count of queued (unsent) scrobbles.
|
||||
pub fn queued_scrobble_count(&self) -> Result<u32, String> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM scrobble_queue WHERE sent = 0",
|
||||
[],
|
||||
|row| row.get::<_, i64>(0),
|
||||
)
|
||||
.map(|count| count as u32)
|
||||
.map_err(|e| format!("Failed to count queued scrobbles: {}", e))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -217,6 +347,41 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scrobble_queue_round_trips_and_marks_sent() {
|
||||
let dir = unique_test_dir("offline-store-scrobbles");
|
||||
let store = OfflineModeStore::new_at(&dir).unwrap();
|
||||
|
||||
let id1 = store
|
||||
.queue_scrobble("Artist A", "Track 1", Some("Album X"), 1000)
|
||||
.unwrap();
|
||||
let id2 = store.queue_scrobble("Artist B", "Track 2", None, 2000).unwrap();
|
||||
assert_ne!(id1, id2);
|
||||
assert_eq!(store.queued_scrobble_count().unwrap(), 2);
|
||||
|
||||
let pending = store.get_queued_scrobbles(50).unwrap();
|
||||
assert_eq!(pending.len(), 2);
|
||||
// Oldest first.
|
||||
assert_eq!(pending[0].timestamp, 1000);
|
||||
assert_eq!(pending[0].artist, "Artist A");
|
||||
assert_eq!(pending[0].album.as_deref(), Some("Album X"));
|
||||
assert_eq!(pending[1].album, None);
|
||||
|
||||
store.mark_scrobbles_sent(&[pending[0].id]).unwrap();
|
||||
assert_eq!(store.queued_scrobble_count().unwrap(), 1);
|
||||
let remaining = store.get_queued_scrobbles(50).unwrap();
|
||||
assert_eq!(remaining.len(), 1);
|
||||
assert_eq!(remaining[0].timestamp, 2000);
|
||||
|
||||
// Cleanup only touches SENT rows older than the cutoff — the fresh
|
||||
// unsent row always survives (the just-sent row's created_at is "now",
|
||||
// so it is not older than any cutoff either).
|
||||
let _ = store.cleanup_sent_scrobbles(7).unwrap();
|
||||
assert_eq!(store.queued_scrobble_count().unwrap(), 1);
|
||||
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_first_snapshot_round_trips() {
|
||||
let dir = unique_test_dir("offline-store-snapshot");
|
||||
|
||||
@@ -9,5 +9,6 @@ pub mod library;
|
||||
pub mod playback;
|
||||
pub mod plex;
|
||||
pub mod remote_control;
|
||||
pub mod scrobblers;
|
||||
pub mod subscription;
|
||||
pub mod tray;
|
||||
@@ -0,0 +1,462 @@
|
||||
//! Portable scrobbler credential storage (Last.fm + ListenBrainz).
|
||||
//!
|
||||
//! Owns the persisted scrobbler settings for the Slint frontend, the part the
|
||||
//! Tauri build kept in per-user localStorage:
|
||||
//! - the master enable + collapse UI flags,
|
||||
//! - Last.fm: session key + username + per-service enable flag
|
||||
//! (replaces the `qbz-lastfm-session-key` / `qbz-lastfm-scrobbling`
|
||||
//! localStorage keys — webview localStorage is unreachable from Slint,
|
||||
//! so Last.fm credentials cannot be shared with the Tauri build),
|
||||
//! - ListenBrainz: token + username + per-service enable flag. The token is
|
||||
//! ALSO written through to the shared `ListenBrainzCache.credentials` row
|
||||
//! by the Slint `scrobble` controller, so LB credentials DO stay shared
|
||||
//! with the Tauri build; this copy is the Slint UI's fast read.
|
||||
//!
|
||||
//! The Last.fm offline queue does NOT live here: it is the `scrobble_queue`
|
||||
//! table in the shared per-user `offline_settings.db`
|
||||
//! ([`crate::offline_mode::store::OfflineModeStore`]) — same rows Tauri queues
|
||||
//! into and flushes from. The ListenBrainz offline queue is the
|
||||
//! `ListenBrainzCache.listen_queue` (qbz-integrations).
|
||||
//!
|
||||
//! Mirrors the [`super::plex`] store: a single-row SQLite settings table
|
||||
//! re-pointed at the active user's data directory via
|
||||
//! [`ScrobblerSettingsState::init_at`] at login, so credentials are scoped per
|
||||
//! Qobuz user.
|
||||
//!
|
||||
//! Runtime concerns — the auth flows, the now-playing + scrobble fire, the
|
||||
//! `min(50% of duration, 240s)` timer, the offline flush — live in the Slint
|
||||
//! `scrobble` controller and call the `qbz-integrations` clients directly.
|
||||
|
||||
use log::info;
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct ScrobblerSettings {
|
||||
/// Master toggle. When false, the whole scrobblers section body is hidden.
|
||||
/// Default OFF — integrations are opt-in.
|
||||
pub enabled: bool,
|
||||
/// Collapse chevron state. Body renders only when `enabled && !ui_collapsed`.
|
||||
pub ui_collapsed: bool,
|
||||
|
||||
// --- Last.fm ---
|
||||
/// Per-service scrobbling enable flag (replaces `qbz-lastfm-scrobbling`).
|
||||
pub lastfm_enabled: bool,
|
||||
/// Last.fm session key (`get_session().key`). Empty = not authenticated.
|
||||
pub lastfm_session_key: String,
|
||||
/// Last.fm username (`LastFmSession.name`), for the "Signed in as …" label.
|
||||
pub lastfm_username: String,
|
||||
|
||||
// --- ListenBrainz ---
|
||||
/// Per-service enable flag.
|
||||
pub listenbrainz_enabled: bool,
|
||||
/// ListenBrainz user token. Empty = not authenticated.
|
||||
pub listenbrainz_token: String,
|
||||
/// ListenBrainz username (`UserInfo.user_name`).
|
||||
pub listenbrainz_username: String,
|
||||
}
|
||||
|
||||
impl ScrobblerSettings {
|
||||
/// Last.fm has credentials (independent of the enable flags).
|
||||
pub fn lastfm_is_authed(&self) -> bool {
|
||||
!self.lastfm_session_key.is_empty()
|
||||
}
|
||||
|
||||
/// ListenBrainz has credentials (independent of the enable flags).
|
||||
pub fn listenbrainz_is_authed(&self) -> bool {
|
||||
!self.listenbrainz_token.is_empty()
|
||||
}
|
||||
|
||||
/// Last.fm should actually scrobble: master + service on + authed.
|
||||
pub fn lastfm_active(&self) -> bool {
|
||||
self.enabled && self.lastfm_enabled && self.lastfm_is_authed()
|
||||
}
|
||||
|
||||
/// ListenBrainz should actually scrobble: master + service on + authed.
|
||||
pub fn listenbrainz_active(&self) -> bool {
|
||||
self.enabled && self.listenbrainz_enabled && self.listenbrainz_is_authed()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ScrobblerSettingsStore {
|
||||
conn: Connection,
|
||||
}
|
||||
|
||||
impl ScrobblerSettingsStore {
|
||||
fn open_at(dir: &Path, db_name: &str) -> Result<Self, String> {
|
||||
std::fs::create_dir_all(dir)
|
||||
.map_err(|e| format!("Failed to create data directory: {}", e))?;
|
||||
|
||||
let db_path = dir.join(db_name);
|
||||
let conn = Connection::open(&db_path)
|
||||
.map_err(|e| format!("Failed to open scrobbler settings database: {}", e))?;
|
||||
|
||||
conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;")
|
||||
.map_err(|e| format!("Failed to enable WAL for scrobbler settings database: {}", e))?;
|
||||
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS scrobbler_settings (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
enabled INTEGER NOT NULL DEFAULT 0,
|
||||
ui_collapsed INTEGER NOT NULL DEFAULT 0,
|
||||
lastfm_enabled INTEGER NOT NULL DEFAULT 0,
|
||||
lastfm_session_key TEXT NOT NULL DEFAULT '',
|
||||
lastfm_username TEXT NOT NULL DEFAULT '',
|
||||
listenbrainz_enabled INTEGER NOT NULL DEFAULT 0,
|
||||
listenbrainz_token TEXT NOT NULL DEFAULT '',
|
||||
listenbrainz_username TEXT NOT NULL DEFAULT ''
|
||||
);",
|
||||
)
|
||||
.map_err(|e| format!("Failed to create scrobbler settings table: {}", e))?;
|
||||
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO scrobbler_settings
|
||||
(id, enabled, ui_collapsed, lastfm_enabled, lastfm_session_key,
|
||||
lastfm_username, listenbrainz_enabled, listenbrainz_token,
|
||||
listenbrainz_username)
|
||||
VALUES (1, 0, 0, 0, '', '', 0, '', '')",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| format!("Failed to insert default scrobbler settings: {}", e))?;
|
||||
|
||||
info!("[ScrobblerSettings] Database initialized");
|
||||
|
||||
Ok(Self { conn })
|
||||
}
|
||||
|
||||
pub fn new_at(base_dir: &Path) -> Result<Self, String> {
|
||||
Self::open_at(base_dir, "scrobbler_settings.db")
|
||||
}
|
||||
|
||||
pub fn get_settings(&self) -> Result<ScrobblerSettings, String> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT enabled, ui_collapsed, lastfm_enabled, lastfm_session_key,
|
||||
lastfm_username, listenbrainz_enabled, listenbrainz_token,
|
||||
listenbrainz_username
|
||||
FROM scrobbler_settings WHERE id = 1",
|
||||
[],
|
||||
|row| {
|
||||
let enabled: i32 = row.get(0)?;
|
||||
let ui_collapsed: i32 = row.get(1)?;
|
||||
let lastfm_enabled: i32 = row.get(2)?;
|
||||
let lastfm_session_key: String = row.get(3)?;
|
||||
let lastfm_username: String = row.get(4)?;
|
||||
let listenbrainz_enabled: i32 = row.get(5)?;
|
||||
let listenbrainz_token: String = row.get(6)?;
|
||||
let listenbrainz_username: String = row.get(7)?;
|
||||
Ok(ScrobblerSettings {
|
||||
enabled: enabled != 0,
|
||||
ui_collapsed: ui_collapsed != 0,
|
||||
lastfm_enabled: lastfm_enabled != 0,
|
||||
lastfm_session_key,
|
||||
lastfm_username,
|
||||
listenbrainz_enabled: listenbrainz_enabled != 0,
|
||||
listenbrainz_token,
|
||||
listenbrainz_username,
|
||||
})
|
||||
},
|
||||
)
|
||||
.map_err(|e| format!("Failed to get scrobbler settings: {}", e))
|
||||
}
|
||||
|
||||
pub fn set_enabled(&self, value: bool) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE scrobbler_settings SET enabled = ?1 WHERE id = 1",
|
||||
params![if value { 1 } else { 0 }],
|
||||
)
|
||||
.map_err(|e| format!("Failed to set scrobbler enabled: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_ui_collapsed(&self, value: bool) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE scrobbler_settings SET ui_collapsed = ?1 WHERE id = 1",
|
||||
params![if value { 1 } else { 0 }],
|
||||
)
|
||||
.map_err(|e| format!("Failed to set scrobbler ui_collapsed: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// --- Last.fm ---
|
||||
|
||||
pub fn set_lastfm_enabled(&self, value: bool) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE scrobbler_settings SET lastfm_enabled = ?1 WHERE id = 1",
|
||||
params![if value { 1 } else { 0 }],
|
||||
)
|
||||
.map_err(|e| format!("Failed to set lastfm_enabled: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persist the Last.fm session key + username together (after `get_session`).
|
||||
pub fn set_lastfm_session(&self, key: &str, username: &str) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE scrobbler_settings
|
||||
SET lastfm_session_key = ?1, lastfm_username = ?2 WHERE id = 1",
|
||||
params![key.trim(), username.trim()],
|
||||
)
|
||||
.map_err(|e| format!("Failed to set lastfm session: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sign out of Last.fm: clear key + username, keep `lastfm_enabled` flag.
|
||||
pub fn disconnect_lastfm(&self) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE scrobbler_settings
|
||||
SET lastfm_session_key = '', lastfm_username = '' WHERE id = 1",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| format!("Failed to disconnect Last.fm: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// --- ListenBrainz ---
|
||||
|
||||
pub fn set_listenbrainz_enabled(&self, value: bool) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE scrobbler_settings SET listenbrainz_enabled = ?1 WHERE id = 1",
|
||||
params![if value { 1 } else { 0 }],
|
||||
)
|
||||
.map_err(|e| format!("Failed to set listenbrainz_enabled: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persist the ListenBrainz token + username together (after `set_token`).
|
||||
pub fn set_listenbrainz_token(&self, token: &str, username: &str) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE scrobbler_settings
|
||||
SET listenbrainz_token = ?1, listenbrainz_username = ?2 WHERE id = 1",
|
||||
params![token.trim(), username.trim()],
|
||||
)
|
||||
.map_err(|e| format!("Failed to set listenbrainz token: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sign out of ListenBrainz: clear token + username, keep enable flag.
|
||||
pub fn disconnect_listenbrainz(&self) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE scrobbler_settings
|
||||
SET listenbrainz_token = '', listenbrainz_username = '' WHERE id = 1",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| format!("Failed to disconnect ListenBrainz: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ScrobblerSettingsState {
|
||||
pub store: Arc<Mutex<Option<ScrobblerSettingsStore>>>,
|
||||
}
|
||||
|
||||
impl Default for ScrobblerSettingsState {
|
||||
fn default() -> Self {
|
||||
Self::new_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl ScrobblerSettingsState {
|
||||
pub fn new_empty() -> Self {
|
||||
Self {
|
||||
store: Arc::new(Mutex::new(None)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_at(&self, base_dir: &Path) -> Result<(), String> {
|
||||
let new_store = ScrobblerSettingsStore::new_at(base_dir)?;
|
||||
let mut guard = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|_| "Failed to lock scrobbler settings store".to_string())?;
|
||||
*guard = Some(new_store);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn teardown(&self) -> Result<(), String> {
|
||||
let mut guard = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|_| "Failed to lock scrobbler settings store".to_string())?;
|
||||
*guard = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn with_store<T>(
|
||||
&self,
|
||||
f: impl FnOnce(&ScrobblerSettingsStore) -> Result<T, String>,
|
||||
) -> Result<T, String> {
|
||||
let guard = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|_| "Failed to lock scrobbler settings store".to_string())?;
|
||||
let store = guard.as_ref().ok_or("No active session - please log in")?;
|
||||
f(store)
|
||||
}
|
||||
|
||||
pub fn get_settings(&self) -> Result<ScrobblerSettings, String> {
|
||||
self.with_store(|s| s.get_settings())
|
||||
}
|
||||
|
||||
pub fn set_enabled(&self, value: bool) -> Result<(), String> {
|
||||
self.with_store(|s| s.set_enabled(value))
|
||||
}
|
||||
|
||||
pub fn set_ui_collapsed(&self, value: bool) -> Result<(), String> {
|
||||
self.with_store(|s| s.set_ui_collapsed(value))
|
||||
}
|
||||
|
||||
pub fn set_lastfm_enabled(&self, value: bool) -> Result<(), String> {
|
||||
self.with_store(|s| s.set_lastfm_enabled(value))
|
||||
}
|
||||
|
||||
pub fn set_lastfm_session(&self, key: &str, username: &str) -> Result<(), String> {
|
||||
self.with_store(|s| s.set_lastfm_session(key, username))
|
||||
}
|
||||
|
||||
pub fn disconnect_lastfm(&self) -> Result<(), String> {
|
||||
self.with_store(|s| s.disconnect_lastfm())
|
||||
}
|
||||
|
||||
pub fn set_listenbrainz_enabled(&self, value: bool) -> Result<(), String> {
|
||||
self.with_store(|s| s.set_listenbrainz_enabled(value))
|
||||
}
|
||||
|
||||
pub fn set_listenbrainz_token(&self, token: &str, username: &str) -> Result<(), String> {
|
||||
self.with_store(|s| s.set_listenbrainz_token(token, username))
|
||||
}
|
||||
|
||||
pub fn disconnect_listenbrainz(&self) -> Result<(), String> {
|
||||
self.with_store(|s| s.disconnect_listenbrainz())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn unique_test_dir(name: &str) -> std::path::PathBuf {
|
||||
let nonce = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
std::env::temp_dir().join(format!("qbz-app-{name}-{}-{nonce}", std::process::id()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scrobbler_settings_default_is_unconfigured() {
|
||||
let s = ScrobblerSettings::default();
|
||||
assert!(!s.enabled);
|
||||
assert!(!s.ui_collapsed);
|
||||
assert!(!s.lastfm_enabled);
|
||||
assert!(s.lastfm_session_key.is_empty());
|
||||
assert!(s.lastfm_username.is_empty());
|
||||
assert!(!s.listenbrainz_enabled);
|
||||
assert!(s.listenbrainz_token.is_empty());
|
||||
assert!(s.listenbrainz_username.is_empty());
|
||||
assert!(!s.lastfm_is_authed());
|
||||
assert!(!s.listenbrainz_is_authed());
|
||||
assert!(!s.lastfm_active());
|
||||
assert!(!s.listenbrainz_active());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scrobbler_store_returns_defaults() {
|
||||
let dir = unique_test_dir("scrobbler-default");
|
||||
let store = ScrobblerSettingsStore::new_at(&dir).expect("open store");
|
||||
let s = store.get_settings().expect("get settings");
|
||||
assert!(!s.enabled);
|
||||
assert!(!s.lastfm_is_authed());
|
||||
assert!(!s.listenbrainz_is_authed());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scrobbler_persists_all_fields() {
|
||||
let dir = unique_test_dir("scrobbler-persist");
|
||||
{
|
||||
let store = ScrobblerSettingsStore::new_at(&dir).expect("open store");
|
||||
store.set_enabled(true).expect("enabled");
|
||||
store.set_ui_collapsed(true).expect("collapsed");
|
||||
store.set_lastfm_enabled(true).expect("lfm enabled");
|
||||
store
|
||||
.set_lastfm_session(" sk-123 ", " alice ")
|
||||
.expect("lfm session");
|
||||
store.set_listenbrainz_enabled(true).expect("lb enabled");
|
||||
store
|
||||
.set_listenbrainz_token(" tok-456 ", " bob ")
|
||||
.expect("lb token");
|
||||
}
|
||||
let reopened = ScrobblerSettingsStore::new_at(&dir).expect("reopen store");
|
||||
let s = reopened.get_settings().expect("get settings");
|
||||
assert!(s.enabled);
|
||||
assert!(s.ui_collapsed);
|
||||
assert!(s.lastfm_enabled);
|
||||
// set_lastfm_session trims whitespace.
|
||||
assert_eq!(s.lastfm_session_key, "sk-123");
|
||||
assert_eq!(s.lastfm_username, "alice");
|
||||
assert!(s.listenbrainz_enabled);
|
||||
assert_eq!(s.listenbrainz_token, "tok-456");
|
||||
assert_eq!(s.listenbrainz_username, "bob");
|
||||
assert!(s.lastfm_active());
|
||||
assert!(s.listenbrainz_active());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scrobbler_disconnect_keeps_enable_flags() {
|
||||
let dir = unique_test_dir("scrobbler-disconnect");
|
||||
let store = ScrobblerSettingsStore::new_at(&dir).expect("open store");
|
||||
store.set_enabled(true).expect("enabled");
|
||||
store.set_lastfm_enabled(true).expect("lfm enabled");
|
||||
store.set_lastfm_session("sk", "alice").expect("lfm session");
|
||||
store.set_listenbrainz_enabled(true).expect("lb enabled");
|
||||
store.set_listenbrainz_token("tok", "bob").expect("lb token");
|
||||
|
||||
store.disconnect_lastfm().expect("disconnect lfm");
|
||||
store.disconnect_listenbrainz().expect("disconnect lb");
|
||||
|
||||
let s = store.get_settings().expect("get settings");
|
||||
// Creds cleared.
|
||||
assert!(s.lastfm_session_key.is_empty());
|
||||
assert!(s.lastfm_username.is_empty());
|
||||
assert!(s.listenbrainz_token.is_empty());
|
||||
assert!(s.listenbrainz_username.is_empty());
|
||||
// Enable flags preserved (so re-auth resumes scrobbling).
|
||||
assert!(s.enabled);
|
||||
assert!(s.lastfm_enabled);
|
||||
assert!(s.listenbrainz_enabled);
|
||||
// No longer authed -> not active.
|
||||
assert!(!s.lastfm_active());
|
||||
assert!(!s.listenbrainz_active());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scrobbler_state_requires_init() {
|
||||
let state = ScrobblerSettingsState::new_empty();
|
||||
assert!(state.get_settings().is_err());
|
||||
|
||||
let dir = unique_test_dir("scrobbler-state");
|
||||
state.init_at(&dir).expect("init at temp dir");
|
||||
state
|
||||
.set_lastfm_session("sk", "alice")
|
||||
.expect("set session via state");
|
||||
let s = state.get_settings().expect("get via state");
|
||||
assert!(s.lastfm_is_authed());
|
||||
assert_eq!(s.lastfm_username, "alice");
|
||||
|
||||
state.teardown().expect("teardown");
|
||||
assert!(state.get_settings().is_err());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user