diff --git a/src-tauri/src/commands_v2.rs b/src-tauri/src/commands_v2.rs index 657fe71b5..e13f8cbe3 100644 --- a/src-tauri/src/commands_v2.rs +++ b/src-tauri/src/commands_v2.rs @@ -6364,52 +6364,19 @@ pub async fn v2_subscribe_playlist( .map_err(|e| format!("Failed to fetch created playlist: {}", e)) } -#[tauri::command] -pub async fn v2_cache_track_for_offline( +/// Shared helper: spawn the download task for a single track. +/// Used by both v2_cache_track_for_offline (single) and v2_cache_tracks_batch_for_offline (batch). +fn spawn_track_cache_download( track_id: u64, - title: String, - artist: String, - album: Option, - album_id: Option, - duration_secs: u64, - quality: String, - bit_depth: Option, - sample_rate: Option, - state: State<'_, AppState>, - cache_state: State<'_, OfflineCacheState>, - library_state: State<'_, crate::library::LibraryState>, - app_handle: tauri::AppHandle, -) -> Result<(), String> { - log::info!("Command: v2_cache_track_for_offline {} - {} by {}", track_id, title, artist); - - let track_info = crate::offline_cache::TrackCacheInfo { - track_id, - title, - artist, - album, - album_id, - duration_secs, - quality, - bit_depth, - sample_rate, - }; - - let file_path = cache_state.track_file_path(track_id, "flac"); - let file_path_str = file_path.to_string_lossy().to_string(); - { - let guard = cache_state.db.lock().await; - let db = guard.as_ref().ok_or("No active session - please log in")?; - db.insert_track(&track_info, &file_path_str)?; - } - - let client = state.client.clone(); - let fetcher = cache_state.fetcher.clone(); - let db = cache_state.db.clone(); - let offline_root = cache_state.get_cache_path(); - let library_db = library_state.db.clone(); - let app = app_handle.clone(); - let semaphore = cache_state.cache_semaphore.clone(); - + file_path: std::path::PathBuf, + client: std::sync::Arc>, + fetcher: std::sync::Arc, + db: std::sync::Arc>>, + offline_root: String, + library_db: std::sync::Arc>>, + app: tauri::AppHandle, + semaphore: std::sync::Arc, +) { tokio::spawn(async move { let _permit = match semaphore.acquire_owned().await { Ok(permit) => permit, @@ -6567,6 +6534,129 @@ pub async fn v2_cache_track_for_offline( } } }); +} + +#[tauri::command] +pub async fn v2_cache_track_for_offline( + track_id: u64, + title: String, + artist: String, + album: Option, + album_id: Option, + duration_secs: u64, + quality: String, + bit_depth: Option, + sample_rate: Option, + state: State<'_, AppState>, + cache_state: State<'_, OfflineCacheState>, + library_state: State<'_, crate::library::LibraryState>, + app_handle: tauri::AppHandle, +) -> Result<(), String> { + log::info!("Command: v2_cache_track_for_offline {} - {} by {}", track_id, title, artist); + + let track_info = crate::offline_cache::TrackCacheInfo { + track_id, + title, + artist, + album, + album_id, + duration_secs, + quality, + bit_depth, + sample_rate, + }; + + let file_path = cache_state.track_file_path(track_id, "flac"); + let file_path_str = file_path.to_string_lossy().to_string(); + { + let guard = cache_state.db.lock().await; + let db = guard.as_ref().ok_or("No active session - please log in")?; + db.insert_track(&track_info, &file_path_str)?; + } + + spawn_track_cache_download( + track_id, + file_path, + state.client.clone(), + cache_state.fetcher.clone(), + cache_state.db.clone(), + cache_state.get_cache_path(), + library_state.db.clone(), + app_handle.clone(), + cache_state.cache_semaphore.clone(), + ); + + Ok(()) +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BatchTrackInfo { + pub id: u64, + pub title: String, + pub artist: String, + pub album: Option, + pub album_id: Option, + pub duration_secs: u64, + pub quality: String, + pub bit_depth: Option, + pub sample_rate: Option, +} + +#[tauri::command] +pub async fn v2_cache_tracks_batch_for_offline( + tracks: Vec, + state: State<'_, AppState>, + cache_state: State<'_, OfflineCacheState>, + library_state: State<'_, crate::library::LibraryState>, + app_handle: tauri::AppHandle, +) -> Result<(), String> { + log::info!("Command: v2_cache_tracks_batch_for_offline ({} tracks)", tracks.len()); + + // Build TrackCacheInfo + file_path pairs for batch insert + let mut batch: Vec<(crate::offline_cache::TrackCacheInfo, String)> = Vec::with_capacity(tracks.len()); + for track in &tracks { + let file_path = cache_state.track_file_path(track.id, "flac"); + let file_path_str = file_path.to_string_lossy().to_string(); + batch.push(( + crate::offline_cache::TrackCacheInfo { + track_id: track.id, + title: track.title.clone(), + artist: track.artist.clone(), + album: track.album.clone(), + album_id: track.album_id.clone(), + duration_secs: track.duration_secs, + quality: track.quality.clone(), + bit_depth: track.bit_depth, + sample_rate: track.sample_rate, + }, + file_path_str, + )); + } + + // Single transactional batch insert + { + let guard = cache_state.db.lock().await; + let db = guard.as_ref().ok_or("No active session - please log in")?; + let refs: Vec<(&crate::offline_cache::TrackCacheInfo, String)> = batch.iter().map(|(info, path)| (info, path.clone())).collect(); + db.insert_tracks_batch(&refs)?; + } + + // Spawn download tasks for each track + for track in &tracks { + let file_path = cache_state.track_file_path(track.id, "flac"); + spawn_track_cache_download( + track.id, + file_path, + state.client.clone(), + cache_state.fetcher.clone(), + cache_state.db.clone(), + cache_state.get_cache_path(), + library_state.db.clone(), + app_handle.clone(), + cache_state.cache_semaphore.clone(), + ); + } Ok(()) } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 222cb903f..4fe5f97e0 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -844,6 +844,7 @@ pub fn run() { commands_v2::v2_show_track_notification, commands_v2::v2_subscribe_playlist, commands_v2::v2_cache_track_for_offline, + commands_v2::v2_cache_tracks_batch_for_offline, commands_v2::v2_start_legacy_migration, commands_v2::v2_library_scan, commands_v2::v2_library_stop_scan, diff --git a/src-tauri/src/offline_cache/db.rs b/src-tauri/src/offline_cache/db.rs index bcea6565d..b6bea8782 100644 --- a/src-tauri/src/offline_cache/db.rs +++ b/src-tauri/src/offline_cache/db.rs @@ -91,6 +91,40 @@ impl OfflineCacheDb { Ok(()) } + /// Insert multiple tracks in a single transaction (batch queuing) + pub fn insert_tracks_batch(&self, tracks: &[(&TrackCacheInfo, String)]) -> Result<(), String> { + let tx = self.conn.unchecked_transaction() + .map_err(|e| format!("Failed to begin transaction: {}", e))?; + + { + let mut stmt = tx.prepare( + "INSERT OR REPLACE INTO cached_tracks + (track_id, title, artist, album, album_id, duration_secs, file_path, quality, bit_depth, sample_rate, status, progress_percent, created_at, last_accessed_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 'queued', 0, datetime('now'), datetime('now'))" + ).map_err(|e| format!("Failed to prepare batch insert: {}", e))?; + + for (info, file_path) in tracks { + stmt.execute(params![ + info.track_id as i64, + info.title, + info.artist, + info.album, + info.album_id, + info.duration_secs as i64, + file_path, + info.quality, + info.bit_depth.map(|v| v as i64), + info.sample_rate, + ]).map_err(|e| format!("Failed to insert track {}: {}", info.track_id, e))?; + } + } + + tx.commit() + .map_err(|e| format!("Failed to commit batch insert: {}", e))?; + + Ok(()) + } + /// Update track status pub fn update_status( &self, diff --git a/src/lib/components/views/PlaylistDetailView.svelte b/src/lib/components/views/PlaylistDetailView.svelte index 168cdf149..a85bedf0e 100644 --- a/src/lib/components/views/PlaylistDetailView.svelte +++ b/src/lib/components/views/PlaylistDetailView.svelte @@ -11,7 +11,7 @@ import TrackRow from '../TrackRow.svelte'; import PlaylistSuggestions from '../PlaylistSuggestions.svelte'; import { extractAdaptiveArtists } from '$lib/services/playlistSuggestionsService'; - import { type OfflineCacheStatus, cacheTrackForOffline, getOfflineCacheState } from '$lib/stores/offlineCacheState'; + import { type OfflineCacheStatus, cacheTrackForOffline, cacheTracksForOfflineBatch, getOfflineCacheState } from '$lib/stores/offlineCacheState'; import { subscribe as subscribeOffline, getStatus as getOfflineStatus, @@ -1937,22 +1937,20 @@ const playlistName = playlist?.name || ''; showToast(translate('playlist.preparingPlaylistOffline', { values: { count: tracksToCache.length, name: playlistName } }), 'info'); - for (const track of tracksToCache) { - try { - await cacheTrackForOffline({ - id: track.id, - title: track.title, - artist: track.artist || 'Unknown', - album: track.album, - albumId: track.albumId, - durationSecs: track.durationSeconds, - quality: '-', - bitDepth: track.bitDepth, - sampleRate: track.samplingRate, - }); - } catch (err) { - console.error(`Failed to queue offline cache for "${track.title}":`, err); - } + try { + await cacheTracksForOfflineBatch(tracksToCache.map(track => ({ + id: track.id, + title: track.title, + artist: track.artist || 'Unknown', + album: track.album, + albumId: track.albumId, + durationSecs: track.durationSeconds, + quality: '-', + bitDepth: track.bitDepth, + sampleRate: track.samplingRate, + }))); + } catch (err) { + console.error('Failed to batch queue offline cache:', err); } } diff --git a/src/lib/stores/offlineCacheState.ts b/src/lib/stores/offlineCacheState.ts index 67c9d5074..9f08b8f15 100644 --- a/src/lib/stores/offlineCacheState.ts +++ b/src/lib/stores/offlineCacheState.ts @@ -196,6 +196,48 @@ export async function cacheTrackForOffline(track: { } } +// Cache multiple tracks for offline in a single batch IPC call +export async function cacheTracksForOfflineBatch(tracks: Array<{ + id: number; + title: string; + artist: string; + album?: string; + albumId?: string; + durationSecs: number; + quality: string; + bitDepth?: number; + sampleRate?: number; +}>): Promise { + if (tracks.length === 0) return; + + // Mark all as queued immediately + for (const track of tracks) { + setOfflineCacheState(track.id, { status: 'queued', progress: 0 }); + } + + try { + await invoke('v2_cache_tracks_batch_for_offline', { + tracks: tracks.map(track => ({ + id: track.id, + title: track.title, + artist: track.artist, + album: track.album, + albumId: track.albumId, + durationSecs: track.durationSecs, + quality: track.quality, + bitDepth: track.bitDepth, + sampleRate: track.sampleRate, + })), + }); + } catch (err) { + console.error('Failed to batch cache tracks for offline:', err); + for (const track of tracks) { + setOfflineCacheState(track.id, { status: 'failed', progress: 0, error: String(err) }); + } + throw err; + } +} + // Remove a track from offline cache export async function removeCachedTrack(trackId: number): Promise { try { diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 3693de3d3..bbce34f24 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -15,6 +15,7 @@ startOfflineCacheEventListeners, stopOfflineCacheEventListeners, cacheTrackForOffline, + cacheTracksForOfflineBatch, removeCachedTrack, getOfflineCacheState, openAlbumFolder, @@ -1125,22 +1126,20 @@ showToast($t('toast.preparingTracksOffline', { values: { count: tracksToDownload.length, album: album.title } }), 'info'); - for (const track of tracksToDownload) { - try { - await cacheTrackForOffline({ - id: track.id, - title: track.title, - artist: track.artist || album.artist || 'Unknown', - album: album.title, - albumId: album.id, - durationSecs: track.durationSeconds, - quality: track.quality || '-', - bitDepth: track.bitDepth, - sampleRate: track.samplingRate, - }); - } catch (err) { - console.error(`Failed to queue download for "${track.title}":`, err); - } + try { + await cacheTracksForOfflineBatch(tracksToDownload.map(track => ({ + id: track.id, + title: track.title, + artist: track.artist || album.artist || 'Unknown', + album: album.title, + albumId: album.id, + durationSecs: track.durationSeconds, + quality: track.quality || '-', + bitDepth: track.bitDepth, + sampleRate: track.samplingRate, + }))); + } catch (err) { + console.error('Failed to batch queue downloads:', err); } } @@ -2024,22 +2023,20 @@ showToast($t('toast.preparingTracksOffline', { values: { count: tracksToDownload.length, album: selectedAlbum.title } }), 'info'); - for (const track of tracksToDownload) { - try { - await cacheTrackForOffline({ - id: track.id, - title: track.title, - artist: track.artist || selectedAlbum.artist || 'Unknown', - album: selectedAlbum.title, - albumId: selectedAlbum.id, - durationSecs: track.durationSeconds, - quality: track.quality || '-', - bitDepth: track.bitDepth, - sampleRate: track.samplingRate, - }); - } catch (err) { - console.error(`Failed to queue "${track.title}" for offline:`, err); - } + try { + await cacheTracksForOfflineBatch(tracksToDownload.map(track => ({ + id: track.id, + title: track.title, + artist: track.artist || selectedAlbum.artist || 'Unknown', + album: selectedAlbum.title, + albumId: selectedAlbum.id, + durationSecs: track.durationSeconds, + quality: track.quality || '-', + bitDepth: track.bitDepth, + sampleRate: track.samplingRate, + }))); + } catch (err) { + console.error('Failed to batch queue for offline:', err); } } @@ -2059,22 +2056,20 @@ showToast($t('toast.refreshingAlbumOffline', { values: { album: selectedAlbum.title } }), 'info'); - for (const track of selectedAlbum.tracks) { - try { - await cacheTrackForOffline({ - id: track.id, - title: track.title, - artist: track.artist || selectedAlbum.artist || 'Unknown', - album: selectedAlbum.title, - albumId: selectedAlbum.id, - durationSecs: track.durationSeconds, - quality: track.quality || '-', - bitDepth: track.bitDepth, - sampleRate: track.samplingRate, - }); - } catch (err) { - console.error(`Failed to refresh "${track.title}" for offline:`, err); - } + try { + await cacheTracksForOfflineBatch(selectedAlbum.tracks.map(track => ({ + id: track.id, + title: track.title, + artist: track.artist || selectedAlbum.artist || 'Unknown', + album: selectedAlbum.title, + albumId: selectedAlbum.id, + durationSecs: track.durationSeconds, + quality: track.quality || '-', + bitDepth: track.bitDepth, + sampleRate: track.samplingRate, + }))); + } catch (err) { + console.error('Failed to batch refresh for offline:', err); } } @@ -2097,22 +2092,20 @@ showToast($t('toast.refreshingAlbumOffline', { values: { album: album.title } }), 'info'); - for (const track of album.tracks.items) { - try { - await cacheTrackForOffline({ - id: track.id, - title: track.title, - artist: track.performer?.name || album.artist?.name || 'Unknown', - album: album.title, - albumId: album.id, - durationSecs: track.duration, - quality: track.hires_streamable ? 'Hi-Res' : '-', - bitDepth: track.maximum_bit_depth, - sampleRate: track.maximum_sampling_rate, - }); - } catch (err) { - console.error(`Failed to refresh "${track.title}" for offline:`, err); - } + try { + await cacheTracksForOfflineBatch(album.tracks.items.map(track => ({ + id: track.id, + title: track.title, + artist: track.performer?.name || album.artist?.name || 'Unknown', + album: album.title, + albumId: album.id, + durationSecs: track.duration, + quality: track.hires_streamable ? 'Hi-Res' : '-', + bitDepth: track.maximum_bit_depth, + sampleRate: track.maximum_sampling_rate, + }))); + } catch (err) { + console.error('Failed to batch refresh for offline:', err); } } catch (err) { console.error('Failed to load album:', err);