From c207a60ba4b34d8318b7d7e35cb28485b12c28a9 Mon Sep 17 00:00:00 2001 From: boxdot Date: Fri, 13 Feb 2026 09:29:26 +0100 Subject: [PATCH] fix: UI lag The lag was due to using sqlite in non-WAL mode. --- src-tauri/src/artist_blacklist/service.rs | 14 +- src-tauri/src/artist_vectors/store.rs | 12 +- src-tauri/src/audio/loudness_cache.rs | 23 +- src-tauri/src/config/audio_settings.rs | 207 ++- src-tauri/src/config/developer_settings.rs | 33 +- src-tauri/src/config/download_settings.rs | 13 +- src-tauri/src/config/favorites_cache.rs | 33 +- src-tauri/src/config/graphics_settings.rs | 87 +- src-tauri/src/config/legal_settings.rs | 21 +- src-tauri/src/config/playback_preferences.rs | 50 +- .../src/config/remote_control_settings.rs | 159 ++- src-tauri/src/config/subscription_state.rs | 19 +- src-tauri/src/config/tray_settings.rs | 59 +- src-tauri/src/config/window_settings.rs | 35 +- src-tauri/src/library/database.rs | 1234 +++++++++++------ src-tauri/src/listenbrainz/cache.rs | 32 +- src-tauri/src/lyrics/cache.rs | 12 +- src-tauri/src/musicbrainz/cache.rs | 15 +- src-tauri/src/offline/mod.rs | 271 +++- src-tauri/src/offline_cache/db.rs | 257 ++-- src-tauri/src/plex/mod.rs | 117 +- src-tauri/src/radio_engine/db.rs | 9 +- src-tauri/src/reco_store/db.rs | 74 +- src-tauri/src/session_store/mod.rs | 67 +- src-tauri/src/updates/mod.rs | 50 +- 25 files changed, 1970 insertions(+), 933 deletions(-) diff --git a/src-tauri/src/artist_blacklist/service.rs b/src-tauri/src/artist_blacklist/service.rs index 4ab56a854..9861b7b63 100644 --- a/src-tauri/src/artist_blacklist/service.rs +++ b/src-tauri/src/artist_blacklist/service.rs @@ -29,7 +29,7 @@ impl BlacklistService { .map_err(|e| format!("Failed to open blacklist database: {}", e))?; // Enable WAL mode for better concurrent access - conn.execute_batch("PRAGMA journal_mode=WAL;") + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") .map_err(|e| format!("Failed to set WAL mode: {}", e))?; let service = Self { @@ -97,7 +97,10 @@ impl BlacklistService { .map_err(|_| "Failed to acquire write lock")?; *set = ids.into_iter().collect(); - log::info!("[Blacklist] Loaded {} blacklisted artists into memory", count); + log::info!( + "[Blacklist] Loaded {} blacklisted artists into memory", + count + ); Ok(()) } @@ -138,7 +141,12 @@ impl BlacklistService { } /// Add an artist to the blacklist - pub fn add(&self, artist_id: u64, artist_name: &str, notes: Option<&str>) -> Result<(), String> { + pub fn add( + &self, + artist_id: u64, + artist_name: &str, + notes: Option<&str>, + ) -> Result<(), String> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() diff --git a/src-tauri/src/artist_vectors/store.rs b/src-tauri/src/artist_vectors/store.rs index c45fed750..9256444e4 100644 --- a/src-tauri/src/artist_vectors/store.rs +++ b/src-tauri/src/artist_vectors/store.rs @@ -508,9 +508,11 @@ impl ArtistVectorStore { let vector_count: i64 = self .conn - .query_row("SELECT COUNT(DISTINCT artist_idx) FROM vector_entries", [], |row| { - row.get(0) - }) + .query_row( + "SELECT COUNT(DISTINCT artist_idx) FROM vector_entries", + [], + |row| row.get(0), + ) .map_err(|e| format!("Failed to count vectors: {}", e))?; let entry_count: i64 = self @@ -663,7 +665,9 @@ mod tests { // Query similar to A let query = vec_a.clone(); - let results = store.find_nearest(&query, 5, &["artist-a".to_string()]).unwrap(); + let results = store + .find_nearest(&query, 5, &["artist-a".to_string()]) + .unwrap(); // B should be most similar (both connect to each other) assert!(!results.is_empty()); diff --git a/src-tauri/src/audio/loudness_cache.rs b/src-tauri/src/audio/loudness_cache.rs index 68caedcea..bcc91d772 100644 --- a/src-tauri/src/audio/loudness_cache.rs +++ b/src-tauri/src/audio/loudness_cache.rs @@ -5,7 +5,7 @@ //! //! Thread-safe via `Mutex`. -use rusqlite::{Connection, params}; +use rusqlite::{params, Connection}; use std::sync::Mutex; #[derive(Debug, Clone)] @@ -33,6 +33,9 @@ impl LoudnessCache { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open loudness cache database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for loudness cache database: {}", e))?; + conn.execute_batch( "CREATE TABLE IF NOT EXISTS track_loudness ( track_id INTEGER PRIMARY KEY, @@ -40,12 +43,15 @@ impl LoudnessCache { peak REAL NOT NULL DEFAULT 0.0, source TEXT NOT NULL DEFAULT 'ebur128', created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')) - )" - ).map_err(|e| format!("Failed to create loudness table: {}", e))?; + )", + ) + .map_err(|e| format!("Failed to create loudness table: {}", e))?; log::info!("[LoudnessCache] Opened at {}", db_path.display()); - Ok(Self { conn: Mutex::new(conn) }) + Ok(Self { + conn: Mutex::new(conn), + }) } /// Look up cached loudness for a track. @@ -61,7 +67,8 @@ impl LoudnessCache { source: row.get(2)?, }) }, - ).ok() + ) + .ok() } /// Store or update loudness data for a track. @@ -73,7 +80,11 @@ impl LoudnessCache { params![track_id as i64, gain_db as f64, peak as f64, source], ); if let Err(e) = result { - log::warn!("[LoudnessCache] Failed to store loudness for track {}: {}", track_id, e); + log::warn!( + "[LoudnessCache] Failed to store loudness for track {}: {}", + track_id, + e + ); } } } diff --git a/src-tauri/src/config/audio_settings.rs b/src-tauri/src/config/audio_settings.rs index 5acbbdf67..160364a10 100644 --- a/src-tauri/src/config/audio_settings.rs +++ b/src-tauri/src/config/audio_settings.rs @@ -3,20 +3,20 @@ //! Stores user preferences for audio output device, exclusive mode, and DAC passthrough. use crate::audio::{AlsaPlugin, AudioBackendType}; -use rusqlite::{Connection, params}; +use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; use std::path::Path; use std::sync::{Arc, Mutex}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AudioSettings { - pub output_device: Option, // None = system default + pub output_device: Option, // None = system default pub exclusive_mode: bool, pub dac_passthrough: bool, - pub preferred_sample_rate: Option, // None = auto - pub backend_type: Option, // None = auto-detect - pub alsa_plugin: Option, // Only used when backend is ALSA - pub alsa_hardware_volume: bool, // Use ALSA mixer for volume (only with hw: devices) + pub preferred_sample_rate: Option, // None = auto + pub backend_type: Option, // None = auto-detect + pub alsa_plugin: Option, // Only used when backend is ALSA + pub alsa_hardware_volume: bool, // Use ALSA mixer for volume (only with hw: devices) /// When true, uncached tracks start playing via streaming instead of waiting for full download pub stream_first_track: bool, /// Initial buffer size in seconds before starting streaming playback (1-10, default 3) @@ -48,15 +48,15 @@ impl Default for AudioSettings { exclusive_mode: false, dac_passthrough: false, preferred_sample_rate: None, - backend_type: None, // Auto-detect (PipeWire if available, else ALSA) - alsa_plugin: Some(AlsaPlugin::Hw), // Default to hw (bit-perfect) - alsa_hardware_volume: false, // Disabled by default (maximum compatibility) - stream_first_track: false, // Disabled by default — user opts in - stream_buffer_seconds: 3, // 3 seconds initial buffer - streaming_only: false, // Disabled by default (cache tracks for instant replay) - limit_quality_to_device: false, // Disabled in 1.1.9 — detection logic unreliable (#45) - device_max_sample_rate: None, // Set when device is selected - normalization_enabled: false, // Off by default — preserves bit-perfect pipeline + backend_type: None, // Auto-detect (PipeWire if available, else ALSA) + alsa_plugin: Some(AlsaPlugin::Hw), // Default to hw (bit-perfect) + alsa_hardware_volume: false, // Disabled by default (maximum compatibility) + stream_first_track: false, // Disabled by default — user opts in + stream_buffer_seconds: 3, // 3 seconds initial buffer + streaming_only: false, // Disabled by default (cache tracks for instant replay) + limit_quality_to_device: false, // Disabled in 1.1.9 — detection logic unreliable (#45) + device_max_sample_rate: None, // Set when device is selected + normalization_enabled: false, // Off by default — preserves bit-perfect pipeline normalization_target_lufs: -14.0, // Spotify/YouTube standard gapless_enabled: false, // Off by default — user opts in } @@ -76,6 +76,9 @@ impl AudioSettingsStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open audio settings database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for audio settings database: {}", e))?; + conn.execute_batch( "CREATE TABLE IF NOT EXISTS audio_settings ( id INTEGER PRIMARY KEY CHECK (id = 1), @@ -90,21 +93,52 @@ impl AudioSettingsStore { stream_buffer_seconds INTEGER NOT NULL DEFAULT 3 ); INSERT OR IGNORE INTO audio_settings (id, exclusive_mode, dac_passthrough) - VALUES (1, 0, 0);" - ).map_err(|e| format!("Failed to create audio settings table: {}", e))?; + VALUES (1, 0, 0);", + ) + .map_err(|e| format!("Failed to create audio settings table: {}", e))?; // Migration: Add new columns if they don't exist (for existing databases) - let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN backend_type TEXT", []); + let _ = conn.execute( + "ALTER TABLE audio_settings ADD COLUMN backend_type TEXT", + [], + ); let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN alsa_plugin TEXT", []); - let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN alsa_hardware_volume INTEGER DEFAULT 0", []); - let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN stream_first_track INTEGER DEFAULT 0", []); - let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN stream_buffer_seconds INTEGER DEFAULT 3", []); - let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN streaming_only INTEGER DEFAULT 0", []); - let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN limit_quality_to_device INTEGER DEFAULT 0", []); - let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN device_max_sample_rate INTEGER", []); - let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN normalization_enabled INTEGER DEFAULT 0", []); - let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN normalization_target_lufs REAL DEFAULT -14.0", []); - let _ = conn.execute("ALTER TABLE audio_settings ADD COLUMN gapless_enabled INTEGER DEFAULT 0", []); + let _ = conn.execute( + "ALTER TABLE audio_settings ADD COLUMN alsa_hardware_volume INTEGER DEFAULT 0", + [], + ); + let _ = conn.execute( + "ALTER TABLE audio_settings ADD COLUMN stream_first_track INTEGER DEFAULT 0", + [], + ); + let _ = conn.execute( + "ALTER TABLE audio_settings ADD COLUMN stream_buffer_seconds INTEGER DEFAULT 3", + [], + ); + let _ = conn.execute( + "ALTER TABLE audio_settings ADD COLUMN streaming_only INTEGER DEFAULT 0", + [], + ); + let _ = conn.execute( + "ALTER TABLE audio_settings ADD COLUMN limit_quality_to_device INTEGER DEFAULT 0", + [], + ); + let _ = conn.execute( + "ALTER TABLE audio_settings ADD COLUMN device_max_sample_rate INTEGER", + [], + ); + let _ = conn.execute( + "ALTER TABLE audio_settings ADD COLUMN normalization_enabled INTEGER DEFAULT 0", + [], + ); + let _ = conn.execute( + "ALTER TABLE audio_settings ADD COLUMN normalization_target_lufs REAL DEFAULT -14.0", + [], + ); + let _ = conn.execute( + "ALTER TABLE audio_settings ADD COLUMN gapless_enabled INTEGER DEFAULT 0", + [], + ); Ok(Self { conn }) } @@ -323,11 +357,13 @@ impl AudioSettingsStore { /// Reset all audio settings to their default values pub fn reset_all(&self) -> Result { let defaults = AudioSettings::default(); - let backend_json: Option = defaults.backend_type + let backend_json: Option = defaults + .backend_type .map(|b| serde_json::to_string(&b)) .transpose() .map_err(|e| format!("Failed to serialize backend type: {}", e))?; - let plugin_json: Option = defaults.alsa_plugin + let plugin_json: Option = defaults + .alsa_plugin .map(|p| serde_json::to_string(&p)) .transpose() .map_err(|e| format!("Failed to serialize ALSA plugin: {}", e))?; @@ -395,14 +431,18 @@ impl AudioSettingsState { pub fn init_at(&self, base_dir: &Path) -> Result<(), String> { let new_store = AudioSettingsStore::new_at(base_dir)?; - let mut guard = self.store.lock() + let mut guard = self + .store + .lock() .map_err(|_| "Failed to lock audio settings store".to_string())?; *guard = Some(new_store); Ok(()) } pub fn teardown(&self) -> Result<(), String> { - let mut guard = self.store.lock() + let mut guard = self + .store + .lock() .map_err(|_| "Failed to lock audio settings store".to_string())?; *guard = None; Ok(()) @@ -414,7 +454,10 @@ impl AudioSettingsState { pub fn get_audio_settings( state: tauri::State<'_, AudioSettingsState>, ) -> Result { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.get_settings() } @@ -426,9 +469,9 @@ pub fn set_audio_output_device( ) -> Result<(), String> { // Normalize hw:X,0 to stable front:CARD=name,DEV=0 format // This ensures the saved device ID survives reboots and USB reconnections - let normalized_device = device.as_ref().map(|d| { - crate::audio::normalize_device_id_to_stable(d) - }); + let normalized_device = device + .as_ref() + .map(|d| crate::audio::normalize_device_id_to_stable(d)); log::info!( "Command: set_audio_output_device {:?} -> {:?} (normalized)", @@ -436,7 +479,10 @@ pub fn set_audio_output_device( normalized_device ); - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_output_device(normalized_device.as_deref()) } @@ -446,7 +492,10 @@ pub fn set_audio_exclusive_mode( state: tauri::State<'_, AudioSettingsState>, enabled: bool, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_exclusive_mode(enabled) } @@ -456,7 +505,10 @@ pub fn set_audio_dac_passthrough( state: tauri::State<'_, AudioSettingsState>, enabled: bool, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_dac_passthrough(enabled) } @@ -466,7 +518,10 @@ pub fn set_audio_sample_rate( state: tauri::State<'_, AudioSettingsState>, rate: Option, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_sample_rate(rate) } @@ -476,7 +531,10 @@ pub fn set_audio_backend_type( state: tauri::State<'_, AudioSettingsState>, backend_type: Option, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_backend_type(backend_type) } @@ -486,7 +544,10 @@ pub fn set_audio_alsa_plugin( state: tauri::State<'_, AudioSettingsState>, plugin: Option, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_alsa_plugin(plugin) } @@ -496,7 +557,10 @@ pub fn set_audio_alsa_hardware_volume( state: tauri::State<'_, AudioSettingsState>, enabled: bool, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_alsa_hardware_volume(enabled) } @@ -506,7 +570,10 @@ pub fn set_audio_stream_first_track( state: tauri::State<'_, AudioSettingsState>, enabled: bool, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_stream_first_track(enabled) } @@ -516,7 +583,10 @@ pub fn set_audio_stream_buffer_seconds( state: tauri::State<'_, AudioSettingsState>, seconds: u8, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_stream_buffer_seconds(seconds) } @@ -526,7 +596,10 @@ pub fn set_audio_streaming_only( state: tauri::State<'_, AudioSettingsState>, enabled: bool, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_streaming_only(enabled) } @@ -536,7 +609,10 @@ pub fn set_audio_limit_quality_to_device( state: tauri::State<'_, AudioSettingsState>, enabled: bool, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_limit_quality_to_device(enabled) } @@ -546,7 +622,10 @@ pub fn set_audio_device_max_sample_rate( state: tauri::State<'_, AudioSettingsState>, rate: Option, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_device_max_sample_rate(rate) } @@ -557,7 +636,10 @@ pub fn set_audio_normalization_enabled( enabled: bool, ) -> Result<(), String> { log::info!("Command: set_audio_normalization_enabled {}", enabled); - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_normalization_enabled(enabled) } @@ -567,8 +649,14 @@ pub fn set_audio_normalization_target( state: tauri::State<'_, AudioSettingsState>, target_lufs: f32, ) -> Result<(), String> { - log::info!("Command: set_audio_normalization_target {} LUFS", target_lufs); - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + log::info!( + "Command: set_audio_normalization_target {} LUFS", + target_lufs + ); + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_normalization_target_lufs(target_lufs) } @@ -579,7 +667,10 @@ pub fn set_audio_gapless_enabled( enabled: bool, ) -> Result<(), String> { log::info!("Command: set_audio_gapless_enabled {}", enabled); - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_gapless_enabled(enabled) } @@ -592,13 +683,21 @@ pub fn reset_audio_settings( log::info!("Command: reset_audio_settings (resetting audio + playback to defaults)"); // Reset audio settings - let guard = audio_state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = audio_state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; let defaults = store.reset_all()?; // Reset playback preferences - let pb_guard = playback_state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let pb_store = pb_guard.as_ref().ok_or("No active session - please log in")?; + let pb_guard = playback_state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let pb_store = pb_guard + .as_ref() + .ok_or("No active session - please log in")?; pb_store.reset_all()?; Ok(defaults) diff --git a/src-tauri/src/config/developer_settings.rs b/src-tauri/src/config/developer_settings.rs index ae7421e94..17352bc02 100644 --- a/src-tauri/src/config/developer_settings.rs +++ b/src-tauri/src/config/developer_settings.rs @@ -3,7 +3,7 @@ //! Stores developer-mode toggles (e.g. force DMA-BUF override for NVIDIA+Wayland). //! These settings are device-level (not per-user) and persist across sessions. -use rusqlite::{Connection, params}; +use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; use std::sync::{Arc, Mutex}; @@ -37,13 +37,22 @@ impl DeveloperSettingsStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open developer settings database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| { + format!( + "Failed to enable WAL for developer settings database: {}", + e + ) + })?; + conn.execute_batch( "CREATE TABLE IF NOT EXISTS developer_settings ( id INTEGER PRIMARY KEY CHECK (id = 1), force_dmabuf INTEGER NOT NULL DEFAULT 0 ); - INSERT OR IGNORE INTO developer_settings (id, force_dmabuf) VALUES (1, 0);" - ).map_err(|e| format!("Failed to create developer settings table: {}", e))?; + INSERT OR IGNORE INTO developer_settings (id, force_dmabuf) VALUES (1, 0);", + ) + .map_err(|e| format!("Failed to create developer settings table: {}", e))?; Ok(Self { conn }) } @@ -98,8 +107,13 @@ impl DeveloperSettingsState { pub fn get_developer_settings( state: tauri::State<'_, DeveloperSettingsState>, ) -> Result { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard.as_ref().ok_or("Developer settings store not initialized")?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard + .as_ref() + .ok_or("Developer settings store not initialized")?; store.get_settings() } @@ -109,7 +123,12 @@ pub fn set_developer_force_dmabuf( enabled: bool, ) -> Result<(), String> { log::info!("Command: set_developer_force_dmabuf {}", enabled); - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard.as_ref().ok_or("Developer settings store not initialized")?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard + .as_ref() + .ok_or("Developer settings store not initialized")?; store.set_force_dmabuf(enabled) } diff --git a/src-tauri/src/config/download_settings.rs b/src-tauri/src/config/download_settings.rs index fcce72e17..94b817c1e 100644 --- a/src-tauri/src/config/download_settings.rs +++ b/src-tauri/src/config/download_settings.rs @@ -2,7 +2,7 @@ //! //! Stores user preferences for download path and library integration. -use rusqlite::{Connection, params}; +use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; use std::path::Path; use std::sync::{Arc, Mutex}; @@ -42,6 +42,9 @@ impl DownloadSettingsStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open download settings database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for download settings database: {}", e))?; + let default_settings = DownloadSettings::default(); conn.execute_batch( @@ -49,14 +52,16 @@ impl DownloadSettingsStore { id INTEGER PRIMARY KEY CHECK (id = 1), download_root TEXT NOT NULL, show_in_library INTEGER NOT NULL DEFAULT 0 - );" - ).map_err(|e| format!("Failed to create download settings table: {}", e))?; + );", + ) + .map_err(|e| format!("Failed to create download settings table: {}", e))?; conn.execute( "INSERT OR IGNORE INTO download_settings (id, download_root, show_in_library) VALUES (1, ?1, 0)", params![default_settings.download_root], - ).map_err(|e| format!("Failed to initialize download settings: {}", e))?; + ) + .map_err(|e| format!("Failed to initialize download settings: {}", e))?; Ok(Self { conn }) } diff --git a/src-tauri/src/config/favorites_cache.rs b/src-tauri/src/config/favorites_cache.rs index dfb30fc12..2458a084f 100644 --- a/src-tauri/src/config/favorites_cache.rs +++ b/src-tauri/src/config/favorites_cache.rs @@ -46,6 +46,9 @@ impl FavoritesCacheStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open favorites cache database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for favorites cache database: {}", e))?; + // Create tables conn.execute( "CREATE TABLE IF NOT EXISTS favorite_tracks ( @@ -91,7 +94,8 @@ impl FavoritesCacheStore { // ============ Track favorites ============ pub fn get_favorite_track_ids(&self) -> Result, String> { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare("SELECT track_id FROM favorite_tracks") .map_err(|e| format!("Failed to prepare query: {}", e))?; @@ -107,7 +111,8 @@ impl FavoritesCacheStore { } pub fn is_track_favorite(&self, track_id: i64) -> Result { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare("SELECT 1 FROM favorite_tracks WHERE track_id = ?1") .map_err(|e| format!("Failed to prepare query: {}", e))?; @@ -158,7 +163,8 @@ impl FavoritesCacheStore { // ============ Album favorites ============ pub fn get_favorite_album_ids(&self) -> Result, String> { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare("SELECT album_id FROM favorite_albums") .map_err(|e| format!("Failed to prepare query: {}", e))?; @@ -174,7 +180,8 @@ impl FavoritesCacheStore { } pub fn is_album_favorite(&self, album_id: &str) -> Result { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare("SELECT 1 FROM favorite_albums WHERE album_id = ?1") .map_err(|e| format!("Failed to prepare query: {}", e))?; @@ -224,7 +231,8 @@ impl FavoritesCacheStore { // ============ Artist favorites ============ pub fn get_favorite_artist_ids(&self) -> Result, String> { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare("SELECT artist_id FROM favorite_artists") .map_err(|e| format!("Failed to prepare query: {}", e))?; @@ -240,7 +248,8 @@ impl FavoritesCacheStore { } pub fn is_artist_favorite(&self, artist_id: i64) -> Result { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare("SELECT 1 FROM favorite_artists WHERE artist_id = ?1") .map_err(|e| format!("Failed to prepare query: {}", e))?; @@ -325,14 +334,18 @@ impl FavoritesCacheState { pub fn init_at(&self, base_dir: &Path) -> Result<(), String> { let new_store = FavoritesCacheStore::new_at(base_dir)?; - let mut guard = self.store.lock() + let mut guard = self + .store + .lock() .map_err(|_| "Failed to lock favorites cache store".to_string())?; *guard = Some(new_store); Ok(()) } pub fn teardown(&self) -> Result<(), String> { - let mut guard = self.store.lock() + let mut guard = self + .store + .lock() .map_err(|_| "Failed to lock favorites cache store".to_string())?; *guard = None; Ok(()) @@ -508,9 +521,7 @@ pub fn sync_cached_favorite_artists( /// Clear all cached favorites (call on logout) #[tauri::command] -pub fn clear_favorites_cache( - state: tauri::State, -) -> Result<(), String> { +pub fn clear_favorites_cache(state: tauri::State) -> Result<(), String> { let guard = state .store .lock() diff --git a/src-tauri/src/config/graphics_settings.rs b/src-tauri/src/config/graphics_settings.rs index 7a7725b58..6d0f5cb71 100644 --- a/src-tauri/src/config/graphics_settings.rs +++ b/src-tauri/src/config/graphics_settings.rs @@ -12,10 +12,10 @@ //! auto-detection (Wayland/NVIDIA). Use QBZ_HARDWARE_ACCEL=0 env var to //! explicitly disable all GPU rendering. -use rusqlite::{Connection, params}; +use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; -use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; // --- Global startup state (set once in main.rs, read-only thereafter) --- static GRAPHICS_USING_FALLBACK: AtomicBool = AtomicBool::new(false); @@ -87,24 +87,24 @@ impl GraphicsSettingsStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open graphics settings database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for graphics settings database: {}", e))?; + conn.execute_batch( "CREATE TABLE IF NOT EXISTS graphics_settings ( id INTEGER PRIMARY KEY CHECK (id = 1), hardware_acceleration INTEGER NOT NULL DEFAULT 0 ); - INSERT OR IGNORE INTO graphics_settings (id, hardware_acceleration) VALUES (1, 0);" - ).map_err(|e| format!("Failed to create graphics settings table: {}", e))?; + INSERT OR IGNORE INTO graphics_settings (id, hardware_acceleration) VALUES (1, 0);", + ) + .map_err(|e| format!("Failed to create graphics settings table: {}", e))?; // Migrations: add columns (no-op if already present) let _ = conn.execute_batch( - "ALTER TABLE graphics_settings ADD COLUMN force_x11 INTEGER NOT NULL DEFAULT 0;" - ); - let _ = conn.execute_batch( - "ALTER TABLE graphics_settings ADD COLUMN gdk_scale TEXT;" - ); - let _ = conn.execute_batch( - "ALTER TABLE graphics_settings ADD COLUMN gdk_dpi_scale TEXT;" + "ALTER TABLE graphics_settings ADD COLUMN force_x11 INTEGER NOT NULL DEFAULT 0;", ); + let _ = conn.execute_batch("ALTER TABLE graphics_settings ADD COLUMN gdk_scale TEXT;"); + let _ = conn.execute_batch("ALTER TABLE graphics_settings ADD COLUMN gdk_dpi_scale TEXT;"); Ok(Self { conn }) } @@ -192,8 +192,13 @@ impl GraphicsSettingsState { pub fn get_graphics_settings( state: tauri::State<'_, GraphicsSettingsState>, ) -> Result { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard.as_ref().ok_or("Graphics settings store not initialized")?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard + .as_ref() + .ok_or("Graphics settings store not initialized")?; store.get_settings() } @@ -202,9 +207,17 @@ pub fn set_hardware_acceleration( state: tauri::State<'_, GraphicsSettingsState>, enabled: bool, ) -> Result<(), String> { - log::info!("[GraphicsSettings] Setting hardware_acceleration to {} (restart required)", enabled); - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard.as_ref().ok_or("Graphics settings store not initialized")?; + log::info!( + "[GraphicsSettings] Setting hardware_acceleration to {} (restart required)", + enabled + ); + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard + .as_ref() + .ok_or("Graphics settings store not initialized")?; store.set_hardware_acceleration(enabled) } @@ -213,9 +226,17 @@ pub fn set_force_x11( state: tauri::State<'_, GraphicsSettingsState>, enabled: bool, ) -> Result<(), String> { - log::info!("[GraphicsSettings] Setting force_x11 to {} (restart required)", enabled); - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard.as_ref().ok_or("Graphics settings store not initialized")?; + log::info!( + "[GraphicsSettings] Setting force_x11 to {} (restart required)", + enabled + ); + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard + .as_ref() + .ok_or("Graphics settings store not initialized")?; store.set_force_x11(enabled) } @@ -224,9 +245,17 @@ pub fn set_gdk_scale( state: tauri::State<'_, GraphicsSettingsState>, value: Option, ) -> Result<(), String> { - log::info!("[GraphicsSettings] Setting gdk_scale to {:?} (restart required)", value); - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard.as_ref().ok_or("Graphics settings store not initialized")?; + log::info!( + "[GraphicsSettings] Setting gdk_scale to {:?} (restart required)", + value + ); + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard + .as_ref() + .ok_or("Graphics settings store not initialized")?; store.set_gdk_scale(value) } @@ -235,9 +264,17 @@ pub fn set_gdk_dpi_scale( state: tauri::State<'_, GraphicsSettingsState>, value: Option, ) -> Result<(), String> { - log::info!("[GraphicsSettings] Setting gdk_dpi_scale to {:?} (restart required)", value); - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard.as_ref().ok_or("Graphics settings store not initialized")?; + log::info!( + "[GraphicsSettings] Setting gdk_dpi_scale to {:?} (restart required)", + value + ); + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard + .as_ref() + .ok_or("Graphics settings store not initialized")?; store.set_gdk_dpi_scale(value) } diff --git a/src-tauri/src/config/legal_settings.rs b/src-tauri/src/config/legal_settings.rs index b7cfb8d39..ebbcb6056 100644 --- a/src-tauri/src/config/legal_settings.rs +++ b/src-tauri/src/config/legal_settings.rs @@ -3,11 +3,11 @@ //! Persists user acceptance of legal terms: //! - qobuz_tos_accepted: User has accepted Qobuz Terms of Service -use rusqlite::{Connection, params}; +use log::info; +use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; use std::path::Path; use std::sync::{Arc, Mutex}; -use log::info; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct LegalSettings { @@ -36,19 +36,24 @@ impl LegalSettingsStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open legal settings database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for legal settings database: {}", e))?; + // Create table conn.execute_batch( "CREATE TABLE IF NOT EXISTS legal_settings ( id INTEGER PRIMARY KEY CHECK (id = 1), qobuz_tos_accepted INTEGER NOT NULL DEFAULT 0 - );" - ).map_err(|e| format!("Failed to create legal settings table: {}", e))?; + );", + ) + .map_err(|e| format!("Failed to create legal settings table: {}", e))?; // Insert default row if it doesn't exist conn.execute( "INSERT OR IGNORE INTO legal_settings (id, qobuz_tos_accepted) VALUES (1, 0)", - [] - ).map_err(|e| format!("Failed to insert default legal settings: {}", e))?; + [], + ) + .map_err(|e| format!("Failed to insert default legal settings: {}", e))?; info!("[LegalSettings] Database initialized"); @@ -117,9 +122,7 @@ pub fn get_legal_settings( } #[tauri::command] -pub fn get_qobuz_tos_accepted( - state: tauri::State<'_, LegalSettingsState>, -) -> Result { +pub fn get_qobuz_tos_accepted(state: tauri::State<'_, LegalSettingsState>) -> Result { let guard = state.lock().map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; let settings = store.get_settings()?; diff --git a/src-tauri/src/config/playback_preferences.rs b/src-tauri/src/config/playback_preferences.rs index 34d7f2900..ff30e72ee 100644 --- a/src-tauri/src/config/playback_preferences.rs +++ b/src-tauri/src/config/playback_preferences.rs @@ -2,11 +2,11 @@ //! //! Stores user preferences for playback behavior (autoplay mode, etc.) -use rusqlite::{Connection, params}; +use log::info; +use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; use std::path::Path; use std::sync::{Arc, Mutex}; -use log::info; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum AutoplayMode { @@ -73,13 +73,22 @@ impl PlaybackPreferencesStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open playback preferences database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| { + format!( + "Failed to enable WAL for playback preferences database: {}", + e + ) + })?; + // Step 1: Create table with old schema (for new installs) or do nothing if exists conn.execute_batch( "CREATE TABLE IF NOT EXISTS playback_preferences ( id INTEGER PRIMARY KEY CHECK (id = 1), autoplay_mode TEXT NOT NULL DEFAULT 'continue' - );" - ).map_err(|e| format!("Failed to create playback preferences table: {}", e))?; + );", + ) + .map_err(|e| format!("Failed to create playback preferences table: {}", e))?; // Step 2: Check if show_context_icon column exists let column_exists: bool = conn @@ -93,7 +102,10 @@ impl PlaybackPreferencesStore { ) .unwrap_or(false); - info!("[PlaybackPrefs] Column show_context_icon exists: {}", column_exists); + info!( + "[PlaybackPrefs] Column show_context_icon exists: {}", + column_exists + ); // Step 3: Add column if it doesn't exist (migration for existing users) if !column_exists { @@ -109,8 +121,9 @@ impl PlaybackPreferencesStore { conn.execute( "INSERT OR IGNORE INTO playback_preferences (id, autoplay_mode, show_context_icon) VALUES (1, 'continue', 0)", - [] - ).map_err(|e| format!("Failed to insert default preferences: {}", e))?; + [], + ) + .map_err(|e| format!("Failed to insert default preferences: {}", e))?; Ok(Self { conn }) } @@ -197,33 +210,46 @@ impl PlaybackPreferencesState { pub fn init_at(&self, base_dir: &Path) -> Result<(), String> { let new_store = PlaybackPreferencesStore::new_at(base_dir)?; - let mut guard = self.store.lock() + let mut guard = self + .store + .lock() .map_err(|_| "Failed to lock playback preferences store".to_string())?; *guard = Some(new_store); Ok(()) } pub fn teardown(&self) -> Result<(), String> { - let mut guard = self.store.lock() + let mut guard = self + .store + .lock() .map_err(|_| "Failed to lock playback preferences store".to_string())?; *guard = None; Ok(()) } pub fn get_preferences(&self) -> Result { - let guard = self.store.lock().map_err(|_| "Failed to lock playback preferences store".to_string())?; + let guard = self + .store + .lock() + .map_err(|_| "Failed to lock playback preferences store".to_string())?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.get_preferences() } pub fn set_autoplay_mode(&self, mode: AutoplayMode) -> Result<(), String> { - let guard = self.store.lock().map_err(|_| "Failed to lock playback preferences store".to_string())?; + let guard = self + .store + .lock() + .map_err(|_| "Failed to lock playback preferences store".to_string())?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_autoplay_mode(mode) } pub fn set_show_context_icon(&self, show: bool) -> Result<(), String> { - let guard = self.store.lock().map_err(|_| "Failed to lock playback preferences store".to_string())?; + let guard = self + .store + .lock() + .map_err(|_| "Failed to lock playback preferences store".to_string())?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_show_context_icon(show) } diff --git a/src-tauri/src/config/remote_control_settings.rs b/src-tauri/src/config/remote_control_settings.rs index 55964b3e6..86a894d9e 100644 --- a/src-tauri/src/config/remote_control_settings.rs +++ b/src-tauri/src/config/remote_control_settings.rs @@ -25,7 +25,7 @@ impl Default for RemoteControlSettings { Self { enabled: false, port: 8182, - secure: true, // HTTPS by default for security + secure: true, // HTTPS by default for security token: String::new(), } } @@ -44,6 +44,14 @@ impl RemoteControlSettingsStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open remote control settings database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| { + format!( + "Failed to enable WAL for remote control settings database: {}", + e + ) + })?; + conn.execute_batch( "CREATE TABLE IF NOT EXISTS remote_control_settings ( id INTEGER PRIMARY KEY CHECK (id = 1), @@ -51,8 +59,9 @@ impl RemoteControlSettingsStore { port INTEGER NOT NULL DEFAULT 8182, secure INTEGER NOT NULL DEFAULT 1, token TEXT NOT NULL DEFAULT '' - );" - ).map_err(|e| format!("Failed to create remote control settings table: {}", e))?; + );", + ) + .map_err(|e| format!("Failed to create remote control settings table: {}", e))?; ensure_secure_column(&conn)?; @@ -61,7 +70,8 @@ impl RemoteControlSettingsStore { "INSERT OR IGNORE INTO remote_control_settings (id, enabled, port, secure, token) VALUES (1, 0, 8182, 0, ?1)", params![token], - ).map_err(|e| format!("Failed to insert default remote control settings: {}", e))?; + ) + .map_err(|e| format!("Failed to insert default remote control settings: {}", e))?; Ok(Self { conn }) } @@ -78,7 +88,8 @@ impl RemoteControlSettingsStore { } pub fn get_settings(&self) -> Result { - let mut settings = self.conn + let mut settings = self + .conn .query_row( "SELECT enabled, port, secure, token FROM remote_control_settings WHERE id = 1", [], @@ -172,21 +183,26 @@ impl RemoteControlSettingsState { pub fn init_at(&self, base_dir: &Path) -> Result<(), String> { let new_store = RemoteControlSettingsStore::new_at(base_dir)?; - let mut guard = self.store.lock() + let mut guard = self + .store + .lock() .map_err(|_| "Failed to lock remote control settings store".to_string())?; *guard = Some(new_store); Ok(()) } pub fn teardown(&self) -> Result<(), String> { - let mut guard = self.store.lock() + let mut guard = self + .store + .lock() .map_err(|_| "Failed to lock remote control settings store".to_string())?; *guard = None; Ok(()) } pub fn get_settings(&self) -> Result { - let guard = self.store + let guard = self + .store .lock() .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; @@ -194,7 +210,8 @@ impl RemoteControlSettingsState { } pub fn set_enabled(&self, enabled: bool) -> Result<(), String> { - let guard = self.store + let guard = self + .store .lock() .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; @@ -202,7 +219,8 @@ impl RemoteControlSettingsState { } pub fn set_port(&self, port: u16) -> Result<(), String> { - let guard = self.store + let guard = self + .store .lock() .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; @@ -210,7 +228,8 @@ impl RemoteControlSettingsState { } pub fn set_secure(&self, secure: bool) -> Result<(), String> { - let guard = self.store + let guard = self + .store .lock() .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; @@ -218,7 +237,8 @@ impl RemoteControlSettingsState { } pub fn regenerate_token(&self) -> Result { - let guard = self.store + let guard = self + .store .lock() .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; @@ -244,7 +264,9 @@ fn ensure_secure_column(conn: &Connection) -> Result<(), String> { .next() .map_err(|e| format!("Schema read error: {}", e))? { - let name: String = row.get(1).map_err(|e| format!("Schema read error: {}", e))?; + let name: String = row + .get(1) + .map_err(|e| format!("Schema read error: {}", e))?; if name == "secure" { return Ok(()); } @@ -292,28 +314,31 @@ impl AllowedOriginsStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open allowed origins database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for allowed origins database: {}", e))?; + // Create allowed_origins table conn.execute_batch( "CREATE TABLE IF NOT EXISTS allowed_origins ( id INTEGER PRIMARY KEY AUTOINCREMENT, origin TEXT NOT NULL UNIQUE, is_default INTEGER NOT NULL DEFAULT 0 - );" - ).map_err(|e| format!("Failed to create allowed_origins table: {}", e))?; + );", + ) + .map_err(|e| format!("Failed to create allowed_origins table: {}", e))?; // Insert default origins if table is empty - let count: i64 = conn.query_row( - "SELECT COUNT(*) FROM allowed_origins", - [], - |row| row.get(0) - ).unwrap_or(0); + let count: i64 = conn + .query_row("SELECT COUNT(*) FROM allowed_origins", [], |row| row.get(0)) + .unwrap_or(0); if count == 0 { for origin in DEFAULT_ALLOWED_ORIGINS { conn.execute( "INSERT OR IGNORE INTO allowed_origins (origin, is_default) VALUES (?1, 1)", params![origin], - ).ok(); + ) + .ok(); } } @@ -337,25 +362,30 @@ impl AllowedOriginsStore { .prepare("SELECT id, origin, is_default FROM allowed_origins ORDER BY is_default DESC, origin ASC") .map_err(|e| format!("Failed to prepare query: {}", e))?; - let origins = stmt.query_map([], |row| { - Ok(AllowedOrigin { - id: row.get(0)?, - origin: row.get(1)?, - is_default: row.get::<_, i32>(2)? != 0, + let origins = stmt + .query_map([], |row| { + Ok(AllowedOrigin { + id: row.get(0)?, + origin: row.get(1)?, + is_default: row.get::<_, i32>(2)? != 0, + }) }) - }).map_err(|e| format!("Failed to query origins: {}", e))?; + .map_err(|e| format!("Failed to query origins: {}", e))?; - origins.collect::, _>>() + origins + .collect::, _>>() .map_err(|e| format!("Failed to collect origins: {}", e)) } /// Check if an origin is allowed pub fn is_origin_allowed(&self, origin: &str) -> bool { - self.conn.query_row( - "SELECT 1 FROM allowed_origins WHERE origin = ?1", - params![origin], - |_| Ok(()) - ).is_ok() + self.conn + .query_row( + "SELECT 1 FROM allowed_origins WHERE origin = ?1", + params![origin], + |_| Ok(()), + ) + .is_ok() } /// Add a new allowed origin @@ -367,16 +397,18 @@ impl AllowedOriginsStore { return Err("Origin cannot be empty".to_string()); } - self.conn.execute( - "INSERT INTO allowed_origins (origin, is_default) VALUES (?1, 0)", - params![normalized], - ).map_err(|e| { - if e.to_string().contains("UNIQUE constraint") { - "Origin already exists".to_string() - } else { - format!("Failed to add origin: {}", e) - } - })?; + self.conn + .execute( + "INSERT INTO allowed_origins (origin, is_default) VALUES (?1, 0)", + params![normalized], + ) + .map_err(|e| { + if e.to_string().contains("UNIQUE constraint") { + "Origin already exists".to_string() + } else { + format!("Failed to add origin: {}", e) + } + })?; let id = self.conn.last_insert_rowid(); Ok(AllowedOrigin { @@ -388,10 +420,10 @@ impl AllowedOriginsStore { /// Remove an allowed origin by ID pub fn remove_origin(&self, id: i64) -> Result<(), String> { - let affected = self.conn.execute( - "DELETE FROM allowed_origins WHERE id = ?1", - params![id], - ).map_err(|e| format!("Failed to remove origin: {}", e))?; + let affected = self + .conn + .execute("DELETE FROM allowed_origins WHERE id = ?1", params![id]) + .map_err(|e| format!("Failed to remove origin: {}", e))?; if affected == 0 { return Err("Origin not found".to_string()); @@ -402,10 +434,12 @@ impl AllowedOriginsStore { /// Restore default origins (adds missing defaults back) pub fn restore_defaults(&self) -> Result<(), String> { for origin in DEFAULT_ALLOWED_ORIGINS { - self.conn.execute( - "INSERT OR IGNORE INTO allowed_origins (origin, is_default) VALUES (?1, 1)", - params![origin], - ).ok(); + self.conn + .execute( + "INSERT OR IGNORE INTO allowed_origins (origin, is_default) VALUES (?1, 1)", + params![origin], + ) + .ok(); } Ok(()) } @@ -431,21 +465,26 @@ impl AllowedOriginsState { pub fn init_at(&self, base_dir: &Path) -> Result<(), String> { let new_store = AllowedOriginsStore::new_at(base_dir)?; - let mut guard = self.store.lock() + let mut guard = self + .store + .lock() .map_err(|_| "Failed to lock allowed origins store".to_string())?; *guard = Some(new_store); Ok(()) } pub fn teardown(&self) -> Result<(), String> { - let mut guard = self.store.lock() + let mut guard = self + .store + .lock() .map_err(|_| "Failed to lock allowed origins store".to_string())?; *guard = None; Ok(()) } pub fn get_origins(&self) -> Result, String> { - let guard = self.store + let guard = self + .store .lock() .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; @@ -456,7 +495,8 @@ impl AllowedOriginsState { self.store .lock() .map(|guard| { - guard.as_ref() + guard + .as_ref() .map(|s| s.is_origin_allowed(origin)) .unwrap_or(false) }) @@ -464,7 +504,8 @@ impl AllowedOriginsState { } pub fn add_origin(&self, origin: &str) -> Result { - let guard = self.store + let guard = self + .store .lock() .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; @@ -472,7 +513,8 @@ impl AllowedOriginsState { } pub fn remove_origin(&self, id: i64) -> Result<(), String> { - let guard = self.store + let guard = self + .store .lock() .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; @@ -480,7 +522,8 @@ impl AllowedOriginsState { } pub fn restore_defaults(&self) -> Result<(), String> { - let guard = self.store + let guard = self + .store .lock() .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; diff --git a/src-tauri/src/config/subscription_state.rs b/src-tauri/src/config/subscription_state.rs index 48fe15576..bba0d2052 100644 --- a/src-tauri/src/config/subscription_state.rs +++ b/src-tauri/src/config/subscription_state.rs @@ -4,7 +4,7 @@ //! invalid state persists for more than a grace period, offline downloads are //! purged. -use rusqlite::{Connection, params}; +use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; use std::path::Path; use std::sync::{Arc, Mutex}; @@ -46,6 +46,14 @@ impl SubscriptionStateStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open subscription state database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| { + format!( + "Failed to enable WAL for subscription state database: {}", + e + ) + })?; + conn.execute_batch( "CREATE TABLE IF NOT EXISTS subscription_state ( id INTEGER PRIMARY KEY CHECK (id = 1), @@ -55,8 +63,9 @@ impl SubscriptionStateStore { last_checked_at INTEGER, downloads_purged_at INTEGER ); - INSERT OR IGNORE INTO subscription_state (id) VALUES (1);" - ).map_err(|e| format!("Failed to create subscription state table: {}", e))?; + INSERT OR IGNORE INTO subscription_state (id) VALUES (1);", + ) + .map_err(|e| format!("Failed to create subscription state table: {}", e))?; Ok(Self { conn }) } @@ -132,7 +141,9 @@ impl SubscriptionStateStore { pub fn should_purge_offline_cache(&self, now: i64) -> Result { let state = self.get_state()?; - let Some(invalid_since) = state.invalid_since else { return Ok(false); }; + let Some(invalid_since) = state.invalid_since else { + return Ok(false); + }; if now - invalid_since < GRACE_PERIOD_SECS { return Ok(false); } diff --git a/src-tauri/src/config/tray_settings.rs b/src-tauri/src/config/tray_settings.rs index 902b80c9c..2749e1ef9 100644 --- a/src-tauri/src/config/tray_settings.rs +++ b/src-tauri/src/config/tray_settings.rs @@ -5,11 +5,11 @@ //! - minimize_to_tray: Hide to tray when minimizing //! - close_to_tray: Hide to tray when closing window -use rusqlite::{Connection, params}; +use log::info; +use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; use std::path::Path; use std::sync::{Arc, Mutex}; -use log::info; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TraySettings { @@ -44,6 +44,9 @@ impl TraySettingsStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open tray settings database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for tray settings database: {}", e))?; + // Create table conn.execute_batch( "CREATE TABLE IF NOT EXISTS tray_settings ( @@ -51,15 +54,17 @@ impl TraySettingsStore { enable_tray INTEGER NOT NULL DEFAULT 1, minimize_to_tray INTEGER NOT NULL DEFAULT 0, close_to_tray INTEGER NOT NULL DEFAULT 0 - );" - ).map_err(|e| format!("Failed to create tray settings table: {}", e))?; + );", + ) + .map_err(|e| format!("Failed to create tray settings table: {}", e))?; // Insert default row if it doesn't exist conn.execute( "INSERT OR IGNORE INTO tray_settings (id, enable_tray, minimize_to_tray, close_to_tray) VALUES (1, 1, 0, 0)", - [] - ).map_err(|e| format!("Failed to insert default tray settings: {}", e))?; + [], + ) + .map_err(|e| format!("Failed to insert default tray settings: {}", e))?; info!("[TraySettings] Database initialized"); @@ -148,39 +153,55 @@ impl TraySettingsState { pub fn init_at(&self, base_dir: &Path) -> Result<(), String> { let new_store = TraySettingsStore::new_at(base_dir)?; - let mut guard = self.store.lock() + let mut guard = self + .store + .lock() .map_err(|_| "Failed to lock tray settings store".to_string())?; *guard = Some(new_store); Ok(()) } pub fn teardown(&self) -> Result<(), String> { - let mut guard = self.store.lock() + let mut guard = self + .store + .lock() .map_err(|_| "Failed to lock tray settings store".to_string())?; *guard = None; Ok(()) } pub fn get_settings(&self) -> Result { - let guard = self.store.lock().map_err(|_| "Failed to lock tray settings store".to_string())?; + let guard = self + .store + .lock() + .map_err(|_| "Failed to lock tray settings store".to_string())?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.get_settings() } pub fn set_enable_tray(&self, value: bool) -> Result<(), String> { - let guard = self.store.lock().map_err(|_| "Failed to lock tray settings store".to_string())?; + let guard = self + .store + .lock() + .map_err(|_| "Failed to lock tray settings store".to_string())?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_enable_tray(value) } pub fn set_minimize_to_tray(&self, value: bool) -> Result<(), String> { - let guard = self.store.lock().map_err(|_| "Failed to lock tray settings store".to_string())?; + let guard = self + .store + .lock() + .map_err(|_| "Failed to lock tray settings store".to_string())?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_minimize_to_tray(value) } pub fn set_close_to_tray(&self, value: bool) -> Result<(), String> { - let guard = self.store.lock().map_err(|_| "Failed to lock tray settings store".to_string())?; + let guard = self + .store + .lock() + .map_err(|_| "Failed to lock tray settings store".to_string())?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.set_close_to_tray(value) } @@ -189,18 +210,16 @@ impl TraySettingsState { // Tauri commands #[tauri::command] -pub fn get_tray_settings( - state: tauri::State, -) -> Result { +pub fn get_tray_settings(state: tauri::State) -> Result { state.get_settings() } #[tauri::command] -pub fn set_enable_tray( - value: bool, - state: tauri::State, -) -> Result<(), String> { - info!("[TraySettings] Setting enable_tray to {} (restart required)", value); +pub fn set_enable_tray(value: bool, state: tauri::State) -> Result<(), String> { + info!( + "[TraySettings] Setting enable_tray to {} (restart required)", + value + ); state.set_enable_tray(value) } diff --git a/src-tauri/src/config/window_settings.rs b/src-tauri/src/config/window_settings.rs index 49b5ea169..f246e4bb3 100644 --- a/src-tauri/src/config/window_settings.rs +++ b/src-tauri/src/config/window_settings.rs @@ -3,11 +3,11 @@ //! Stores user preferences for window title bar behavior: //! - use_system_titlebar: Use OS native window decorations instead of custom CSD title bar -use rusqlite::{Connection, params}; +use log::info; +use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; use std::path::Path; use std::sync::{Arc, Mutex}; -use log::info; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct WindowSettings { @@ -36,18 +36,23 @@ impl WindowSettingsStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open window settings database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for window settings database: {}", e))?; + conn.execute_batch( "CREATE TABLE IF NOT EXISTS window_settings ( id INTEGER PRIMARY KEY CHECK (id = 1), use_system_titlebar INTEGER NOT NULL DEFAULT 0 - );" - ).map_err(|e| format!("Failed to create window settings table: {}", e))?; + );", + ) + .map_err(|e| format!("Failed to create window settings table: {}", e))?; conn.execute( "INSERT OR IGNORE INTO window_settings (id, use_system_titlebar) VALUES (1, 0)", - [] - ).map_err(|e| format!("Failed to insert default window settings: {}", e))?; + [], + ) + .map_err(|e| format!("Failed to insert default window settings: {}", e))?; info!("[WindowSettings] Database initialized"); @@ -111,14 +116,24 @@ impl WindowSettingsState { } pub fn get_settings(&self) -> Result { - let guard = self.store.lock().map_err(|_| "Failed to lock window settings store".to_string())?; - let store = guard.as_ref().ok_or("Window settings store not initialized")?; + let guard = self + .store + .lock() + .map_err(|_| "Failed to lock window settings store".to_string())?; + let store = guard + .as_ref() + .ok_or("Window settings store not initialized")?; store.get_settings() } pub fn set_use_system_titlebar(&self, value: bool) -> Result<(), String> { - let guard = self.store.lock().map_err(|_| "Failed to lock window settings store".to_string())?; - let store = guard.as_ref().ok_or("Window settings store not initialized")?; + let guard = self + .store + .lock() + .map_err(|_| "Failed to lock window settings store".to_string())?; + let store = guard + .as_ref() + .ok_or("Window settings store not initialized")?; store.set_use_system_titlebar(value) } } diff --git a/src-tauri/src/library/database.rs b/src-tauri/src/library/database.rs index 6bacdfc6f..b1304655b 100644 --- a/src-tauri/src/library/database.rs +++ b/src-tauri/src/library/database.rs @@ -42,7 +42,7 @@ impl LibraryDatabase { .map_err(|e| LibraryError::Database(format!("Failed to open database: {}", e)))?; // Enable WAL mode for better concurrent access - conn.execute_batch("PRAGMA journal_mode=WAL;") + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") .map_err(|e| LibraryError::Database(format!("Failed to set WAL mode: {}", e)))?; let db = Self { conn }; @@ -201,7 +201,8 @@ impl LibraryDatabase { /// Run schema migrations for existing databases fn run_migrations(&self) -> Result<(), LibraryError> { // Migration: Add qobuz download tracking fields - let has_source: bool = self.conn + let has_source: bool = self + .conn .query_row( "SELECT COUNT(*) FROM pragma_table_info('local_tracks') WHERE name = 'source'", [], @@ -212,16 +213,19 @@ impl LibraryDatabase { if !has_source { log::info!("Running migration: adding source and qobuz_track_id to local_tracks"); - self.conn.execute_batch( - "ALTER TABLE local_tracks ADD COLUMN source TEXT DEFAULT 'user'; + self.conn + .execute_batch( + "ALTER TABLE local_tracks ADD COLUMN source TEXT DEFAULT 'user'; ALTER TABLE local_tracks ADD COLUMN qobuz_track_id INTEGER; CREATE INDEX IF NOT EXISTS idx_tracks_source ON local_tracks(source); - CREATE INDEX IF NOT EXISTS idx_tracks_qobuz_id ON local_tracks(qobuz_track_id);" - ).map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; + CREATE INDEX IF NOT EXISTS idx_tracks_qobuz_id ON local_tracks(qobuz_track_id);", + ) + .map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; } // Check if playlist_settings has the 'hidden' column (added in v2) - let has_hidden: bool = self.conn + let has_hidden: bool = self + .conn .query_row( "SELECT COUNT(*) FROM pragma_table_info('playlist_settings') WHERE name = 'hidden'", [], @@ -231,15 +235,20 @@ impl LibraryDatabase { .unwrap_or(false); if !has_hidden { - log::info!("Running migration: adding hidden and position columns to playlist_settings"); - self.conn.execute_batch( - "ALTER TABLE playlist_settings ADD COLUMN hidden INTEGER DEFAULT 0; - ALTER TABLE playlist_settings ADD COLUMN position INTEGER DEFAULT 0;" - ).map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; + log::info!( + "Running migration: adding hidden and position columns to playlist_settings" + ); + self.conn + .execute_batch( + "ALTER TABLE playlist_settings ADD COLUMN hidden INTEGER DEFAULT 0; + ALTER TABLE playlist_settings ADD COLUMN position INTEGER DEFAULT 0;", + ) + .map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; } // Check if playlist_stats table exists - let has_stats_table: bool = self.conn + let has_stats_table: bool = self + .conn .query_row( "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='playlist_stats'", [], @@ -250,15 +259,17 @@ impl LibraryDatabase { if !has_stats_table { log::info!("Running migration: creating playlist_stats table"); - self.conn.execute_batch( - "CREATE TABLE IF NOT EXISTS playlist_stats ( + self.conn + .execute_batch( + "CREATE TABLE IF NOT EXISTS playlist_stats ( qobuz_playlist_id INTEGER PRIMARY KEY, play_count INTEGER DEFAULT 0, last_played_at INTEGER, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL - );" - ).map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; + );", + ) + .map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; } let has_album_group_key: bool = self @@ -346,7 +357,8 @@ impl LibraryDatabase { } // Migration: Add folder metadata columns (alias, network info) - let has_folder_alias: bool = self.conn + let has_folder_alias: bool = self + .conn .query_row( "SELECT COUNT(*) FROM pragma_table_info('library_folders') WHERE name = 'alias'", [], @@ -357,12 +369,14 @@ impl LibraryDatabase { if !has_folder_alias { log::info!("Running migration: adding folder metadata columns (alias, network info)"); - self.conn.execute_batch( - "ALTER TABLE library_folders ADD COLUMN alias TEXT; + self.conn + .execute_batch( + "ALTER TABLE library_folders ADD COLUMN alias TEXT; ALTER TABLE library_folders ADD COLUMN is_network INTEGER DEFAULT 0; ALTER TABLE library_folders ADD COLUMN network_fs_type TEXT; - ALTER TABLE library_folders ADD COLUMN user_override_network INTEGER DEFAULT 0;" - ).map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; + ALTER TABLE library_folders ADD COLUMN user_override_network INTEGER DEFAULT 0;", + ) + .map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; } // Migration: Add is_favorite column to playlist_settings @@ -384,7 +398,8 @@ impl LibraryDatabase { } // Migration: Add playlist_folders table and folder_id column - let has_playlist_folders: bool = self.conn + let has_playlist_folders: bool = self + .conn .query_row( "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='playlist_folders'", [], @@ -451,7 +466,8 @@ impl LibraryDatabase { // Migration: Change sample_rate from INTEGER to REAL for decimal precision (44.1kHz, 88.2kHz, etc.) // Check if sample_rate is currently INTEGER - let sample_rate_type: String = self.conn + let sample_rate_type: String = self + .conn .query_row( "SELECT type FROM pragma_table_info('local_tracks') WHERE name = 'sample_rate'", [], @@ -464,8 +480,9 @@ impl LibraryDatabase { // SQLite doesn't support ALTER COLUMN type change, need to recreate table // CRITICAL: Explicitly list all columns to handle different DB versions safely - self.conn.execute_batch( - r#" + self.conn + .execute_batch( + r#" -- Clean up any leftover temp table from previous failed migration DROP TABLE IF EXISTS local_tracks_new; @@ -529,8 +546,11 @@ impl LibraryDatabase { CREATE UNIQUE INDEX IF NOT EXISTS idx_tracks_file_nocue ON local_tracks(file_path) WHERE cue_file_path IS NULL; - "# - ).map_err(|e| LibraryError::Database(format!("sample_rate migration failed: {}", e)))?; + "#, + ) + .map_err(|e| { + LibraryError::Database(format!("sample_rate migration failed: {}", e)) + })?; // Add optional columns if they existed in old table // These were added in previous migrations, so they may or may not exist @@ -558,7 +578,8 @@ impl LibraryDatabase { } // Re-add source and qobuz_track_id columns if they don't exist - let has_source: bool = self.conn + let has_source: bool = self + .conn .query_row( "SELECT COUNT(*) FROM pragma_table_info('local_tracks') WHERE name = 'source'", [], @@ -587,9 +608,11 @@ impl LibraryDatabase { .unwrap_or(false); if !has_catalog { - self.conn.execute_batch( - "ALTER TABLE local_tracks ADD COLUMN catalog_number TEXT;" - ).map_err(|e| LibraryError::Database(format!("Failed to re-add catalog_number: {}", e)))?; + self.conn + .execute_batch("ALTER TABLE local_tracks ADD COLUMN catalog_number TEXT;") + .map_err(|e| { + LibraryError::Database(format!("Failed to re-add catalog_number: {}", e)) + })?; } log::info!("Migration completed: sample_rate is now REAL"); @@ -607,9 +630,9 @@ impl LibraryDatabase { if !has_canonical_name { log::info!("Running migration: adding canonical_name to artist_images"); - self.conn.execute_batch( - "ALTER TABLE artist_images ADD COLUMN canonical_name TEXT;" - ).map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; + self.conn + .execute_batch("ALTER TABLE artist_images ADD COLUMN canonical_name TEXT;") + .map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; } // Create folder_id index after all migrations have run (ensures column exists) @@ -629,8 +652,9 @@ impl LibraryDatabase { if !has_custom_order_table { log::info!("Running migration: creating playlist_track_custom_order table"); - self.conn.execute_batch( - "CREATE TABLE IF NOT EXISTS playlist_track_custom_order ( + self.conn + .execute_batch( + "CREATE TABLE IF NOT EXISTS playlist_track_custom_order ( id INTEGER PRIMARY KEY, qobuz_playlist_id INTEGER NOT NULL, track_id INTEGER NOT NULL, @@ -643,8 +667,9 @@ impl LibraryDatabase { CREATE INDEX IF NOT EXISTS idx_playlist_custom_order_playlist ON playlist_track_custom_order(qobuz_playlist_id); CREATE INDEX IF NOT EXISTS idx_playlist_custom_order_position - ON playlist_track_custom_order(qobuz_playlist_id, custom_position);" - ).map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; + ON playlist_track_custom_order(qobuz_playlist_id, custom_position);", + ) + .map_err(|e| LibraryError::Database(format!("Migration failed: {}", e)))?; } Ok(()) @@ -678,7 +703,8 @@ impl LibraryDatabase { .map_err(|e| LibraryError::Database(e.to_string()))?; // Get the folder ID (either newly inserted or existing) - let id: i64 = self.conn + let id: i64 = self + .conn .query_row( "SELECT id FROM library_folders WHERE path = ?", params![path], @@ -839,7 +865,8 @@ impl LibraryDatabase { /// This also clears the last_scan since the new path needs to be scanned pub fn update_folder_path(&self, id: i64, new_path: &str) -> Result<(), LibraryError> { // Check if new path already exists as a different folder - let existing: Option = self.conn + let existing: Option = self + .conn .query_row( "SELECT id FROM library_folders WHERE path = ? AND id != ?", params![new_path, id], @@ -849,7 +876,9 @@ impl LibraryDatabase { .map_err(|e| LibraryError::Database(e.to_string()))?; if existing.is_some() { - return Err(LibraryError::Database("A folder with this path already exists".to_string())); + return Err(LibraryError::Database( + "A folder with this path already exists".to_string(), + )); } self.conn @@ -880,13 +909,17 @@ impl LibraryDatabase { pub fn insert_track(&self, track: &LocalTrack) -> Result { // Don't overwrite Qobuz cached tracks with scanned data if self.is_qobuz_cached_track_by_path(&track.file_path)? { - log::debug!("Skipping track insert - already exists as Qobuz cached track: {}", track.file_path); + log::debug!( + "Skipping track insert - already exists as Qobuz cached track: {}", + track.file_path + ); // Return the existing ID - return self.conn + return self + .conn .query_row( "SELECT id FROM local_tracks WHERE file_path = ?1", params![track.file_path], - |row| row.get(0) + |row| row.get(0), ) .map_err(|e| LibraryError::Database(e.to_string())); } @@ -984,7 +1017,9 @@ impl LibraryDatabase { pub fn get_all_track_paths(&self) -> Result, LibraryError> { let mut stmt = self .conn - .prepare("SELECT id, file_path FROM local_tracks WHERE source IS NULL OR source = 'user'") + .prepare( + "SELECT id, file_path FROM local_tracks WHERE source IS NULL OR source = 'user'", + ) .map_err(|e| LibraryError::Database(e.to_string()))?; let rows = stmt @@ -1010,7 +1045,8 @@ impl LibraryDatabase { placeholders.join(",") ); - let params: Vec<&dyn rusqlite::ToSql> = ids.iter().map(|id| id as &dyn rusqlite::ToSql).collect(); + let params: Vec<&dyn rusqlite::ToSql> = + ids.iter().map(|id| id as &dyn rusqlite::ToSql).collect(); let count = self .conn @@ -1163,7 +1199,12 @@ impl LibraryDatabase { let all_artists: String = row.get::<_, Option>(3)?.unwrap_or_default(); let artwork_path: Option = row.get(6)?; - log::debug!("Album {} by {}: artwork_path = {:?}", album, artist, artwork_path); + log::debug!( + "Album {} by {}: artwork_path = {:?}", + album, + artist, + artwork_path + ); Ok(LocalAlbum { id: group_key.clone(), @@ -1183,7 +1224,9 @@ impl LibraryDatabase { directory_path: row .get::<_, Option>(12)? .unwrap_or_else(|| group_key.clone()), - source: row.get::<_, Option>(13)?.unwrap_or_else(|| "user".to_string()), + source: row + .get::<_, Option>(13)? + .unwrap_or_else(|| "user".to_string()), }) }) .map_err(|e| LibraryError::Database(e.to_string()))?; @@ -1583,9 +1626,7 @@ impl LibraryDatabase { .map_err(|e| LibraryError::Database(e.to_string()))?; let rows = stmt - .query_map(params![&pattern], |row| { - Self::row_to_track(row) - }) + .query_map(params![&pattern], |row| Self::row_to_track(row)) .map_err(|e| LibraryError::Database(e.to_string()))?; let mut tracks = Vec::new(); @@ -1720,7 +1761,7 @@ pub struct PlaylistSettings { pub position: i32, pub has_local_content: LocalContentStatus, pub is_favorite: bool, - pub folder_id: Option, // ID of the folder this playlist belongs to (null = root) + pub folder_id: Option, // ID of the folder this playlist belongs to (null = root) pub created_at: i64, pub updated_at: i64, } @@ -1776,9 +1817,9 @@ pub struct PlaylistStats { pub struct PlaylistFolder { pub id: String, pub name: String, - pub icon_type: String, // "preset" or "custom" - pub icon_preset: String, // lucide icon name - pub icon_color: String, // hex color + pub icon_type: String, // "preset" or "custom" + pub icon_preset: String, // lucide icon name + pub icon_color: String, // hex color pub custom_image_path: Option, pub is_hidden: bool, pub position: i32, @@ -1830,7 +1871,10 @@ impl LibraryDatabase { // === Playlist Settings === /// Get playlist settings by Qobuz playlist ID - pub fn get_playlist_settings(&self, qobuz_playlist_id: u64) -> Result, LibraryError> { + pub fn get_playlist_settings( + &self, + qobuz_playlist_id: u64, + ) -> Result, LibraryError> { let result = self.conn.query_row( "SELECT qobuz_playlist_id, custom_artwork_path, sort_by, sort_order, last_search_query, notes, hidden, position, has_local_content, is_favorite, folder_id, created_at, updated_at @@ -1904,7 +1948,12 @@ impl LibraryDatabase { } /// Update just the sort settings for a playlist - pub fn update_playlist_sort(&self, qobuz_playlist_id: u64, sort_by: &str, sort_order: &str) -> Result<(), LibraryError> { + pub fn update_playlist_sort( + &self, + qobuz_playlist_id: u64, + sort_by: &str, + sort_order: &str, + ) -> Result<(), LibraryError> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs() as i64) @@ -1920,17 +1969,25 @@ impl LibraryDatabase { return self.save_playlist_settings(&settings); } - self.conn.execute( - "UPDATE playlist_settings SET sort_by = ?1, sort_order = ?2, updated_at = ?3 + self.conn + .execute( + "UPDATE playlist_settings SET sort_by = ?1, sort_order = ?2, updated_at = ?3 WHERE qobuz_playlist_id = ?4", - params![sort_by, sort_order, now, qobuz_playlist_id as i64], - ).map_err(|e| LibraryError::Database(format!("Failed to update playlist sort: {}", e)))?; + params![sort_by, sort_order, now, qobuz_playlist_id as i64], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to update playlist sort: {}", e)) + })?; Ok(()) } /// Update custom artwork path for a playlist - pub fn update_playlist_artwork(&self, qobuz_playlist_id: u64, artwork_path: Option<&str>) -> Result<(), LibraryError> { + pub fn update_playlist_artwork( + &self, + qobuz_playlist_id: u64, + artwork_path: Option<&str>, + ) -> Result<(), LibraryError> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs() as i64) @@ -1945,17 +2002,25 @@ impl LibraryDatabase { return self.save_playlist_settings(&settings); } - self.conn.execute( - "UPDATE playlist_settings SET custom_artwork_path = ?1, updated_at = ?2 + self.conn + .execute( + "UPDATE playlist_settings SET custom_artwork_path = ?1, updated_at = ?2 WHERE qobuz_playlist_id = ?3", - params![artwork_path, now, qobuz_playlist_id as i64], - ).map_err(|e| LibraryError::Database(format!("Failed to update playlist artwork: {}", e)))?; + params![artwork_path, now, qobuz_playlist_id as i64], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to update playlist artwork: {}", e)) + })?; Ok(()) } /// Update last search query for a playlist - pub fn update_playlist_search_query(&self, qobuz_playlist_id: u64, query: Option<&str>) -> Result<(), LibraryError> { + pub fn update_playlist_search_query( + &self, + qobuz_playlist_id: u64, + query: Option<&str>, + ) -> Result<(), LibraryError> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs() as i64) @@ -1970,21 +2035,29 @@ impl LibraryDatabase { return self.save_playlist_settings(&settings); } - self.conn.execute( - "UPDATE playlist_settings SET last_search_query = ?1, updated_at = ?2 + self.conn + .execute( + "UPDATE playlist_settings SET last_search_query = ?1, updated_at = ?2 WHERE qobuz_playlist_id = ?3", - params![query, now, qobuz_playlist_id as i64], - ).map_err(|e| LibraryError::Database(format!("Failed to update playlist search query: {}", e)))?; + params![query, now, qobuz_playlist_id as i64], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to update playlist search query: {}", e)) + })?; Ok(()) } /// Delete playlist settings pub fn delete_playlist_settings(&self, qobuz_playlist_id: u64) -> Result<(), LibraryError> { - self.conn.execute( - "DELETE FROM playlist_settings WHERE qobuz_playlist_id = ?1", - params![qobuz_playlist_id as i64], - ).map_err(|e| LibraryError::Database(format!("Failed to delete playlist settings: {}", e)))?; + self.conn + .execute( + "DELETE FROM playlist_settings WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to delete playlist settings: {}", e)) + })?; Ok(()) } @@ -1997,30 +2070,41 @@ impl LibraryDatabase { FROM playlist_settings ORDER BY position ASC, updated_at DESC" ).map_err(|e| LibraryError::Database(format!("Failed to prepare statement: {}", e)))?; - let settings = stmt.query_map([], |row| { - Ok(PlaylistSettings { - qobuz_playlist_id: row.get::<_, i64>(0)? as u64, - custom_artwork_path: row.get(1)?, - sort_by: row.get(2)?, - sort_order: row.get(3)?, - last_search_query: row.get(4)?, - notes: row.get(5)?, - hidden: row.get::<_, i32>(6)? != 0, - position: row.get(7)?, - has_local_content: LocalContentStatus::from_str(&row.get::<_, Option>(8)?.unwrap_or_default()), - is_favorite: row.get::<_, i32>(9).unwrap_or(0) != 0, - folder_id: row.get(10)?, - created_at: row.get(11)?, - updated_at: row.get(12)?, + let settings = stmt + .query_map([], |row| { + Ok(PlaylistSettings { + qobuz_playlist_id: row.get::<_, i64>(0)? as u64, + custom_artwork_path: row.get(1)?, + sort_by: row.get(2)?, + sort_order: row.get(3)?, + last_search_query: row.get(4)?, + notes: row.get(5)?, + hidden: row.get::<_, i32>(6)? != 0, + position: row.get(7)?, + has_local_content: LocalContentStatus::from_str( + &row.get::<_, Option>(8)?.unwrap_or_default(), + ), + is_favorite: row.get::<_, i32>(9).unwrap_or(0) != 0, + folder_id: row.get(10)?, + created_at: row.get(11)?, + updated_at: row.get(12)?, + }) }) - }).map_err(|e| LibraryError::Database(format!("Failed to query playlist settings: {}", e)))?; + .map_err(|e| { + LibraryError::Database(format!("Failed to query playlist settings: {}", e)) + })?; - settings.collect::, _>>() - .map_err(|e| LibraryError::Database(format!("Failed to collect playlist settings: {}", e))) + settings.collect::, _>>().map_err(|e| { + LibraryError::Database(format!("Failed to collect playlist settings: {}", e)) + }) } /// Update hidden status for a playlist - pub fn set_playlist_hidden(&self, qobuz_playlist_id: u64, hidden: bool) -> Result<(), LibraryError> { + pub fn set_playlist_hidden( + &self, + qobuz_playlist_id: u64, + hidden: bool, + ) -> Result<(), LibraryError> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs() as i64) @@ -2035,17 +2119,25 @@ impl LibraryDatabase { return self.save_playlist_settings(&settings); } - self.conn.execute( - "UPDATE playlist_settings SET hidden = ?1, updated_at = ?2 + self.conn + .execute( + "UPDATE playlist_settings SET hidden = ?1, updated_at = ?2 WHERE qobuz_playlist_id = ?3", - params![hidden as i32, now, qobuz_playlist_id as i64], - ).map_err(|e| LibraryError::Database(format!("Failed to update playlist hidden: {}", e)))?; + params![hidden as i32, now, qobuz_playlist_id as i64], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to update playlist hidden: {}", e)) + })?; Ok(()) } /// Update favorite status for a playlist - pub fn set_playlist_favorite(&self, qobuz_playlist_id: u64, favorite: bool) -> Result<(), LibraryError> { + pub fn set_playlist_favorite( + &self, + qobuz_playlist_id: u64, + favorite: bool, + ) -> Result<(), LibraryError> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs() as i64) @@ -2060,11 +2152,15 @@ impl LibraryDatabase { return self.save_playlist_settings(&settings); } - self.conn.execute( - "UPDATE playlist_settings SET is_favorite = ?1, updated_at = ?2 + self.conn + .execute( + "UPDATE playlist_settings SET is_favorite = ?1, updated_at = ?2 WHERE qobuz_playlist_id = ?3", - params![favorite as i32, now, qobuz_playlist_id as i64], - ).map_err(|e| LibraryError::Database(format!("Failed to update playlist favorite: {}", e)))?; + params![favorite as i32, now, qobuz_playlist_id as i64], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to update playlist favorite: {}", e)) + })?; Ok(()) } @@ -2075,16 +2171,23 @@ impl LibraryDatabase { "SELECT qobuz_playlist_id FROM playlist_settings WHERE is_favorite = 1 ORDER BY updated_at DESC" ).map_err(|e| LibraryError::Database(format!("Failed to prepare statement: {}", e)))?; - let ids = stmt.query_map([], |row| { - Ok(row.get::<_, i64>(0)? as u64) - }).map_err(|e| LibraryError::Database(format!("Failed to query favorite playlists: {}", e)))?; + let ids = stmt + .query_map([], |row| Ok(row.get::<_, i64>(0)? as u64)) + .map_err(|e| { + LibraryError::Database(format!("Failed to query favorite playlists: {}", e)) + })?; - ids.collect::, _>>() - .map_err(|e| LibraryError::Database(format!("Failed to collect favorite playlist IDs: {}", e))) + ids.collect::, _>>().map_err(|e| { + LibraryError::Database(format!("Failed to collect favorite playlist IDs: {}", e)) + }) } /// Update position for a playlist - pub fn set_playlist_position(&self, qobuz_playlist_id: u64, position: i32) -> Result<(), LibraryError> { + pub fn set_playlist_position( + &self, + qobuz_playlist_id: u64, + position: i32, + ) -> Result<(), LibraryError> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs() as i64) @@ -2099,11 +2202,15 @@ impl LibraryDatabase { return self.save_playlist_settings(&settings); } - self.conn.execute( - "UPDATE playlist_settings SET position = ?1, updated_at = ?2 + self.conn + .execute( + "UPDATE playlist_settings SET position = ?1, updated_at = ?2 WHERE qobuz_playlist_id = ?3", - params![position, now, qobuz_playlist_id as i64], - ).map_err(|e| LibraryError::Database(format!("Failed to update playlist position: {}", e)))?; + params![position, now, qobuz_playlist_id as i64], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to update playlist position: {}", e)) + })?; Ok(()) } @@ -2124,11 +2231,15 @@ impl LibraryDatabase { settings.position = index as i32; self.save_playlist_settings(&settings)?; } else { - self.conn.execute( - "UPDATE playlist_settings SET position = ?1, updated_at = ?2 + self.conn + .execute( + "UPDATE playlist_settings SET position = ?1, updated_at = ?2 WHERE qobuz_playlist_id = ?3", - params![index as i32, now, playlist_id as i64], - ).map_err(|e| LibraryError::Database(format!("Failed to reorder playlists: {}", e)))?; + params![index as i32, now, playlist_id as i64], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to reorder playlists: {}", e)) + })?; } } @@ -2138,28 +2249,37 @@ impl LibraryDatabase { // === Playlist Stats === /// Get playlist stats - pub fn get_playlist_stats(&self, qobuz_playlist_id: u64) -> Result, LibraryError> { - let result = self.conn.query_row( - "SELECT qobuz_playlist_id, play_count, last_played_at, created_at, updated_at + pub fn get_playlist_stats( + &self, + qobuz_playlist_id: u64, + ) -> Result, LibraryError> { + let result = self + .conn + .query_row( + "SELECT qobuz_playlist_id, play_count, last_played_at, created_at, updated_at FROM playlist_stats WHERE qobuz_playlist_id = ?1", - params![qobuz_playlist_id as i64], - |row| { - Ok(PlaylistStats { - qobuz_playlist_id: row.get::<_, i64>(0)? as u64, - play_count: row.get::<_, i32>(1)? as u32, - last_played_at: row.get(2)?, - created_at: row.get(3)?, - updated_at: row.get(4)?, - }) - }, - ).optional() - .map_err(|e| LibraryError::Database(format!("Failed to get playlist stats: {}", e)))?; + params![qobuz_playlist_id as i64], + |row| { + Ok(PlaylistStats { + qobuz_playlist_id: row.get::<_, i64>(0)? as u64, + play_count: row.get::<_, i32>(1)? as u32, + last_played_at: row.get(2)?, + created_at: row.get(3)?, + updated_at: row.get(4)?, + }) + }, + ) + .optional() + .map_err(|e| LibraryError::Database(format!("Failed to get playlist stats: {}", e)))?; Ok(result) } /// Increment play count and update last_played_at for a playlist - pub fn increment_playlist_play_count(&self, qobuz_playlist_id: u64) -> Result { + pub fn increment_playlist_play_count( + &self, + qobuz_playlist_id: u64, + ) -> Result { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs() as i64) @@ -2201,29 +2321,43 @@ impl LibraryDatabase { /// Get all playlist stats (for sorting by play count) pub fn get_all_playlist_stats(&self) -> Result, LibraryError> { - let mut stmt = self.conn.prepare( - "SELECT qobuz_playlist_id, play_count, last_played_at, created_at, updated_at - FROM playlist_stats ORDER BY play_count DESC" - ).map_err(|e| LibraryError::Database(format!("Failed to prepare statement: {}", e)))?; + let mut stmt = self + .conn + .prepare( + "SELECT qobuz_playlist_id, play_count, last_played_at, created_at, updated_at + FROM playlist_stats ORDER BY play_count DESC", + ) + .map_err(|e| LibraryError::Database(format!("Failed to prepare statement: {}", e)))?; - let stats = stmt.query_map([], |row| { - Ok(PlaylistStats { - qobuz_playlist_id: row.get::<_, i64>(0)? as u64, - play_count: row.get::<_, i32>(1)? as u32, - last_played_at: row.get(2)?, - created_at: row.get(3)?, - updated_at: row.get(4)?, + let stats = stmt + .query_map([], |row| { + Ok(PlaylistStats { + qobuz_playlist_id: row.get::<_, i64>(0)? as u64, + play_count: row.get::<_, i32>(1)? as u32, + last_played_at: row.get(2)?, + created_at: row.get(3)?, + updated_at: row.get(4)?, + }) }) - }).map_err(|e| LibraryError::Database(format!("Failed to query playlist stats: {}", e)))?; + .map_err(|e| { + LibraryError::Database(format!("Failed to query playlist stats: {}", e)) + })?; - stats.collect::, _>>() + stats + .collect::, _>>() .map_err(|e| LibraryError::Database(format!("Failed to collect playlist stats: {}", e))) } // === Playlist Folders === /// Create a new playlist folder - pub fn create_playlist_folder(&self, name: &str, icon_type: Option<&str>, icon_preset: Option<&str>, icon_color: Option<&str>) -> Result { + pub fn create_playlist_folder( + &self, + name: &str, + icon_type: Option<&str>, + icon_preset: Option<&str>, + icon_color: Option<&str>, + ) -> Result { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs() as i64) @@ -2232,8 +2366,13 @@ impl LibraryDatabase { let id = uuid::Uuid::new_v4().to_string(); // Get the next position - let max_position: i32 = self.conn - .query_row("SELECT COALESCE(MAX(position), -1) FROM playlist_folders", [], |row| row.get(0)) + let max_position: i32 = self + .conn + .query_row( + "SELECT COALESCE(MAX(position), -1) FROM playlist_folders", + [], + |row| row.get(0), + ) .unwrap_or(-1); let folder = PlaylistFolder { @@ -2276,27 +2415,35 @@ impl LibraryDatabase { FROM playlist_folders ORDER BY position ASC" ).map_err(|e| LibraryError::Database(format!("Failed to prepare statement: {}", e)))?; - let folders = stmt.query_map([], |row| { - Ok(PlaylistFolder { - id: row.get(0)?, - name: row.get(1)?, - icon_type: row.get(2)?, - icon_preset: row.get(3)?, - icon_color: row.get(4)?, - custom_image_path: row.get(5)?, - is_hidden: row.get::<_, i32>(6)? != 0, - position: row.get(7)?, - created_at: row.get(8)?, - updated_at: row.get(9)?, + let folders = stmt + .query_map([], |row| { + Ok(PlaylistFolder { + id: row.get(0)?, + name: row.get(1)?, + icon_type: row.get(2)?, + icon_preset: row.get(3)?, + icon_color: row.get(4)?, + custom_image_path: row.get(5)?, + is_hidden: row.get::<_, i32>(6)? != 0, + position: row.get(7)?, + created_at: row.get(8)?, + updated_at: row.get(9)?, + }) }) - }).map_err(|e| LibraryError::Database(format!("Failed to query playlist folders: {}", e)))?; + .map_err(|e| { + LibraryError::Database(format!("Failed to query playlist folders: {}", e)) + })?; - folders.collect::, _>>() - .map_err(|e| LibraryError::Database(format!("Failed to collect playlist folders: {}", e))) + folders.collect::, _>>().map_err(|e| { + LibraryError::Database(format!("Failed to collect playlist folders: {}", e)) + }) } /// Get a playlist folder by ID - pub fn get_playlist_folder(&self, folder_id: &str) -> Result, LibraryError> { + pub fn get_playlist_folder( + &self, + folder_id: &str, + ) -> Result, LibraryError> { let result = self.conn.query_row( "SELECT id, name, icon_type, icon_preset, icon_color, custom_image_path, is_hidden, position, created_at, updated_at FROM playlist_folders WHERE id = ?1", @@ -2338,14 +2485,16 @@ impl LibraryDatabase { .unwrap_or(0); // Get existing folder - let existing = self.get_playlist_folder(folder_id)? + let existing = self + .get_playlist_folder(folder_id)? .ok_or_else(|| LibraryError::Database("Folder not found".to_string()))?; let new_name = name.unwrap_or(&existing.name); let new_icon_type = icon_type.unwrap_or(&existing.icon_type); let new_icon_preset = icon_preset.unwrap_or(&existing.icon_preset); let new_icon_color = icon_color.unwrap_or(&existing.icon_color); - let new_custom_image_path = custom_image_path.unwrap_or(existing.custom_image_path.as_deref()); + let new_custom_image_path = + custom_image_path.unwrap_or(existing.custom_image_path.as_deref()); let new_is_hidden = is_hidden.unwrap_or(existing.is_hidden); self.conn.execute( @@ -2369,10 +2518,14 @@ impl LibraryDatabase { /// Delete a playlist folder (playlists return to root via ON DELETE SET NULL) pub fn delete_playlist_folder(&self, folder_id: &str) -> Result<(), LibraryError> { - self.conn.execute( - "DELETE FROM playlist_folders WHERE id = ?1", - params![folder_id], - ).map_err(|e| LibraryError::Database(format!("Failed to delete playlist folder: {}", e)))?; + self.conn + .execute( + "DELETE FROM playlist_folders WHERE id = ?1", + params![folder_id], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to delete playlist folder: {}", e)) + })?; Ok(()) } @@ -2385,17 +2538,23 @@ impl LibraryDatabase { .unwrap_or(0); for (position, folder_id) in folder_ids.iter().enumerate() { - self.conn.execute( - "UPDATE playlist_folders SET position = ?1, updated_at = ?2 WHERE id = ?3", - params![position as i32, now, folder_id], - ).map_err(|e| LibraryError::Database(format!("Failed to reorder folder: {}", e)))?; + self.conn + .execute( + "UPDATE playlist_folders SET position = ?1, updated_at = ?2 WHERE id = ?3", + params![position as i32, now, folder_id], + ) + .map_err(|e| LibraryError::Database(format!("Failed to reorder folder: {}", e)))?; } Ok(()) } /// Move a playlist to a folder (or root if folder_id is None) - pub fn move_playlist_to_folder(&self, qobuz_playlist_id: u64, folder_id: Option<&str>) -> Result<(), LibraryError> { + pub fn move_playlist_to_folder( + &self, + qobuz_playlist_id: u64, + folder_id: Option<&str>, + ) -> Result<(), LibraryError> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs() as i64) @@ -2419,66 +2578,97 @@ impl LibraryDatabase { } /// Get playlists in a specific folder (or root if folder_id is None) - pub fn get_playlists_in_folder(&self, folder_id: Option<&str>) -> Result, LibraryError> { + pub fn get_playlists_in_folder( + &self, + folder_id: Option<&str>, + ) -> Result, LibraryError> { if let Some(fid) = folder_id { let mut stmt = self.conn.prepare( "SELECT qobuz_playlist_id FROM playlist_settings WHERE folder_id = ?1 ORDER BY position ASC" ).map_err(|e| LibraryError::Database(format!("Failed to prepare statement: {}", e)))?; - let ids = stmt.query_map(params![fid], |row| { - Ok(row.get::<_, i64>(0)? as u64) - }).map_err(|e| LibraryError::Database(format!("Failed to query playlists in folder: {}", e)))?; + let ids = stmt + .query_map(params![fid], |row| Ok(row.get::<_, i64>(0)? as u64)) + .map_err(|e| { + LibraryError::Database(format!("Failed to query playlists in folder: {}", e)) + })?; - ids.collect::, _>>() - .map_err(|e| LibraryError::Database(format!("Failed to collect playlist IDs: {}", e))) + ids.collect::, _>>().map_err(|e| { + LibraryError::Database(format!("Failed to collect playlist IDs: {}", e)) + }) } else { let mut stmt = self.conn.prepare( "SELECT qobuz_playlist_id FROM playlist_settings WHERE folder_id IS NULL ORDER BY position ASC" ).map_err(|e| LibraryError::Database(format!("Failed to prepare statement: {}", e)))?; - let ids = stmt.query_map([], |row| { - Ok(row.get::<_, i64>(0)? as u64) - }).map_err(|e| LibraryError::Database(format!("Failed to query playlists in folder: {}", e)))?; + let ids = stmt + .query_map([], |row| Ok(row.get::<_, i64>(0)? as u64)) + .map_err(|e| { + LibraryError::Database(format!("Failed to query playlists in folder: {}", e)) + })?; - ids.collect::, _>>() - .map_err(|e| LibraryError::Database(format!("Failed to collect playlist IDs: {}", e))) + ids.collect::, _>>().map_err(|e| { + LibraryError::Database(format!("Failed to collect playlist IDs: {}", e)) + }) } } // === Playlist Local Tracks === /// Add a local track to a playlist - pub fn add_local_track_to_playlist(&self, qobuz_playlist_id: u64, local_track_id: i64, position: i32) -> Result<(), LibraryError> { + pub fn add_local_track_to_playlist( + &self, + qobuz_playlist_id: u64, + local_track_id: i64, + position: i32, + ) -> Result<(), LibraryError> { 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 OR REPLACE INTO playlist_local_tracks + self.conn + .execute( + "INSERT OR REPLACE INTO playlist_local_tracks (qobuz_playlist_id, local_track_id, position, added_at) VALUES (?1, ?2, ?3, ?4)", - params![qobuz_playlist_id as i64, local_track_id, position, now], - ).map_err(|e| LibraryError::Database(format!("Failed to add local track to playlist: {}", e)))?; + params![qobuz_playlist_id as i64, local_track_id, position, now], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to add local track to playlist: {}", e)) + })?; Ok(()) } /// Remove a local track from a playlist - pub fn remove_local_track_from_playlist(&self, qobuz_playlist_id: u64, local_track_id: i64) -> Result<(), LibraryError> { - self.conn.execute( - "DELETE FROM playlist_local_tracks + pub fn remove_local_track_from_playlist( + &self, + qobuz_playlist_id: u64, + local_track_id: i64, + ) -> Result<(), LibraryError> { + self.conn + .execute( + "DELETE FROM playlist_local_tracks WHERE qobuz_playlist_id = ?1 AND local_track_id = ?2", - params![qobuz_playlist_id as i64, local_track_id], - ).map_err(|e| LibraryError::Database(format!("Failed to remove local track from playlist: {}", e)))?; + params![qobuz_playlist_id as i64, local_track_id], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to remove local track from playlist: {}", e)) + })?; Ok(()) } /// Get all local tracks in a playlist - pub fn get_playlist_local_tracks(&self, qobuz_playlist_id: u64) -> Result, LibraryError> { - let mut stmt = self.conn.prepare( - "SELECT t.id, t.file_path, t.title, t.artist, t.album, t.album_artist, + pub fn get_playlist_local_tracks( + &self, + qobuz_playlist_id: u64, + ) -> Result, LibraryError> { + let mut stmt = self + .conn + .prepare( + "SELECT t.id, t.file_path, t.title, t.artist, t.album, t.album_artist, t.album_group_key, t.album_group_title, t.track_number, t.disc_number, t.year, t.genre, t.duration_secs, t.format, t.bit_depth, t.sample_rate, t.channels, t.file_size_bytes, t.cue_file_path, t.cue_start_secs, @@ -2487,63 +2677,13 @@ impl LibraryDatabase { FROM playlist_local_tracks plt JOIN local_tracks t ON plt.local_track_id = t.id WHERE plt.qobuz_playlist_id = ?1 - ORDER BY plt.position ASC" - ).map_err(|e| LibraryError::Database(format!("Failed to prepare statement: {}", e)))?; + ORDER BY plt.position ASC", + ) + .map_err(|e| LibraryError::Database(format!("Failed to prepare statement: {}", e)))?; - let tracks = stmt.query_map(params![qobuz_playlist_id as i64], |row| { - Ok(LocalTrack { - id: row.get(0)?, - file_path: row.get(1)?, - title: row.get(2)?, - artist: row.get(3)?, - album: row.get(4)?, - album_artist: row.get(5)?, - album_group_key: row.get::<_, Option>(6)?.unwrap_or_default(), - album_group_title: row.get::<_, Option>(7)?.unwrap_or_default(), - track_number: row.get(8)?, - disc_number: row.get(9)?, - year: row.get(10)?, - genre: row.get(11)?, - catalog_number: None, - duration_secs: row.get(12)?, - format: Self::parse_format(&row.get::<_, String>(13)?), - bit_depth: row.get(14)?, - sample_rate: row.get::<_, f64>(15)?, - channels: row.get(16)?, - file_size_bytes: row.get(17)?, - cue_file_path: row.get(18)?, - cue_start_secs: row.get(19)?, - cue_end_secs: row.get(20)?, - artwork_path: row.get(21)?, - last_modified: row.get(22)?, - indexed_at: row.get(23)?, - source: row.get(24)?, - qobuz_track_id: row.get(25)?, - }) - }).map_err(|e| LibraryError::Database(format!("Failed to query playlist local tracks: {}", e)))?; - - tracks.collect::, _>>() - .map_err(|e| LibraryError::Database(format!("Failed to collect playlist local tracks: {}", e))) - } - - /// Get all local tracks in a playlist with their positions (for mixed ordering) - pub fn get_playlist_local_tracks_with_position(&self, qobuz_playlist_id: u64) -> Result, LibraryError> { - let mut stmt = self.conn.prepare( - "SELECT t.id, t.file_path, t.title, t.artist, t.album, t.album_artist, - t.album_group_key, t.album_group_title, t.track_number, t.disc_number, - t.year, t.genre, t.duration_secs, t.format, t.bit_depth, t.sample_rate, - t.channels, t.file_size_bytes, t.cue_file_path, t.cue_start_secs, - t.cue_end_secs, t.artwork_path, t.last_modified, t.indexed_at, t.source, - t.qobuz_track_id, plt.position - FROM playlist_local_tracks plt - JOIN local_tracks t ON plt.local_track_id = t.id - WHERE plt.qobuz_playlist_id = ?1 - ORDER BY plt.position ASC" - ).map_err(|e| LibraryError::Database(format!("Failed to prepare statement: {}", e)))?; - - let tracks = stmt.query_map(params![qobuz_playlist_id as i64], |row| { - Ok(crate::library::PlaylistLocalTrack { - track: LocalTrack { + let tracks = stmt + .query_map(params![qobuz_playlist_id as i64], |row| { + Ok(LocalTrack { id: row.get(0)?, file_path: row.get(1)?, title: row.get(2)?, @@ -2571,43 +2711,132 @@ impl LibraryDatabase { indexed_at: row.get(23)?, source: row.get(24)?, qobuz_track_id: row.get(25)?, - }, - playlist_position: row.get(26)?, + }) }) - }).map_err(|e| LibraryError::Database(format!("Failed to query playlist local tracks with position: {}", e)))?; + .map_err(|e| { + LibraryError::Database(format!("Failed to query playlist local tracks: {}", e)) + })?; - tracks.collect::, _>>() - .map_err(|e| LibraryError::Database(format!("Failed to collect playlist local tracks with position: {}", e))) + tracks.collect::, _>>().map_err(|e| { + LibraryError::Database(format!("Failed to collect playlist local tracks: {}", e)) + }) + } + + /// Get all local tracks in a playlist with their positions (for mixed ordering) + pub fn get_playlist_local_tracks_with_position( + &self, + qobuz_playlist_id: u64, + ) -> Result, LibraryError> { + let mut stmt = self + .conn + .prepare( + "SELECT t.id, t.file_path, t.title, t.artist, t.album, t.album_artist, + t.album_group_key, t.album_group_title, t.track_number, t.disc_number, + t.year, t.genre, t.duration_secs, t.format, t.bit_depth, t.sample_rate, + t.channels, t.file_size_bytes, t.cue_file_path, t.cue_start_secs, + t.cue_end_secs, t.artwork_path, t.last_modified, t.indexed_at, t.source, + t.qobuz_track_id, plt.position + FROM playlist_local_tracks plt + JOIN local_tracks t ON plt.local_track_id = t.id + WHERE plt.qobuz_playlist_id = ?1 + ORDER BY plt.position ASC", + ) + .map_err(|e| LibraryError::Database(format!("Failed to prepare statement: {}", e)))?; + + let tracks = stmt + .query_map(params![qobuz_playlist_id as i64], |row| { + Ok(crate::library::PlaylistLocalTrack { + track: LocalTrack { + id: row.get(0)?, + file_path: row.get(1)?, + title: row.get(2)?, + artist: row.get(3)?, + album: row.get(4)?, + album_artist: row.get(5)?, + album_group_key: row.get::<_, Option>(6)?.unwrap_or_default(), + album_group_title: row.get::<_, Option>(7)?.unwrap_or_default(), + track_number: row.get(8)?, + disc_number: row.get(9)?, + year: row.get(10)?, + genre: row.get(11)?, + catalog_number: None, + duration_secs: row.get(12)?, + format: Self::parse_format(&row.get::<_, String>(13)?), + bit_depth: row.get(14)?, + sample_rate: row.get::<_, f64>(15)?, + channels: row.get(16)?, + file_size_bytes: row.get(17)?, + cue_file_path: row.get(18)?, + cue_start_secs: row.get(19)?, + cue_end_secs: row.get(20)?, + artwork_path: row.get(21)?, + last_modified: row.get(22)?, + indexed_at: row.get(23)?, + source: row.get(24)?, + qobuz_track_id: row.get(25)?, + }, + playlist_position: row.get(26)?, + }) + }) + .map_err(|e| { + LibraryError::Database(format!( + "Failed to query playlist local tracks with position: {}", + e + )) + })?; + + tracks.collect::, _>>().map_err(|e| { + LibraryError::Database(format!( + "Failed to collect playlist local tracks with position: {}", + e + )) + }) } /// Get count of local tracks in a playlist - pub fn get_playlist_local_track_count(&self, qobuz_playlist_id: u64) -> Result { - let count: u32 = self.conn.query_row( - "SELECT COUNT(*) FROM playlist_local_tracks WHERE qobuz_playlist_id = ?1", - params![qobuz_playlist_id as i64], - |row| row.get(0), - ).map_err(|e| LibraryError::Database(format!("Failed to count playlist local tracks: {}", e)))?; + pub fn get_playlist_local_track_count( + &self, + qobuz_playlist_id: u64, + ) -> Result { + let count: u32 = self + .conn + .query_row( + "SELECT COUNT(*) FROM playlist_local_tracks WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64], + |row| row.get(0), + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to count playlist local tracks: {}", e)) + })?; Ok(count) } /// Get local track counts for all playlists - pub fn get_all_playlist_local_track_counts(&self) -> Result, LibraryError> { - let mut stmt = self.conn.prepare( - "SELECT qobuz_playlist_id, COUNT(*) as count + pub fn get_all_playlist_local_track_counts( + &self, + ) -> Result, LibraryError> { + let mut stmt = self + .conn + .prepare( + "SELECT qobuz_playlist_id, COUNT(*) as count FROM playlist_local_tracks - GROUP BY qobuz_playlist_id" - ).map_err(|e| LibraryError::Database(format!("Failed to prepare query: {}", e)))?; + GROUP BY qobuz_playlist_id", + ) + .map_err(|e| LibraryError::Database(format!("Failed to prepare query: {}", e)))?; - let rows = stmt.query_map([], |row| { - let playlist_id: i64 = row.get(0)?; - let count: u32 = row.get(1)?; - Ok((playlist_id as u64, count)) - }).map_err(|e| LibraryError::Database(format!("Failed to query: {}", e)))?; + let rows = stmt + .query_map([], |row| { + let playlist_id: i64 = row.get(0)?; + let count: u32 = row.get(1)?; + Ok((playlist_id as u64, count)) + }) + .map_err(|e| LibraryError::Database(format!("Failed to query: {}", e)))?; let mut result = std::collections::HashMap::new(); for row in rows { - let (playlist_id, count) = row.map_err(|e| LibraryError::Database(format!("Failed to read row: {}", e)))?; + let (playlist_id, count) = + row.map_err(|e| LibraryError::Database(format!("Failed to read row: {}", e)))?; result.insert(playlist_id, count); } @@ -2615,22 +2844,35 @@ impl LibraryDatabase { } /// Update position of a local track in a playlist - pub fn update_local_track_position(&self, qobuz_playlist_id: u64, local_track_id: i64, new_position: i32) -> Result<(), LibraryError> { - self.conn.execute( - "UPDATE playlist_local_tracks SET position = ?1 + pub fn update_local_track_position( + &self, + qobuz_playlist_id: u64, + local_track_id: i64, + new_position: i32, + ) -> Result<(), LibraryError> { + self.conn + .execute( + "UPDATE playlist_local_tracks SET position = ?1 WHERE qobuz_playlist_id = ?2 AND local_track_id = ?3", - params![new_position, qobuz_playlist_id as i64, local_track_id], - ).map_err(|e| LibraryError::Database(format!("Failed to update local track position: {}", e)))?; + params![new_position, qobuz_playlist_id as i64, local_track_id], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to update local track position: {}", e)) + })?; Ok(()) } /// Clear all local tracks from a playlist pub fn clear_playlist_local_tracks(&self, qobuz_playlist_id: u64) -> Result<(), LibraryError> { - self.conn.execute( - "DELETE FROM playlist_local_tracks WHERE qobuz_playlist_id = ?1", - params![qobuz_playlist_id as i64], - ).map_err(|e| LibraryError::Database(format!("Failed to clear playlist local tracks: {}", e)))?; + self.conn + .execute( + "DELETE FROM playlist_local_tracks WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to clear playlist local tracks: {}", e)) + })?; Ok(()) } @@ -2639,25 +2881,37 @@ impl LibraryDatabase { /// Get custom track order for a playlist /// Returns Vec of (track_id, is_local, custom_position) - pub fn get_playlist_custom_order(&self, qobuz_playlist_id: u64) -> Result, LibraryError> { - let mut stmt = self.conn.prepare( - "SELECT track_id, is_local, custom_position + pub fn get_playlist_custom_order( + &self, + qobuz_playlist_id: u64, + ) -> Result, LibraryError> { + let mut stmt = self + .conn + .prepare( + "SELECT track_id, is_local, custom_position FROM playlist_track_custom_order WHERE qobuz_playlist_id = ?1 - ORDER BY custom_position ASC" - ).map_err(|e| LibraryError::Database(format!("Failed to prepare custom order query: {}", e)))?; + ORDER BY custom_position ASC", + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to prepare custom order query: {}", e)) + })?; - let rows = stmt.query_map(params![qobuz_playlist_id as i64], |row| { - Ok(( - row.get::<_, i64>(0)?, - row.get::<_, i32>(1)? != 0, - row.get::<_, i32>(2)? - )) - }).map_err(|e| LibraryError::Database(format!("Failed to query custom order: {}", e)))?; + let rows = stmt + .query_map(params![qobuz_playlist_id as i64], |row| { + Ok(( + row.get::<_, i64>(0)?, + row.get::<_, i32>(1)? != 0, + row.get::<_, i32>(2)?, + )) + }) + .map_err(|e| LibraryError::Database(format!("Failed to query custom order: {}", e)))?; let mut result = Vec::new(); for row in rows { - result.push(row.map_err(|e| LibraryError::Database(format!("Failed to read custom order row: {}", e)))?); + result.push(row.map_err(|e| { + LibraryError::Database(format!("Failed to read custom order row: {}", e)) + })?); } Ok(result) } @@ -2667,7 +2921,7 @@ impl LibraryDatabase { pub fn init_playlist_custom_order( &self, qobuz_playlist_id: u64, - track_ids: &[(i64, bool)], // (track_id, is_local) + track_ids: &[(i64, bool)], // (track_id, is_local) ) -> Result<(), LibraryError> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -2675,17 +2929,26 @@ impl LibraryDatabase { .as_secs() as i64; // Clear existing custom order - self.conn.execute( - "DELETE FROM playlist_track_custom_order WHERE qobuz_playlist_id = ?1", - params![qobuz_playlist_id as i64], - ).map_err(|e| LibraryError::Database(format!("Failed to clear existing custom order: {}", e)))?; + self.conn + .execute( + "DELETE FROM playlist_track_custom_order WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to clear existing custom order: {}", e)) + })?; // Insert new order - let mut stmt = self.conn.prepare( - "INSERT INTO playlist_track_custom_order + let mut stmt = self + .conn + .prepare( + "INSERT INTO playlist_track_custom_order (qobuz_playlist_id, track_id, is_local, custom_position, created_at, updated_at) - VALUES (?1, ?2, ?3, ?4, ?5, ?6)" - ).map_err(|e| LibraryError::Database(format!("Failed to prepare custom order insert: {}", e)))?; + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to prepare custom order insert: {}", e)) + })?; for (position, (track_id, is_local)) in track_ids.iter().enumerate() { stmt.execute(params![ @@ -2695,7 +2958,8 @@ impl LibraryDatabase { position as i32, now, now, - ]).map_err(|e| LibraryError::Database(format!("Failed to insert custom order: {}", e)))?; + ]) + .map_err(|e| LibraryError::Database(format!("Failed to insert custom order: {}", e)))?; } Ok(()) @@ -2705,7 +2969,7 @@ impl LibraryDatabase { pub fn set_playlist_custom_order( &self, qobuz_playlist_id: u64, - orders: &[(i64, bool, i32)], // (track_id, is_local, position) + orders: &[(i64, bool, i32)], // (track_id, is_local, position) ) -> Result<(), LibraryError> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -2713,17 +2977,26 @@ impl LibraryDatabase { .as_secs() as i64; // Clear existing custom order - self.conn.execute( - "DELETE FROM playlist_track_custom_order WHERE qobuz_playlist_id = ?1", - params![qobuz_playlist_id as i64], - ).map_err(|e| LibraryError::Database(format!("Failed to clear existing custom order: {}", e)))?; + self.conn + .execute( + "DELETE FROM playlist_track_custom_order WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to clear existing custom order: {}", e)) + })?; // Insert new order - let mut stmt = self.conn.prepare( - "INSERT INTO playlist_track_custom_order + let mut stmt = self + .conn + .prepare( + "INSERT INTO playlist_track_custom_order (qobuz_playlist_id, track_id, is_local, custom_position, created_at, updated_at) - VALUES (?1, ?2, ?3, ?4, ?5, ?6)" - ).map_err(|e| LibraryError::Database(format!("Failed to prepare custom order insert: {}", e)))?; + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to prepare custom order insert: {}", e)) + })?; for (track_id, is_local, position) in orders { stmt.execute(params![ @@ -2733,7 +3006,8 @@ impl LibraryDatabase { *position, now, now, - ]).map_err(|e| LibraryError::Database(format!("Failed to insert custom order: {}", e)))?; + ]) + .map_err(|e| LibraryError::Database(format!("Failed to insert custom order: {}", e)))?; } Ok(()) @@ -2753,12 +3027,15 @@ impl LibraryDatabase { .as_secs() as i64; // Get current position of the track - let current_position: Option = self.conn.query_row( - "SELECT custom_position FROM playlist_track_custom_order + let current_position: Option = self + .conn + .query_row( + "SELECT custom_position FROM playlist_track_custom_order WHERE qobuz_playlist_id = ?1 AND track_id = ?2 AND is_local = ?3", - params![qobuz_playlist_id as i64, track_id, is_local as i32], - |row| row.get(0), - ).ok(); + params![qobuz_playlist_id as i64, track_id, is_local as i32], + |row| row.get(0), + ) + .ok(); let current_position = match current_position { Some(pos) => pos, @@ -2781,54 +3058,83 @@ impl LibraryDatabase { // Shift other tracks to make room if new_position < current_position { // Moving up: shift tracks between new_position and current_position down - self.conn.execute( - "UPDATE playlist_track_custom_order + self.conn + .execute( + "UPDATE playlist_track_custom_order SET custom_position = custom_position + 1, updated_at = ?4 WHERE qobuz_playlist_id = ?1 AND custom_position >= ?2 AND custom_position < ?3", - params![qobuz_playlist_id as i64, new_position, current_position, now], - ).map_err(|e| LibraryError::Database(format!("Failed to shift tracks: {}", e)))?; + params![ + qobuz_playlist_id as i64, + new_position, + current_position, + now + ], + ) + .map_err(|e| LibraryError::Database(format!("Failed to shift tracks: {}", e)))?; } else { // Moving down: shift tracks between current_position and new_position up - self.conn.execute( - "UPDATE playlist_track_custom_order + self.conn + .execute( + "UPDATE playlist_track_custom_order SET custom_position = custom_position - 1, updated_at = ?4 WHERE qobuz_playlist_id = ?1 AND custom_position > ?2 AND custom_position <= ?3", - params![qobuz_playlist_id as i64, current_position, new_position, now], - ).map_err(|e| LibraryError::Database(format!("Failed to shift tracks: {}", e)))?; + params![ + qobuz_playlist_id as i64, + current_position, + new_position, + now + ], + ) + .map_err(|e| LibraryError::Database(format!("Failed to shift tracks: {}", e)))?; } // Update the track's position - self.conn.execute( - "UPDATE playlist_track_custom_order + self.conn + .execute( + "UPDATE playlist_track_custom_order SET custom_position = ?3, updated_at = ?5 WHERE qobuz_playlist_id = ?1 AND track_id = ?2 AND is_local = ?4", - params![qobuz_playlist_id as i64, track_id, new_position, is_local as i32, now], - ).map_err(|e| LibraryError::Database(format!("Failed to update track position: {}", e)))?; + params![ + qobuz_playlist_id as i64, + track_id, + new_position, + is_local as i32, + now + ], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to update track position: {}", e)) + })?; Ok(()) } /// Check if a playlist has custom order defined pub fn has_playlist_custom_order(&self, qobuz_playlist_id: u64) -> Result { - let count: i32 = self.conn.query_row( - "SELECT COUNT(*) FROM playlist_track_custom_order WHERE qobuz_playlist_id = ?1", - params![qobuz_playlist_id as i64], - |row| row.get(0), - ).map_err(|e| LibraryError::Database(format!("Failed to check custom order: {}", e)))?; + let count: i32 = self + .conn + .query_row( + "SELECT COUNT(*) FROM playlist_track_custom_order WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64], + |row| row.get(0), + ) + .map_err(|e| LibraryError::Database(format!("Failed to check custom order: {}", e)))?; Ok(count > 0) } /// Clear custom order for a playlist pub fn clear_playlist_custom_order(&self, qobuz_playlist_id: u64) -> Result<(), LibraryError> { - self.conn.execute( - "DELETE FROM playlist_track_custom_order WHERE qobuz_playlist_id = ?1", - params![qobuz_playlist_id as i64], - ).map_err(|e| LibraryError::Database(format!("Failed to clear custom order: {}", e)))?; + self.conn + .execute( + "DELETE FROM playlist_track_custom_order WHERE qobuz_playlist_id = ?1", + params![qobuz_playlist_id as i64], + ) + .map_err(|e| LibraryError::Database(format!("Failed to clear custom order: {}", e)))?; Ok(()) } @@ -2836,47 +3142,60 @@ impl LibraryDatabase { // === Album Settings === /// Get album settings - pub fn get_album_settings(&self, album_group_key: &str) -> Result, LibraryError> { - let result = self.conn.query_row( - "SELECT album_group_key, hidden, created_at, updated_at + pub fn get_album_settings( + &self, + album_group_key: &str, + ) -> Result, LibraryError> { + let result = self + .conn + .query_row( + "SELECT album_group_key, hidden, created_at, updated_at FROM album_settings WHERE album_group_key = ?1", - params![album_group_key], - |row| { - Ok(crate::library::AlbumSettings { - album_group_key: row.get(0)?, - hidden: row.get::<_, i32>(1)? != 0, - created_at: row.get(2)?, - updated_at: row.get(3)?, - }) - }, - ).optional() - .map_err(|e| LibraryError::Database(format!("Failed to get album settings: {}", e)))?; + params![album_group_key], + |row| { + Ok(crate::library::AlbumSettings { + album_group_key: row.get(0)?, + hidden: row.get::<_, i32>(1)? != 0, + created_at: row.get(2)?, + updated_at: row.get(3)?, + }) + }, + ) + .optional() + .map_err(|e| LibraryError::Database(format!("Failed to get album settings: {}", e)))?; Ok(result) } /// Set album hidden status - pub fn set_album_hidden(&self, album_group_key: &str, hidden: bool) -> Result<(), LibraryError> { + pub fn set_album_hidden( + &self, + album_group_key: &str, + hidden: bool, + ) -> Result<(), LibraryError> { 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 album_settings (album_group_key, hidden, created_at, updated_at) + self.conn + .execute( + "INSERT INTO album_settings (album_group_key, hidden, created_at, updated_at) VALUES (?1, ?2, ?3, ?4) ON CONFLICT(album_group_key) DO UPDATE SET hidden = excluded.hidden, updated_at = excluded.updated_at", - params![album_group_key, hidden as i32, now, now], - ).map_err(|e| LibraryError::Database(format!("Failed to set album hidden: {}", e)))?; + params![album_group_key, hidden as i32, now, now], + ) + .map_err(|e| LibraryError::Database(format!("Failed to set album hidden: {}", e)))?; Ok(()) } /// Get all hidden albums pub fn get_hidden_albums(&self) -> Result, LibraryError> { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare("SELECT album_group_key FROM album_settings WHERE hidden = 1") .map_err(|e| LibraryError::Database(e.to_string()))?; @@ -2912,19 +3231,24 @@ impl LibraryDatabase { qobuz_track_id: u64, file_path: &str, ) -> Result { - let updated = self.conn.execute( - "UPDATE local_tracks + let updated = self + .conn + .execute( + "UPDATE local_tracks SET source = 'qobuz_download', qobuz_track_id = ?1 WHERE file_path = ?2 AND (source IS NULL OR source != 'qobuz_download')", - params![qobuz_track_id as i64, file_path], - ) - .map_err(|e| LibraryError::Database(format!("Failed to repair cached track by path: {}", e)))?; + params![qobuz_track_id as i64, file_path], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to repair cached track by path: {}", e)) + })?; Ok(updated > 0) } /// Check if a track exists by file path (for repair matching) pub fn track_exists_by_path(&self, file_path: &str) -> Result { - let count: i64 = self.conn + let count: i64 = self + .conn .query_row( "SELECT COUNT(*) FROM local_tracks WHERE file_path = ?1", params![file_path], @@ -3015,21 +3339,21 @@ impl LibraryDatabase { artwork_path: Option<&str>, ) -> Result<(), LibraryError> { use std::time::SystemTime; - + // First, remove any existing entry for this qobuz_track_id to prevent duplicates let _ = self.remove_qobuz_cached_track(track_id); - + // Get file size if file exists let file_size_bytes = std::fs::metadata(file_path) .map(|m| m.len() as i64) .unwrap_or(0); - + // Get current timestamp let now = SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap() .as_secs() as i64; - + self.conn.execute( r#" INSERT INTO local_tracks ( @@ -3072,29 +3396,39 @@ impl LibraryDatabase { /// Remove a Qobuz cached track from the library by track_id /// Note: Database source field remains 'qobuz_download' for compatibility pub fn remove_qobuz_cached_track(&self, qobuz_track_id: u64) -> Result<(), LibraryError> { - self.conn.execute( - "DELETE FROM local_tracks WHERE qobuz_track_id = ?1 AND source = 'qobuz_download'", - params![qobuz_track_id as i64], - ) - .map_err(|e| LibraryError::Database(format!("Failed to remove Qobuz cached track: {}", e)))?; + self.conn + .execute( + "DELETE FROM local_tracks WHERE qobuz_track_id = ?1 AND source = 'qobuz_download'", + params![qobuz_track_id as i64], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to remove Qobuz cached track: {}", e)) + })?; Ok(()) } /// Remove all Qobuz cached tracks from the library /// Note: Database source field remains 'qobuz_download' for compatibility pub fn remove_all_qobuz_cached_tracks(&self) -> Result { - let count = self.conn.execute( - "DELETE FROM local_tracks WHERE source = 'qobuz_download'", - [], - ) - .map_err(|e| LibraryError::Database(format!("Failed to remove all Qobuz cached tracks: {}", e)))?; + let count = self + .conn + .execute( + "DELETE FROM local_tracks WHERE source = 'qobuz_download'", + [], + ) + .map_err(|e| { + LibraryError::Database(format!("Failed to remove all Qobuz cached tracks: {}", e)) + })?; Ok(count) } // === Artist Images Management === /// Get cached artist image - pub fn get_artist_image(&self, artist_name: &str) -> Result, LibraryError> { + pub fn get_artist_image( + &self, + artist_name: &str, + ) -> Result, LibraryError> { let result = self.conn.query_row( "SELECT artist_name, image_url, source, custom_image_path, canonical_name FROM artist_images WHERE artist_name = ?1", params![artist_name], @@ -3113,14 +3447,20 @@ impl LibraryDatabase { } /// Get all canonical artist names mapping (for bulk lookup) - pub fn get_all_canonical_names(&self) -> Result, LibraryError> { + pub fn get_all_canonical_names( + &self, + ) -> Result, LibraryError> { let mut stmt = self.conn.prepare( "SELECT artist_name, canonical_name FROM artist_images WHERE canonical_name IS NOT NULL" ).map_err(|e| LibraryError::Database(format!("Failed to prepare query: {}", e)))?; - let rows = stmt.query_map([], |row| { - Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) - }).map_err(|e| LibraryError::Database(format!("Failed to query canonical names: {}", e)))?; + let rows = stmt + .query_map([], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + }) + .map_err(|e| { + LibraryError::Database(format!("Failed to query canonical names: {}", e)) + })?; let mut map = std::collections::HashMap::new(); for row in rows { @@ -3139,7 +3479,13 @@ impl LibraryDatabase { source: &str, custom_image_path: Option<&str>, ) -> Result<(), LibraryError> { - self.cache_artist_image_with_canonical(artist_name, image_url, source, custom_image_path, None) + self.cache_artist_image_with_canonical( + artist_name, + image_url, + source, + custom_image_path, + None, + ) } /// Cache artist image with canonical name from Qobuz/Discogs @@ -3170,7 +3516,8 @@ impl LibraryDatabase { /// Check if a track exists locally by Qobuz track ID pub fn has_local_track_by_qobuz_id(&self, qobuz_track_id: u64) -> Result { - let count: i64 = self.conn + let count: i64 = self + .conn .query_row( "SELECT COUNT(*) FROM local_tracks WHERE qobuz_track_id = ?1", params![qobuz_track_id as i64], @@ -3181,13 +3528,19 @@ impl LibraryDatabase { } /// Check if a track exists locally by title, artist, and album (fuzzy match) - pub fn has_local_track_by_metadata(&self, title: &str, artist: &str, album: &str) -> Result { + pub fn has_local_track_by_metadata( + &self, + title: &str, + artist: &str, + album: &str, + ) -> Result { // Normalize strings for comparison let title_lower = title.to_lowercase(); let artist_lower = artist.to_lowercase(); let album_lower = album.to_lowercase(); - let count: i64 = self.conn + let count: i64 = self + .conn .query_row( "SELECT COUNT(*) FROM local_tracks WHERE LOWER(title) = ?1 AND LOWER(artist) = ?2 AND LOWER(album) = ?3", @@ -3199,7 +3552,10 @@ impl LibraryDatabase { } /// Get local track ID by Qobuz track ID (for downloaded tracks) - pub fn get_local_track_id_by_qobuz_id(&self, qobuz_track_id: u64) -> Result, LibraryError> { + pub fn get_local_track_id_by_qobuz_id( + &self, + qobuz_track_id: u64, + ) -> Result, LibraryError> { self.conn .query_row( "SELECT id FROM local_tracks WHERE qobuz_track_id = ?1", @@ -3211,7 +3567,12 @@ impl LibraryDatabase { } /// Get local track ID by metadata (title, artist, album) - pub fn get_local_track_id_by_metadata(&self, title: &str, artist: &str, album: &str) -> Result, LibraryError> { + pub fn get_local_track_id_by_metadata( + &self, + title: &str, + artist: &str, + album: &str, + ) -> Result, LibraryError> { let title_lower = title.to_lowercase(); let artist_lower = artist.to_lowercase(); let album_lower = album.to_lowercase(); @@ -3230,7 +3591,10 @@ impl LibraryDatabase { /// Batch check which track IDs have local copies /// Returns a set of Qobuz track IDs that have local versions - pub fn get_tracks_with_local_copies(&self, qobuz_track_ids: &[u64]) -> Result, LibraryError> { + pub fn get_tracks_with_local_copies( + &self, + qobuz_track_ids: &[u64], + ) -> Result, LibraryError> { use std::collections::HashSet; if qobuz_track_ids.is_empty() { @@ -3248,7 +3612,9 @@ impl LibraryDatabase { placeholders_str ); - let mut stmt = self.conn.prepare(&query) + let mut stmt = self + .conn + .prepare(&query) .map_err(|e| LibraryError::Database(e.to_string()))?; let params: Vec = qobuz_track_ids @@ -3256,9 +3622,11 @@ impl LibraryDatabase { .map(|&id| rusqlite::types::Value::Integer(id as i64)) .collect(); - let rows = stmt.query_map(rusqlite::params_from_iter(params.iter()), |row| { - row.get::<_, i64>(0) - }).map_err(|e| LibraryError::Database(e.to_string()))?; + let rows = stmt + .query_map(rusqlite::params_from_iter(params.iter()), |row| { + row.get::<_, i64>(0) + }) + .map_err(|e| LibraryError::Database(e.to_string()))?; let mut result = HashSet::new(); for row in rows { @@ -3290,11 +3658,18 @@ impl LibraryDatabase { return self.save_playlist_settings(&settings); } - self.conn.execute( - "UPDATE playlist_settings SET has_local_content = ?1, updated_at = ?2 + self.conn + .execute( + "UPDATE playlist_settings SET has_local_content = ?1, updated_at = ?2 WHERE qobuz_playlist_id = ?3", - params![status.as_str(), now, qobuz_playlist_id as i64], - ).map_err(|e| LibraryError::Database(format!("Failed to update playlist local content status: {}", e)))?; + params![status.as_str(), now, qobuz_playlist_id as i64], + ) + .map_err(|e| { + LibraryError::Database(format!( + "Failed to update playlist local content status: {}", + e + )) + })?; Ok(()) } @@ -3318,28 +3693,37 @@ impl LibraryDatabase { ORDER BY position ASC, updated_at DESC" }; - let mut stmt = self.conn.prepare(query) + let mut stmt = self + .conn + .prepare(query) .map_err(|e| LibraryError::Database(format!("Failed to prepare statement: {}", e)))?; - let settings = stmt.query_map([], |row| { - Ok(PlaylistSettings { - qobuz_playlist_id: row.get::<_, i64>(0)? as u64, - custom_artwork_path: row.get(1)?, - sort_by: row.get(2)?, - sort_order: row.get(3)?, - last_search_query: row.get(4)?, - notes: row.get(5)?, - hidden: row.get::<_, i32>(6)? != 0, - position: row.get(7)?, - has_local_content: LocalContentStatus::from_str(&row.get::<_, Option>(8)?.unwrap_or_default()), - is_favorite: row.get::<_, i32>(9).unwrap_or(0) != 0, - folder_id: row.get(10)?, - created_at: row.get(11)?, - updated_at: row.get(12)?, + let settings = stmt + .query_map([], |row| { + Ok(PlaylistSettings { + qobuz_playlist_id: row.get::<_, i64>(0)? as u64, + custom_artwork_path: row.get(1)?, + sort_by: row.get(2)?, + sort_order: row.get(3)?, + last_search_query: row.get(4)?, + notes: row.get(5)?, + hidden: row.get::<_, i32>(6)? != 0, + position: row.get(7)?, + has_local_content: LocalContentStatus::from_str( + &row.get::<_, Option>(8)?.unwrap_or_default(), + ), + is_favorite: row.get::<_, i32>(9).unwrap_or(0) != 0, + folder_id: row.get(10)?, + created_at: row.get(11)?, + updated_at: row.get(12)?, + }) }) - }).map_err(|e| LibraryError::Database(format!("Failed to query playlists by local content: {}", e)))?; + .map_err(|e| { + LibraryError::Database(format!("Failed to query playlists by local content: {}", e)) + })?; - settings.collect::, _>>() + settings + .collect::, _>>() .map_err(|e| LibraryError::Database(format!("Failed to collect playlists: {}", e))) } } diff --git a/src-tauri/src/listenbrainz/cache.rs b/src-tauri/src/listenbrainz/cache.rs index c68739ac3..33a9e2fa9 100644 --- a/src-tauri/src/listenbrainz/cache.rs +++ b/src-tauri/src/listenbrainz/cache.rs @@ -151,7 +151,11 @@ impl ListenBrainzCache { } /// Save token and username - pub fn set_credentials(&self, token: Option<&str>, user_name: Option<&str>) -> Result<(), String> { + pub fn set_credentials( + &self, + token: Option<&str>, + user_name: Option<&str>, + ) -> Result<(), String> { let now = Self::current_timestamp(); self.conn .execute( @@ -173,7 +177,9 @@ impl ListenBrainzCache { pub fn is_enabled(&self) -> Result { let enabled: i64 = self .conn - .query_row("SELECT enabled FROM lb_settings WHERE id = 1", [], |row| row.get(0)) + .query_row("SELECT enabled FROM lb_settings WHERE id = 1", [], |row| { + row.get(0) + }) .unwrap_or(1); Ok(enabled != 0) } @@ -208,7 +214,8 @@ impl ListenBrainzCache { self.enforce_queue_limits()?; let now = Self::current_timestamp(); - let artist_mbids_json = artist_mbids.map(|ids| serde_json::to_string(ids).unwrap_or_default()); + let artist_mbids_json = + artist_mbids.map(|ids| serde_json::to_string(ids).unwrap_or_default()); self.conn .execute( @@ -247,7 +254,9 @@ impl ListenBrainzCache { // Remove excess entries (keep newest) let count: i64 = self .conn - .query_row("SELECT COUNT(*) FROM lb_queue WHERE sent = 0", [], |row| row.get(0)) + .query_row("SELECT COUNT(*) FROM lb_queue WHERE sent = 0", [], |row| { + row.get(0) + }) .unwrap_or(0); if count >= QUEUE_MAX_SIZE { @@ -282,8 +291,8 @@ impl ListenBrainzCache { let listens = stmt .query_map(params![limit], |row| { let artist_mbids_json: Option = row.get(7)?; - let artist_mbids: Option> = artist_mbids_json - .and_then(|json| serde_json::from_str(&json).ok()); + let artist_mbids: Option> = + artist_mbids_json.and_then(|json| serde_json::from_str(&json).ok()); Ok(QueuedListen { id: row.get(0)?, @@ -325,7 +334,8 @@ impl ListenBrainzCache { .prepare(&sql) .map_err(|e| format!("Failed to prepare statement: {}", e))?; - let params: Vec<&dyn rusqlite::ToSql> = ids.iter().map(|id| id as &dyn rusqlite::ToSql).collect(); + let params: Vec<&dyn rusqlite::ToSql> = + ids.iter().map(|id| id as &dyn rusqlite::ToSql).collect(); stmt.execute(params.as_slice()) .map_err(|e| format!("Failed to mark listens as sent: {}", e))?; @@ -346,11 +356,9 @@ impl ListenBrainzCache { /// Get count of queued (unsent) listens pub fn get_queue_count(&self) -> Result { self.conn - .query_row( - "SELECT COUNT(*) FROM lb_queue WHERE sent = 0", - [], - |row| row.get::<_, i64>(0), - ) + .query_row("SELECT COUNT(*) FROM lb_queue WHERE sent = 0", [], |row| { + row.get::<_, i64>(0) + }) .map(|count| count as u32) .map_err(|e| format!("Failed to count queued listens: {}", e)) } diff --git a/src-tauri/src/lyrics/cache.rs b/src-tauri/src/lyrics/cache.rs index d75a7fda9..ea954cdaf 100644 --- a/src-tauri/src/lyrics/cache.rs +++ b/src-tauri/src/lyrics/cache.rs @@ -16,14 +16,18 @@ impl LyricsCacheDb { let conn = Connection::open(path) .map_err(|e| format!("Failed to open lyrics cache database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for lyrics cache database: {}", e))?; + let db = Self { conn }; db.init_schema()?; Ok(db) } fn init_schema(&self) -> Result<(), String> { - self.conn.execute_batch( - " + self.conn + .execute_batch( + " CREATE TABLE IF NOT EXISTS lyrics_cache ( id INTEGER PRIMARY KEY AUTOINCREMENT, track_id INTEGER, @@ -42,8 +46,8 @@ impl LyricsCacheDb { CREATE INDEX IF NOT EXISTS idx_lyrics_track_id ON lyrics_cache(track_id); CREATE INDEX IF NOT EXISTS idx_lyrics_cache_key ON lyrics_cache(cache_key); ", - ) - .map_err(|e| format!("Failed to initialize lyrics cache schema: {}", e))?; + ) + .map_err(|e| format!("Failed to initialize lyrics cache schema: {}", e))?; Ok(()) } diff --git a/src-tauri/src/musicbrainz/cache.rs b/src-tauri/src/musicbrainz/cache.rs index 3dddc2262..4655d9928 100644 --- a/src-tauri/src/musicbrainz/cache.rs +++ b/src-tauri/src/musicbrainz/cache.rs @@ -296,7 +296,11 @@ impl MusicBrainzCache { } /// Cache artist relationships - pub fn set_artist_relations(&self, mbid: &str, data: &ArtistRelationships) -> Result<(), String> { + pub fn set_artist_relations( + &self, + mbid: &str, + data: &ArtistRelationships, + ) -> Result<(), String> { let fetched_at = Self::current_timestamp(); let json = serde_json::to_string(data) .map_err(|e| format!("Failed to serialize relations: {}", e))?; @@ -350,7 +354,10 @@ impl MusicBrainzCache { .map_err(|e| format!("Failed to cleanup relations: {}", e))?; if total_deleted > 0 { - log::info!("MusicBrainz cache cleanup: removed {} expired entries", total_deleted); + log::info!( + "MusicBrainz cache cleanup: removed {} expired entries", + total_deleted + ); } Ok(total_deleted) @@ -392,7 +399,9 @@ impl MusicBrainzCache { let relations: i64 = self .conn - .query_row("SELECT COUNT(*) FROM mb_artist_relations", [], |row| row.get(0)) + .query_row("SELECT COUNT(*) FROM mb_artist_relations", [], |row| { + row.get(0) + }) .unwrap_or(0); Ok(CacheStats { diff --git a/src-tauri/src/offline/mod.rs b/src-tauri/src/offline/mod.rs index 9f473d50f..ccfb54968 100644 --- a/src-tauri/src/offline/mod.rs +++ b/src-tauri/src/offline/mod.rs @@ -7,7 +7,7 @@ //! - Offline settings persistence //! - Pending playlist sync queue (playlists created offline) -use rusqlite::{Connection, params}; +use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -105,6 +105,9 @@ impl OfflineStore { let conn = Connection::open(&db_path) .map_err(|e| format!("Failed to open offline settings database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for offline settings database: {}", e))?; + // Create base tables (with original schema for backward compatibility) conn.execute_batch( "CREATE TABLE IF NOT EXISTS offline_settings ( @@ -136,8 +139,9 @@ impl OfflineStore { created_at INTEGER NOT NULL, sent INTEGER NOT NULL DEFAULT 0 ); - CREATE INDEX IF NOT EXISTS idx_scrobble_queue_sent ON scrobble_queue(sent);" - ).map_err(|e| format!("Failed to create offline settings table: {}", e))?; + CREATE INDEX IF NOT EXISTS idx_scrobble_queue_sent ON scrobble_queue(sent);", + ) + .map_err(|e| format!("Failed to create offline settings table: {}", e))?; // Migration: Add new columns if they don't exist (run each separately to handle partial migrations) let migrations = [ @@ -274,13 +278,14 @@ impl OfflineStore { /// Get all pending (unsynced) playlists pub fn get_pending_playlists(&self) -> Result, String> { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare( "SELECT id, name, description, is_public, track_ids, COALESCE(local_track_ids, '[]'), COALESCE(local_track_paths, '[]'), created_at, synced, qobuz_playlist_id - FROM pending_playlist_sync WHERE synced = 0 ORDER BY created_at ASC" + FROM pending_playlist_sync WHERE synced = 0 ORDER BY created_at ASC", ) .map_err(|e| format!("Failed to prepare statement: {}", e))?; @@ -290,10 +295,12 @@ impl OfflineStore { let track_ids: Vec = serde_json::from_str(&track_ids_json).unwrap_or_default(); let local_track_ids_json: String = row.get(5)?; - let local_track_ids: Vec = serde_json::from_str(&local_track_ids_json).unwrap_or_default(); + let local_track_ids: Vec = + serde_json::from_str(&local_track_ids_json).unwrap_or_default(); let local_track_paths_json: String = row.get(6)?; - let local_track_paths: Vec = serde_json::from_str(&local_track_paths_json).unwrap_or_default(); + let local_track_paths: Vec = + serde_json::from_str(&local_track_paths_json).unwrap_or_default(); Ok(PendingPlaylist { id: row.get(0)?, @@ -316,7 +323,11 @@ impl OfflineStore { } /// Update the Qobuz playlist ID without marking as synced (for partial sync recovery) - pub fn update_qobuz_playlist_id(&self, pending_id: i64, qobuz_playlist_id: u64) -> Result<(), String> { + pub fn update_qobuz_playlist_id( + &self, + pending_id: i64, + qobuz_playlist_id: u64, + ) -> Result<(), String> { self.conn .execute( "UPDATE pending_playlist_sync SET qobuz_playlist_id = ?1 WHERE id = ?2", @@ -327,7 +338,11 @@ impl OfflineStore { } /// Mark a pending playlist as synced with its Qobuz ID - pub fn mark_playlist_synced(&self, pending_id: i64, qobuz_playlist_id: u64) -> Result<(), String> { + pub fn mark_playlist_synced( + &self, + pending_id: i64, + qobuz_playlist_id: u64, + ) -> Result<(), String> { self.conn .execute( "UPDATE pending_playlist_sync SET synced = 1, qobuz_playlist_id = ?1 WHERE id = ?2", @@ -361,15 +376,13 @@ impl OfflineStore { .map_err(|e| format!("Failed to prepare query: {}", e))?; let (current_qobuz_json, current_local_paths_json): (String, String) = stmt - .query_row(params![pending_id], |row| { - Ok((row.get(0)?, row.get(1)?)) - }) + .query_row(params![pending_id], |row| Ok((row.get(0)?, row.get(1)?))) .map_err(|e| format!("Failed to get pending playlist: {}", e))?; - let mut current_qobuz: Vec = serde_json::from_str(¤t_qobuz_json) - .unwrap_or_default(); - let mut current_local_paths: Vec = serde_json::from_str(¤t_local_paths_json) - .unwrap_or_default(); + let mut current_qobuz: Vec = + serde_json::from_str(¤t_qobuz_json).unwrap_or_default(); + let mut current_local_paths: Vec = + serde_json::from_str(¤t_local_paths_json).unwrap_or_default(); // Append new tracks current_qobuz.extend_from_slice(qobuz_track_ids); @@ -432,10 +445,11 @@ impl OfflineStore { /// Get all unsent scrobbles (up to 50 for Last.fm batch limit) pub fn get_queued_scrobbles(&self, limit: u32) -> Result, String> { - let mut stmt = self.conn + 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" + FROM scrobble_queue WHERE sent = 0 ORDER BY timestamp ASC LIMIT ?1", ) .map_err(|e| format!("Failed to prepare statement: {}", e))?; @@ -470,11 +484,13 @@ impl OfflineStore { placeholders.join(",") ); - let mut stmt = self.conn + let mut stmt = self + .conn .prepare(&sql) .map_err(|e| format!("Failed to prepare statement: {}", e))?; - let params: Vec<&dyn rusqlite::ToSql> = ids.iter().map(|id| id as &dyn rusqlite::ToSql).collect(); + let params: Vec<&dyn rusqlite::ToSql> = + ids.iter().map(|id| id as &dyn rusqlite::ToSql).collect(); stmt.execute(params.as_slice()) .map_err(|e| format!("Failed to mark scrobbles as sent: {}", e))?; @@ -489,7 +505,8 @@ impl OfflineStore { .unwrap_or(0) - (older_than_days as i64 * 24 * 60 * 60); - let deleted = self.conn + let deleted = self + .conn .execute( "DELETE FROM scrobble_queue WHERE sent = 1 AND created_at < ?1", params![cutoff], @@ -532,7 +549,10 @@ impl OfflineState { pub fn init_at(&self, base_dir: &std::path::Path) -> Result<(), String> { let new_store = OfflineStore::new_at(base_dir)?; - let mut guard = self.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let mut guard = self + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; *guard = Some(new_store); Ok(()) } @@ -583,7 +603,12 @@ pub async fn check_network_connectivity() -> bool { } } Err(e) => { - log::warn!("Network check attempt {} to {} failed: {}", attempt, endpoint, e); + log::warn!( + "Network check attempt {} to {} failed: {}", + attempt, + endpoint, + e + ); } } @@ -625,8 +650,13 @@ pub mod commands { offline_state: State<'_, OfflineState>, ) -> Result { let settings = { - let guard__ = offline_state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = offline_state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.get_settings()? }; @@ -659,11 +689,14 @@ pub mod commands { /// Get offline settings #[tauri::command] - pub fn get_offline_settings( - state: State<'_, OfflineState>, - ) -> Result { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + pub fn get_offline_settings(state: State<'_, OfflineState>) -> Result { + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.get_settings() } @@ -675,8 +708,13 @@ pub mod commands { app_handle: AppHandle, ) -> Result { { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.set_manual_offline_mode(enabled)?; } @@ -695,8 +733,13 @@ pub mod commands { enabled: bool, state: State<'_, OfflineState>, ) -> Result<(), String> { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.set_show_partial_playlists(enabled) } @@ -706,8 +749,13 @@ pub mod commands { enabled: bool, state: State<'_, OfflineState>, ) -> Result<(), String> { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.set_allow_cast_while_offline(enabled) } @@ -717,8 +765,13 @@ pub mod commands { enabled: bool, state: State<'_, OfflineState>, ) -> Result<(), String> { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.set_allow_immediate_scrobbling(enabled) } @@ -728,8 +781,13 @@ pub mod commands { enabled: bool, state: State<'_, OfflineState>, ) -> Result<(), String> { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.set_allow_accumulated_scrobbling(enabled) } @@ -739,8 +797,13 @@ pub mod commands { enabled: bool, state: State<'_, OfflineState>, ) -> Result<(), String> { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.set_show_network_folders_in_manual_offline(enabled) } @@ -762,9 +825,20 @@ pub mod commands { local_track_paths: Vec, state: State<'_, OfflineState>, ) -> Result { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; - store.create_pending_playlist(&name, description.as_deref(), is_public, &track_ids, &local_track_paths) + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; + store.create_pending_playlist( + &name, + description.as_deref(), + is_public, + &track_ids, + &local_track_paths, + ) } /// Get all playlists pending sync @@ -772,8 +846,13 @@ pub mod commands { pub fn get_pending_playlists( state: State<'_, OfflineState>, ) -> Result, String> { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.get_pending_playlists() } @@ -785,18 +864,26 @@ pub mod commands { local_track_paths: Vec, state: State<'_, OfflineState>, ) -> Result<(), String> { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.add_tracks_to_pending_playlist(pending_id, &qobuz_track_ids, &local_track_paths) } /// Get count of pending playlists #[tauri::command] - pub fn get_pending_playlist_count( - state: State<'_, OfflineState>, - ) -> Result { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + pub fn get_pending_playlist_count(state: State<'_, OfflineState>) -> Result { + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.get_pending_playlist_count() } @@ -807,8 +894,13 @@ pub mod commands { qobuz_playlist_id: u64, state: State<'_, OfflineState>, ) -> Result<(), String> { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.update_qobuz_playlist_id(pending_id, qobuz_playlist_id) } @@ -819,8 +911,13 @@ pub mod commands { qobuz_playlist_id: u64, state: State<'_, OfflineState>, ) -> Result<(), String> { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.mark_playlist_synced(pending_id, qobuz_playlist_id) } @@ -830,8 +927,13 @@ pub mod commands { pending_id: i64, state: State<'_, OfflineState>, ) -> Result<(), String> { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.delete_pending_playlist(pending_id) } @@ -846,8 +948,13 @@ pub mod commands { timestamp: i64, state: State<'_, OfflineState>, ) -> Result { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.queue_scrobble(&artist, &track, album.as_deref(), timestamp) } @@ -857,8 +964,13 @@ pub mod commands { limit: Option, state: State<'_, OfflineState>, ) -> Result, String> { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.get_queued_scrobbles(limit.unwrap_or(50)) } @@ -868,18 +980,26 @@ pub mod commands { ids: Vec, state: State<'_, OfflineState>, ) -> Result<(), String> { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.mark_scrobbles_sent(&ids) } /// Get count of queued (unsent) scrobbles #[tauri::command] - pub fn get_queued_scrobble_count( - state: State<'_, OfflineState>, - ) -> Result { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + pub fn get_queued_scrobble_count(state: State<'_, OfflineState>) -> Result { + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.get_queued_scrobble_count() } @@ -889,8 +1009,13 @@ pub mod commands { older_than_days: Option, state: State<'_, OfflineState>, ) -> Result { - let guard__ = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; - let store = guard__.as_ref().ok_or("No active session - please log in")?; + let guard__ = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; + let store = guard__ + .as_ref() + .ok_or("No active session - please log in")?; store.cleanup_sent_scrobbles(older_than_days.unwrap_or(7)) } } diff --git a/src-tauri/src/offline_cache/db.rs b/src-tauri/src/offline_cache/db.rs index c812905fc..bcea6565d 100644 --- a/src-tauri/src/offline_cache/db.rs +++ b/src-tauri/src/offline_cache/db.rs @@ -1,9 +1,11 @@ //! SQLite database for offline cache index -use rusqlite::{Connection, params}; +use rusqlite::{params, Connection}; use std::path::Path; -use super::{CachedTrackInfo, OfflineCacheStats, OfflineCacheStatus, ReadyTrackForSync, TrackCacheInfo}; +use super::{ + CachedTrackInfo, OfflineCacheStats, OfflineCacheStatus, ReadyTrackForSync, TrackCacheInfo, +}; /// Database wrapper for cached tracks index pub struct OfflineCacheDb { @@ -16,6 +18,9 @@ impl OfflineCacheDb { let conn = Connection::open(path) .map_err(|e| format!("Failed to open offline cache database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for offline cache database: {}", e))?; + let db = Self { conn }; db.init_schema()?; Ok(db) @@ -28,8 +33,9 @@ impl OfflineCacheDb { /// Initialize database schema fn init_schema(&self) -> Result<(), String> { - self.conn.execute_batch( - " + self.conn + .execute_batch( + " CREATE TABLE IF NOT EXISTS cached_tracks ( id INTEGER PRIMARY KEY AUTOINCREMENT, track_id INTEGER UNIQUE NOT NULL, @@ -55,8 +61,9 @@ impl OfflineCacheDb { CREATE INDEX IF NOT EXISTS idx_track_id ON cached_tracks(track_id); CREATE INDEX IF NOT EXISTS idx_status ON cached_tracks(status); CREATE INDEX IF NOT EXISTS idx_last_accessed ON cached_tracks(last_accessed_at); - " - ).map_err(|e| format!("Failed to initialize database schema: {}", e))?; + ", + ) + .map_err(|e| format!("Failed to initialize database schema: {}", e))?; Ok(()) } @@ -85,17 +92,29 @@ impl OfflineCacheDb { } /// Update track status - pub fn update_status(&self, track_id: u64, status: OfflineCacheStatus, error: Option<&str>) -> Result<(), String> { - self.conn.execute( - "UPDATE cached_tracks SET status = ?1, error_message = ?2 WHERE track_id = ?3", - params![status.as_str(), error, track_id as i64], - ).map_err(|e| format!("Failed to update status: {}", e))?; + pub fn update_status( + &self, + track_id: u64, + status: OfflineCacheStatus, + error: Option<&str>, + ) -> Result<(), String> { + self.conn + .execute( + "UPDATE cached_tracks SET status = ?1, error_message = ?2 WHERE track_id = ?3", + params![status.as_str(), error, track_id as i64], + ) + .map_err(|e| format!("Failed to update status: {}", e))?; Ok(()) } /// Update caching progress - pub fn update_progress(&self, track_id: u64, progress: u8, size_bytes: u64) -> Result<(), String> { + pub fn update_progress( + &self, + track_id: u64, + progress: u8, + size_bytes: u64, + ) -> Result<(), String> { self.conn.execute( "UPDATE cached_tracks SET progress_percent = ?1, file_size_bytes = ?2 WHERE track_id = ?3", params![progress as i64, size_bytes as i64, track_id as i64], @@ -116,21 +135,26 @@ impl OfflineCacheDb { /// Update last accessed time (for LRU) pub fn touch(&self, track_id: u64) -> Result<(), String> { - self.conn.execute( - "UPDATE cached_tracks SET last_accessed_at = datetime('now') WHERE track_id = ?1", - params![track_id as i64], - ).map_err(|e| format!("Failed to update access time: {}", e))?; + self.conn + .execute( + "UPDATE cached_tracks SET last_accessed_at = datetime('now') WHERE track_id = ?1", + params![track_id as i64], + ) + .map_err(|e| format!("Failed to update access time: {}", e))?; Ok(()) } /// Check if a track is cached and ready pub fn is_cached(&self, track_id: u64) -> Result { - let count: i64 = self.conn.query_row( - "SELECT COUNT(*) FROM cached_tracks WHERE track_id = ?1 AND status = 'ready'", - params![track_id as i64], - |row| row.get(0), - ).map_err(|e| format!("Failed to check cache: {}", e))?; + let count: i64 = self + .conn + .query_row( + "SELECT COUNT(*) FROM cached_tracks WHERE track_id = ?1 AND status = 'ready'", + params![track_id as i64], + |row| row.get(0), + ) + .map_err(|e| format!("Failed to check cache: {}", e))?; Ok(count > 0) } @@ -157,18 +181,20 @@ impl OfflineCacheDb { FROM cached_tracks WHERE status = 'ready'" ).map_err(|e| format!("Failed to prepare query: {}", e))?; - let tracks = stmt.query_map([], |row| { - Ok(ReadyTrackForSync { - track_id: row.get::<_, i64>(0)? as u64, - title: row.get(1)?, - artist: row.get(2)?, - album: row.get(3)?, - duration_secs: row.get::<_, i64>(4)? as u64, - file_path: row.get(5)?, - bit_depth: row.get::<_, Option>(6)?.map(|v| v as u32), - sample_rate: row.get(7)?, + let tracks = stmt + .query_map([], |row| { + Ok(ReadyTrackForSync { + track_id: row.get::<_, i64>(0)? as u64, + title: row.get(1)?, + artist: row.get(2)?, + album: row.get(3)?, + duration_secs: row.get::<_, i64>(4)? as u64, + file_path: row.get(5)?, + bit_depth: row.get::<_, Option>(6)?.map(|v| v as u32), + sample_rate: row.get(7)?, + }) }) - }).map_err(|e| format!("Failed to query tracks: {}", e))?; + .map_err(|e| format!("Failed to query tracks: {}", e))?; let mut result = Vec::new(); for track in tracks { @@ -219,25 +245,27 @@ impl OfflineCacheDb { FROM cached_tracks ORDER BY last_accessed_at DESC" ).map_err(|e| format!("Failed to prepare query: {}", e))?; - let tracks = stmt.query_map([], |row| { - Ok(CachedTrackInfo { - track_id: row.get::<_, i64>(0)? as u64, - title: row.get(1)?, - artist: row.get(2)?, - album: row.get(3)?, - album_id: row.get(4)?, - duration_secs: row.get::<_, i64>(5)? as u64, - file_size_bytes: row.get::<_, i64>(6)? as u64, - quality: row.get::<_, Option>(7)?.unwrap_or_default(), - bit_depth: row.get::<_, Option>(8)?.map(|v| v as u32), - sample_rate: row.get(9)?, - status: OfflineCacheStatus::from_str(&row.get::<_, String>(10)?), - progress_percent: row.get::<_, i64>(11)? as u8, - error_message: row.get(12)?, - created_at: row.get(13)?, - last_accessed_at: row.get(14)?, + let tracks = stmt + .query_map([], |row| { + Ok(CachedTrackInfo { + track_id: row.get::<_, i64>(0)? as u64, + title: row.get(1)?, + artist: row.get(2)?, + album: row.get(3)?, + album_id: row.get(4)?, + duration_secs: row.get::<_, i64>(5)? as u64, + file_size_bytes: row.get::<_, i64>(6)? as u64, + quality: row.get::<_, Option>(7)?.unwrap_or_default(), + bit_depth: row.get::<_, Option>(8)?.map(|v| v as u32), + sample_rate: row.get(9)?, + status: OfflineCacheStatus::from_str(&row.get::<_, String>(10)?), + progress_percent: row.get::<_, i64>(11)? as u8, + error_message: row.get(12)?, + created_at: row.get(13)?, + last_accessed_at: row.get(14)?, + }) }) - }).map_err(|e| format!("Failed to query tracks: {}", e))?; + .map_err(|e| format!("Failed to query tracks: {}", e))?; let mut result = Vec::new(); for track in tracks { @@ -250,33 +278,44 @@ impl OfflineCacheDb { /// Delete a track from cache pub fn delete_track(&self, track_id: u64) -> Result, String> { // Get file path before deleting - let file_path: Option = self.conn.query_row( - "SELECT file_path FROM cached_tracks WHERE track_id = ?1", - params![track_id as i64], - |row| row.get(0), - ).ok(); + let file_path: Option = self + .conn + .query_row( + "SELECT file_path FROM cached_tracks WHERE track_id = ?1", + params![track_id as i64], + |row| row.get(0), + ) + .ok(); - self.conn.execute( - "DELETE FROM cached_tracks WHERE track_id = ?1", - params![track_id as i64], - ).map_err(|e| format!("Failed to delete track: {}", e))?; + self.conn + .execute( + "DELETE FROM cached_tracks WHERE track_id = ?1", + params![track_id as i64], + ) + .map_err(|e| format!("Failed to delete track: {}", e))?; Ok(file_path) } /// Get statistics - pub fn get_stats(&self, cache_path: &str, limit_bytes: Option) -> Result { - let total_tracks: i64 = self.conn.query_row( - "SELECT COUNT(*) FROM cached_tracks", - [], - |row| row.get(0), - ).map_err(|e| format!("Failed to count tracks: {}", e))?; + pub fn get_stats( + &self, + cache_path: &str, + limit_bytes: Option, + ) -> Result { + let total_tracks: i64 = self + .conn + .query_row("SELECT COUNT(*) FROM cached_tracks", [], |row| row.get(0)) + .map_err(|e| format!("Failed to count tracks: {}", e))?; - let ready_tracks: i64 = self.conn.query_row( - "SELECT COUNT(*) FROM cached_tracks WHERE status = 'ready'", - [], - |row| row.get(0), - ).map_err(|e| format!("Failed to count ready tracks: {}", e))?; + let ready_tracks: i64 = self + .conn + .query_row( + "SELECT COUNT(*) FROM cached_tracks WHERE status = 'ready'", + [], + |row| row.get(0), + ) + .map_err(|e| format!("Failed to count ready tracks: {}", e))?; let downloading_tracks: i64 = self.conn.query_row( "SELECT COUNT(*) FROM cached_tracks WHERE status = 'downloading' OR status = 'queued'", @@ -284,11 +323,14 @@ impl OfflineCacheDb { |row| row.get(0), ).map_err(|e| format!("Failed to count downloading tracks: {}", e))?; - let failed_tracks: i64 = self.conn.query_row( - "SELECT COUNT(*) FROM cached_tracks WHERE status = 'failed'", - [], - |row| row.get(0), - ).map_err(|e| format!("Failed to count failed tracks: {}", e))?; + let failed_tracks: i64 = self + .conn + .query_row( + "SELECT COUNT(*) FROM cached_tracks WHERE status = 'failed'", + [], + |row| row.get(0), + ) + .map_err(|e| format!("Failed to count failed tracks: {}", e))?; let total_size: i64 = self.conn.query_row( "SELECT COALESCE(SUM(file_size_bytes), 0) FROM cached_tracks WHERE status = 'ready'", @@ -308,29 +350,38 @@ impl OfflineCacheDb { } /// Get tracks to evict (LRU order) to free up space - pub fn get_tracks_for_eviction(&self, bytes_to_free: u64) -> Result, String> { - let mut stmt = self.conn.prepare( - "SELECT track_id, file_path, file_size_bytes FROM cached_tracks + pub fn get_tracks_for_eviction( + &self, + bytes_to_free: u64, + ) -> Result, String> { + let mut stmt = self + .conn + .prepare( + "SELECT track_id, file_path, file_size_bytes FROM cached_tracks WHERE status = 'ready' - ORDER BY last_accessed_at ASC" - ).map_err(|e| format!("Failed to prepare eviction query: {}", e))?; + ORDER BY last_accessed_at ASC", + ) + .map_err(|e| format!("Failed to prepare eviction query: {}", e))?; let mut result = Vec::new(); let mut freed = 0u64; - let rows = stmt.query_map([], |row| { - Ok(( - row.get::<_, i64>(0)? as u64, - row.get::<_, String>(1)?, - row.get::<_, i64>(2)? as u64, - )) - }).map_err(|e| format!("Failed to query for eviction: {}", e))?; + let rows = stmt + .query_map([], |row| { + Ok(( + row.get::<_, i64>(0)? as u64, + row.get::<_, String>(1)?, + row.get::<_, i64>(2)? as u64, + )) + }) + .map_err(|e| format!("Failed to query for eviction: {}", e))?; for row in rows { if freed >= bytes_to_free { break; } - let (track_id, file_path, size) = row.map_err(|e| format!("Failed to read row: {}", e))?; + let (track_id, file_path, size) = + row.map_err(|e| format!("Failed to read row: {}", e))?; result.push((track_id, file_path)); freed += size; } @@ -341,15 +392,19 @@ impl OfflineCacheDb { /// Clear all entries pub fn clear_all(&self) -> Result, String> { // Get all file paths first - let mut stmt = self.conn.prepare("SELECT file_path FROM cached_tracks") + let mut stmt = self + .conn + .prepare("SELECT file_path FROM cached_tracks") .map_err(|e| format!("Failed to prepare query: {}", e))?; - let paths: Vec = stmt.query_map([], |row| row.get(0)) + let paths: Vec = stmt + .query_map([], |row| row.get(0)) .map_err(|e| format!("Failed to query paths: {}", e))? .filter_map(|r| r.ok()) .collect(); - self.conn.execute("DELETE FROM cached_tracks", []) + self.conn + .execute("DELETE FROM cached_tracks", []) .map_err(|e| format!("Failed to clear database: {}", e))?; Ok(paths) @@ -357,19 +412,23 @@ impl OfflineCacheDb { /// Update file path for a track (after organizing) pub fn update_file_path(&self, track_id: u64, new_path: &str) -> Result<(), String> { - self.conn.execute( - "UPDATE cached_tracks SET file_path = ?1 WHERE track_id = ?2", - params![new_path, track_id as i64], - ).map_err(|e| format!("Failed to update file path: {}", e))?; + self.conn + .execute( + "UPDATE cached_tracks SET file_path = ?1 WHERE track_id = ?2", + params![new_path, track_id as i64], + ) + .map_err(|e| format!("Failed to update file path: {}", e))?; Ok(()) } /// Update artwork path for a track pub fn update_artwork_path(&self, track_id: u64, artwork_path: &str) -> Result<(), String> { - self.conn.execute( - "UPDATE cached_tracks SET artwork_path = ?1 WHERE track_id = ?2", - params![artwork_path, track_id as i64], - ).map_err(|e| format!("Failed to update artwork path: {}", e))?; + self.conn + .execute( + "UPDATE cached_tracks SET artwork_path = ?1 WHERE track_id = ?2", + params![artwork_path, track_id as i64], + ) + .map_err(|e| format!("Failed to update artwork path: {}", e))?; Ok(()) } } diff --git a/src-tauri/src/plex/mod.rs b/src-tauri/src/plex/mod.rs index d04222638..36431e291 100644 --- a/src-tauri/src/plex/mod.rs +++ b/src-tauri/src/plex/mod.rs @@ -9,7 +9,7 @@ use std::hash::{Hash, Hasher}; use std::time::Duration; use reqwest::header::{HeaderMap, HeaderValue}; -use rusqlite::{Connection, params}; +use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; use tauri::State; @@ -171,6 +171,9 @@ fn open_plex_cache_db() -> Result { let conn = Connection::open(db_path) .map_err(|e| format!("Failed to open Plex cache database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for Plex cache database: {}", e))?; + conn.execute_batch( " CREATE TABLE IF NOT EXISTS plex_cache_sections ( @@ -199,8 +202,9 @@ fn open_plex_cache_db() -> Result { updated_at INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS idx_plex_cache_tracks_section ON plex_cache_tracks(section_key); - " - ).map_err(|e| format!("Failed to initialize Plex cache schema: {}", e))?; + ", + ) + .map_err(|e| format!("Failed to initialize Plex cache schema: {}", e))?; Ok(conn) } @@ -289,7 +293,9 @@ fn decode_xml_entities(input: &str) -> String { "quot" => Some('"'), "apos" => Some('\''), _ if entity.starts_with("#x") || entity.starts_with("#X") => { - u32::from_str_radix(&entity[2..], 16).ok().and_then(char::from_u32) + u32::from_str_radix(&entity[2..], 16) + .ok() + .and_then(char::from_u32) } _ if entity.starts_with('#') => { entity[1..].parse::().ok().and_then(char::from_u32) @@ -916,13 +922,25 @@ pub fn plex_cache_get_albums() -> Result, String> { row.get::<_, Option>(6)?, )) }) - .map_err(|e| format!("Failed to query Plex cache tracks for album aggregation: {}", e))?; + .map_err(|e| { + format!( + "Failed to query Plex cache tracks for album aggregation: {}", + e + ) + })?; let mut grouped: HashMap = HashMap::new(); for row in rows { - let (artist_opt, album_opt, duration_ms_opt, artwork_path, container, sampling_rate_hz_opt, bit_depth_opt) = - row.map_err(|e| format!("Failed to read Plex cache aggregation row: {}", e))?; + let ( + artist_opt, + album_opt, + duration_ms_opt, + artwork_path, + container, + sampling_rate_hz_opt, + bit_depth_opt, + ) = row.map_err(|e| format!("Failed to read Plex cache aggregation row: {}", e))?; let artist = artist_opt .map(|v| decode_xml_entities(v.trim())) .filter(|v| !v.is_empty()) @@ -934,19 +952,21 @@ pub fn plex_cache_get_albums() -> Result, String> { let album = normalize_album_title(Some(&artist), &album_raw); let album_key = plex_album_key(&artist, &album); - let entry = grouped.entry(album_key.clone()).or_insert_with(|| PlexCachedAlbum { - id: album_key.clone(), - title: album.clone(), - artist: artist.clone(), - artwork_path: artwork_path.clone(), - track_count: 0, - total_duration_secs: 0, - format: container.clone().unwrap_or_else(|| "flac".to_string()), - bit_depth: bit_depth_opt.map(|v| v as u32), - sample_rate: sampling_rate_hz_opt.map(|v| v as u32).unwrap_or(44100), - source: "plex".to_string(), - likely_single_file_album: false, - }); + let entry = grouped + .entry(album_key.clone()) + .or_insert_with(|| PlexCachedAlbum { + id: album_key.clone(), + title: album.clone(), + artist: artist.clone(), + artwork_path: artwork_path.clone(), + track_count: 0, + total_duration_secs: 0, + format: container.clone().unwrap_or_else(|| "flac".to_string()), + bit_depth: bit_depth_opt.map(|v| v as u32), + sample_rate: sampling_rate_hz_opt.map(|v| v as u32).unwrap_or(44100), + source: "plex".to_string(), + likely_single_file_album: false, + }); entry.track_count += 1; if let Some(duration_ms) = duration_ms_opt { @@ -1022,8 +1042,17 @@ pub fn plex_cache_get_album_tracks(album_key: String) -> Result Result) -> Result, String> { +pub fn plex_cache_search_tracks( + query: String, + limit: Option, +) -> Result, String> { let conn = open_plex_cache_db()?; let max = limit.unwrap_or(5000) as i64; let needle = format!("%{}%", query.to_lowercase()); @@ -1090,8 +1122,17 @@ pub fn plex_cache_search_tracks(query: String, limit: Option) -> Result) -> Result { +pub fn plex_cache_update_track_quality( + updates: Vec, +) -> Result { if updates.is_empty() { return Ok(0); } let mut conn = open_plex_cache_db()?; - let tx = conn - .transaction() - .map_err(|e| format!("Failed to start Plex cache quality update transaction: {}", e))?; + let tx = conn.transaction().map_err(|e| { + format!( + "Failed to start Plex cache quality update transaction: {}", + e + ) + })?; let now = now_epoch_secs(); let mut updated_rows = 0usize; @@ -1248,8 +1294,12 @@ pub fn plex_cache_update_track_quality(updates: Vec) -> updated_rows += affected; } - tx.commit() - .map_err(|e| format!("Failed to commit Plex cache quality update transaction: {}", e))?; + tx.commit().map_err(|e| { + format!( + "Failed to commit Plex cache quality update transaction: {}", + e + ) + })?; Ok(updated_rows) } @@ -1387,7 +1437,10 @@ mod tests { tracks[0].part_key.as_deref(), Some("/library/parts/999/file.flac") ); - assert_eq!(tracks[0].artwork_path.as_deref(), Some("/library/metadata/42/thumb/1")); + assert_eq!( + tracks[0].artwork_path.as_deref(), + Some("/library/metadata/42/thumb/1") + ); assert_eq!(tracks[0].sampling_rate_hz, Some(96000)); assert_eq!(tracks[0].bit_depth, Some(24)); } diff --git a/src-tauri/src/radio_engine/db.rs b/src-tauri/src/radio_engine/db.rs index 38b91ff37..0a40134f8 100644 --- a/src-tauri/src/radio_engine/db.rs +++ b/src-tauri/src/radio_engine/db.rs @@ -79,9 +79,9 @@ impl RadioDb { } pub fn open(path: &Path) -> Result { - let conn = Connection::open(path) - .map_err(|e| format!("Failed to open radio database: {}", e))?; - conn.execute_batch("PRAGMA journal_mode=WAL;") + let conn = + Connection::open(path).map_err(|e| format!("Failed to open radio database: {}", e))?; + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") .map_err(|e| format!("Failed to set WAL mode: {}", e))?; let db = Self { conn, @@ -379,7 +379,8 @@ impl RadioDb { let mut artists = Vec::new(); for row in rows { - artists.push(row.map_err(|e| format!("Failed to read recent artist row: {}", e))? as u64); + artists + .push(row.map_err(|e| format!("Failed to read recent artist row: {}", e))? as u64); } Ok(artists) } diff --git a/src-tauri/src/reco_store/db.rs b/src-tauri/src/reco_store/db.rs index 330c3724a..19c01bfaf 100644 --- a/src-tauri/src/reco_store/db.rs +++ b/src-tauri/src/reco_store/db.rs @@ -4,7 +4,9 @@ use rusqlite::{params, Connection}; use std::path::Path; use std::time::{SystemTime, UNIX_EPOCH}; -use crate::reco_store::{AlbumCardMeta, ArtistCardMeta, RecoEventInput, TopArtistSeed, TrackDisplayMeta}; +use crate::reco_store::{ + AlbumCardMeta, ArtistCardMeta, RecoEventInput, TopArtistSeed, TrackDisplayMeta, +}; #[derive(Debug, Clone)] pub struct RecoEventRecord { @@ -31,8 +33,11 @@ pub struct RecoStoreDb { impl RecoStoreDb { pub fn new(path: &Path) -> Result { - let conn = Connection::open(path) - .map_err(|e| format!("Failed to open reco database: {}", e))?; + let conn = + Connection::open(path).map_err(|e| format!("Failed to open reco database: {}", e))?; + + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for reco database: {}", e))?; let db = Self { conn }; db.init()?; Ok(db) @@ -150,7 +155,8 @@ impl RecoStoreDb { } pub fn get_recent_album_ids(&self, limit: u32) -> Result, String> { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare( r#" SELECT album_id, MAX(created_at) AS last_played @@ -175,7 +181,8 @@ impl RecoStoreDb { } pub fn get_recent_track_ids(&self, limit: u32) -> Result, String> { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare( r#" SELECT track_id, MAX(created_at) AS last_played @@ -272,7 +279,8 @@ impl RecoStoreDb { /// Get unique album_ids that have NULL genre_id (for backfill) pub fn get_album_ids_without_genre(&self, limit: u32) -> Result, String> { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare( r#" SELECT DISTINCT album_id @@ -296,7 +304,8 @@ impl RecoStoreDb { /// Update genre_id for all events with a given album_id pub fn update_genre_for_album(&self, album_id: &str, genre_id: u64) -> Result { - let affected = self.conn + let affected = self + .conn .execute( "UPDATE reco_events SET genre_id = ? WHERE album_id = ? AND genre_id IS NULL", params![genre_id, album_id], @@ -306,7 +315,8 @@ impl RecoStoreDb { } pub fn get_top_artist_ids(&self, limit: u32) -> Result, String> { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare( r#" SELECT artist_id, COUNT(*) AS play_count, MAX(created_at) AS last_played @@ -336,7 +346,8 @@ impl RecoStoreDb { } pub fn get_favorite_album_ids(&self, limit: u32) -> Result, String> { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare( r#" SELECT album_id, MAX(created_at) AS last_favorite @@ -361,7 +372,8 @@ impl RecoStoreDb { } pub fn get_favorite_track_ids(&self, limit: u32) -> Result, String> { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare( r#" SELECT track_id, MAX(created_at) AS last_favorite @@ -461,8 +473,13 @@ impl RecoStoreDb { Ok(count > 0) } - pub fn get_scored_album_ids(&self, score_type: &str, limit: u32) -> Result, String> { - let mut stmt = self.conn + pub fn get_scored_album_ids( + &self, + score_type: &str, + limit: u32, + ) -> Result, String> { + let mut stmt = self + .conn .prepare( r#" SELECT album_id @@ -486,7 +503,8 @@ impl RecoStoreDb { } pub fn get_scored_track_ids(&self, score_type: &str, limit: u32) -> Result, String> { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare( r#" SELECT track_id @@ -514,7 +532,8 @@ impl RecoStoreDb { score_type: &str, limit: u32, ) -> Result, String> { - let mut stmt = self.conn + let mut stmt = self + .conn .prepare( r#" SELECT artist_id, score @@ -598,7 +617,9 @@ impl RecoStoreDb { placeholders.join(",") ); - let mut stmt = self.conn.prepare(&query) + let mut stmt = self + .conn + .prepare(&query) .map_err(|e| format!("Failed to prepare album meta query: {}", e))?; let params_vec: Vec> = ids @@ -606,7 +627,8 @@ impl RecoStoreDb { .map(|id| Box::new(id.clone()) as Box) .collect(); - let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect(); + let params_refs: Vec<&dyn rusqlite::ToSql> = + params_vec.iter().map(|p| p.as_ref()).collect(); let rows = stmt .query_map(params_refs.as_slice(), |row| { @@ -670,7 +692,9 @@ impl RecoStoreDb { placeholders.join(",") ); - let mut stmt = self.conn.prepare(&query) + let mut stmt = self + .conn + .prepare(&query) .map_err(|e| format!("Failed to prepare track meta query: {}", e))?; let params_vec: Vec> = ids @@ -678,7 +702,8 @@ impl RecoStoreDb { .map(|id| Box::new(*id as i64) as Box) .collect(); - let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect(); + let params_refs: Vec<&dyn rusqlite::ToSql> = + params_vec.iter().map(|p| p.as_ref()).collect(); let rows = stmt .query_map(params_refs.as_slice(), |row| { @@ -755,7 +780,9 @@ impl RecoStoreDb { placeholders.join(",") ); - let mut stmt = self.conn.prepare(&query) + let mut stmt = self + .conn + .prepare(&query) .map_err(|e| format!("Failed to prepare artist meta query: {}", e))?; let params_vec: Vec> = ids @@ -763,7 +790,8 @@ impl RecoStoreDb { .map(|id| Box::new(*id as i64) as Box) .collect(); - let params_refs: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|p| p.as_ref()).collect(); + let params_refs: Vec<&dyn rusqlite::ToSql> = + params_vec.iter().map(|p| p.as_ref()).collect(); let rows = stmt .query_map(params_refs.as_slice(), |row| { @@ -771,7 +799,11 @@ impl RecoStoreDb { Ok(ArtistCardMeta { id: row.get(0)?, name: row.get(1)?, - image: if image_url.is_empty() { None } else { Some(image_url) }, + image: if image_url.is_empty() { + None + } else { + Some(image_url) + }, play_count: None, // filled by caller from seeds }) }) diff --git a/src-tauri/src/session_store/mod.rs b/src-tauri/src/session_store/mod.rs index 6798f5f29..9a32e5ee1 100644 --- a/src-tauri/src/session_store/mod.rs +++ b/src-tauri/src/session_store/mod.rs @@ -1,4 +1,4 @@ -use rusqlite::{Connection, params}; +use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; use std::path::Path; use std::sync::{Arc, Mutex}; @@ -85,7 +85,7 @@ impl SessionStore { .map_err(|e| format!("Failed to open session database: {}", e))?; // Enable WAL mode for better concurrent access - conn.execute_batch("PRAGMA journal_mode=WAL;") + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") .map_err(|e| format!("Failed to set WAL mode: {}", e))?; // Create tables @@ -130,7 +130,8 @@ impl SessionStore { [], |row| row.get(0), ) - .unwrap_or(0) > 0; + .unwrap_or(0) + > 0; if !has_hires { let _ = conn.execute_batch( @@ -138,7 +139,7 @@ impl SessionStore { ALTER TABLE queue_tracks ADD COLUMN hires INTEGER NOT NULL DEFAULT 0; ALTER TABLE queue_tracks ADD COLUMN bit_depth INTEGER; ALTER TABLE queue_tracks ADD COLUMN sample_rate REAL; - " + ", ); } @@ -149,7 +150,8 @@ impl SessionStore { [], |row| row.get(0), ) - .unwrap_or(0) > 0; + .unwrap_or(0) + > 0; if !has_is_local { let _ = conn.execute_batch( @@ -157,7 +159,7 @@ impl SessionStore { ALTER TABLE queue_tracks ADD COLUMN is_local INTEGER NOT NULL DEFAULT 0; ALTER TABLE queue_tracks ADD COLUMN album_id TEXT; ALTER TABLE queue_tracks ADD COLUMN artist_id INTEGER; - " + ", ); } @@ -167,13 +169,14 @@ impl SessionStore { [], |row| row.get(0), ) - .unwrap_or(0) > 0; + .unwrap_or(0) + > 0; if !has_source { let _ = conn.execute_batch( " ALTER TABLE queue_tracks ADD COLUMN source TEXT; - " + ", ); } @@ -188,7 +191,8 @@ impl SessionStore { .as_secs() as i64; // Use a transaction for atomicity - self.conn.execute("BEGIN TRANSACTION", []) + self.conn + .execute("BEGIN TRANSACTION", []) .map_err(|e| format!("Failed to begin transaction: {}", e))?; // Clear existing queue @@ -249,7 +253,8 @@ impl SessionStore { return Err(format!("Failed to update player state: {}", e)); } - self.conn.execute("COMMIT", []) + self.conn + .execute("COMMIT", []) .map_err(|e| format!("Failed to commit transaction: {}", e))?; Ok(()) @@ -359,7 +364,8 @@ impl SessionStore { /// Clear the session (e.g., on logout) pub fn clear_session(&self) -> Result<(), String> { - self.conn.execute("DELETE FROM queue_tracks", []) + self.conn + .execute("DELETE FROM queue_tracks", []) .map_err(|e| format!("Failed to clear queue: {}", e))?; self.conn.execute( @@ -393,7 +399,10 @@ impl SessionStoreState { /// Initialize the store at a specific directory pub fn init_at(&self, base_dir: &Path) -> Result<(), String> { let store = SessionStore::new_at(base_dir)?; - *self.store.lock().map_err(|e| format!("Lock error: {}", e))? = Some(store); + *self + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))? = Some(store); Ok(()) } @@ -428,7 +437,10 @@ pub fn save_session_state( saved_at: 0, // Will be set in save_session }; - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.save_session(&session) } @@ -437,7 +449,10 @@ pub fn save_session_state( pub fn load_session_state( state: tauri::State<'_, SessionStoreState>, ) -> Result { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.load_session() } @@ -447,7 +462,10 @@ pub fn save_session_volume( state: tauri::State<'_, SessionStoreState>, volume: f32, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.save_volume(volume) } @@ -457,7 +475,10 @@ pub fn save_session_position( state: tauri::State<'_, SessionStoreState>, position_secs: u64, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.save_position(position_secs) } @@ -468,16 +489,20 @@ pub fn save_session_playback_mode( shuffle: bool, repeat_mode: String, ) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.save_playback_mode(shuffle, &repeat_mode) } #[tauri::command] -pub fn clear_session( - state: tauri::State<'_, SessionStoreState>, -) -> Result<(), String> { - let guard = state.store.lock().map_err(|e| format!("Lock error: {}", e))?; +pub fn clear_session(state: tauri::State<'_, SessionStoreState>) -> Result<(), String> { + let guard = state + .store + .lock() + .map_err(|e| format!("Lock error: {}", e))?; let store = guard.as_ref().ok_or("No active session - please log in")?; store.clear_session() } diff --git a/src-tauri/src/updates/mod.rs b/src-tauri/src/updates/mod.rs index f915e0c6c..d665e1f45 100644 --- a/src-tauri/src/updates/mod.rs +++ b/src-tauri/src/updates/mod.rs @@ -109,8 +109,11 @@ impl UpdatesStore { } fn open_at(db_path: &Path) -> Result { - let conn = - Connection::open(db_path).map_err(|e| format!("Failed to open updates database: {}", e))?; + let conn = Connection::open(db_path) + .map_err(|e| format!("Failed to open updates database: {}", e))?; + + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("Failed to enable WAL for updates database: {}", e))?; conn.execute_batch( "CREATE TABLE IF NOT EXISTS update_preferences ( @@ -446,9 +449,12 @@ fn select_latest_valid_update( if !is_newer_version(current_version, &info.version) { continue; } - let is_blocked = state.with_store(|store| { - store.is_release_acknowledged(&info.version) || store.is_release_ignored(&info.version) - }).unwrap_or(false); + let is_blocked = state + .with_store(|store| { + store.is_release_acknowledged(&info.version) + || store.is_release_ignored(&info.version) + }) + .unwrap_or(false); if is_blocked { continue; } @@ -460,7 +466,9 @@ fn select_latest_valid_update( // ==================== Tauri commands ==================== #[tauri::command] -pub fn get_update_preferences(state: tauri::State) -> Result { +pub fn get_update_preferences( + state: tauri::State, +) -> Result { state.with_store(|store| store.get_preferences())? } @@ -481,7 +489,10 @@ pub fn set_show_whats_new_on_launch( } #[tauri::command] -pub fn acknowledge_release(version: String, state: tauri::State) -> Result<(), String> { +pub fn acknowledge_release( + version: String, + state: tauri::State, +) -> Result<(), String> { state.with_store(|store| store.acknowledge_release(&version))? } @@ -491,22 +502,34 @@ pub fn ignore_release(version: String, state: tauri::State) -> Res } #[tauri::command] -pub fn is_release_acknowledged(version: String, state: tauri::State) -> Result { +pub fn is_release_acknowledged( + version: String, + state: tauri::State, +) -> Result { state.with_store(|store| store.is_release_acknowledged(&version)) } #[tauri::command] -pub fn is_release_ignored(version: String, state: tauri::State) -> Result { +pub fn is_release_ignored( + version: String, + state: tauri::State, +) -> Result { state.with_store(|store| store.is_release_ignored(&version)) } #[tauri::command] -pub fn has_whats_new_been_shown(version: String, state: tauri::State) -> Result { +pub fn has_whats_new_been_shown( + version: String, + state: tauri::State, +) -> Result { state.with_store(|store| store.has_whats_new_been_shown(&version)) } #[tauri::command] -pub fn mark_whats_new_shown(version: String, state: tauri::State) -> Result<(), String> { +pub fn mark_whats_new_shown( + version: String, + state: tauri::State, +) -> Result<(), String> { state.with_store(|store| store.mark_whats_new_shown(&version))? } @@ -533,7 +556,10 @@ pub async fn check_for_updates( let current_version = state.current_version(); if mode == "launch" { - let prefs = match state.with_store(|store| store.get_preferences()).and_then(|r| r) { + let prefs = match state + .with_store(|store| store.get_preferences()) + .and_then(|r| r) + { Ok(p) => p, Err(e) => { warn!("[Updates] Failed to read preferences: {}", e);