diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index a2a7be606..1a350fa04 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -387,6 +387,7 @@ pub fn run() { library::commands::playlist_add_local_track, library::commands::playlist_remove_local_track, library::commands::playlist_get_local_tracks, + library::commands::playlist_get_all_local_track_counts, library::commands::playlist_clear_local_tracks, // Playlist management commands library::commands::playlist_get_all_settings, @@ -478,6 +479,7 @@ pub fn run() { download_cache::commands::move_downloads_to_path, download_cache::commands::detect_legacy_downloads, download_cache::commands::start_legacy_migration, + download_cache::commands::sync_downloads_to_library, // Lyrics commands lyrics::commands::lyrics_get, lyrics::commands::lyrics_clear_cache, diff --git a/src-tauri/src/library/commands.rs b/src-tauri/src/library/commands.rs index a1953161d..eff2e610b 100644 --- a/src-tauri/src/library/commands.rs +++ b/src-tauri/src/library/commands.rs @@ -1031,6 +1031,18 @@ pub async fn playlist_get_local_tracks( .map_err(|e| e.to_string()) } +/// Get local track counts for all playlists +#[tauri::command] +pub async fn playlist_get_all_local_track_counts( + state: State<'_, LibraryState>, +) -> Result, String> { + log::info!("Command: playlist_get_all_local_track_counts"); + + let db = state.db.lock().await; + db.get_all_playlist_local_track_counts() + .map_err(|e| e.to_string()) +} + /// Clear all local tracks from a playlist #[tauri::command] pub async fn playlist_clear_local_tracks( diff --git a/src-tauri/src/library/database.rs b/src-tauri/src/library/database.rs index ffca099b5..b44c045a4 100644 --- a/src-tauri/src/library/database.rs +++ b/src-tauri/src/library/database.rs @@ -1561,6 +1561,29 @@ impl LibraryDatabase { 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 + FROM playlist_local_tracks + 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 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)))?; + result.insert(playlist_id, count); + } + + Ok(result) + } + /// 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( @@ -1664,29 +1687,46 @@ impl LibraryDatabase { bit_depth: Option, sample_rate: Option, ) -> Result<(), LibraryError> { + use std::time::SystemTime; + + // 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 ( file_path, title, artist, album, album_artist, track_number, disc_number, year, duration_secs, format, bit_depth, sample_rate, channels, + file_size_bytes, last_modified, indexed_at, source, qobuz_track_id - ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, 'qobuz_download', ?14) + ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, 'qobuz_download', ?17) "#, params![ file_path, title, artist, album.unwrap_or("Unknown Album"), - album.unwrap_or("Unknown Album"), // Use album as album_artist + artist, // Use artist as album_artist for proper grouping 0, // track_number - will be updated if metadata is available None::, // disc_number None::, // year duration_secs as i64, "flac", // Default format for downloads bit_depth.map(|v| v as i64), - sample_rate, + sample_rate.map(|v| v as i64).unwrap_or(44100), 2, // Assume stereo + file_size_bytes, + now, + now, track_id as i64, ], ) diff --git a/src/lib/components/PlaylistModal.svelte b/src/lib/components/PlaylistModal.svelte index 5ec358ee6..9b8bd41a4 100644 --- a/src/lib/components/PlaylistModal.svelte +++ b/src/lib/components/PlaylistModal.svelte @@ -43,8 +43,31 @@ let selectedPlaylistId = $state(null); let loading = $state(false); let error = $state(null); + + // Local track counts for playlists + let localTrackCounts = $state>(new Map()); let showDeleteConfirm = $state(false); + // Load local track counts + async function loadLocalTrackCounts() { + try { + const counts = await invoke>('playlist_get_all_local_track_counts'); + const map = new Map(); + for (const [id, count] of Object.entries(counts)) { + map.set(Number(id), count); + } + localTrackCounts = map; + } catch (err) { + console.debug('Failed to load local track counts:', err); + } + } + + // Get total track count for a playlist + function getTotalTrackCount(pl: Playlist): number { + const localCount = localTrackCounts.get(pl.id) ?? 0; + return pl.tracks_count + localCount; + } + // Reset form when modal opens $effect(() => { if (isOpen) { @@ -63,6 +86,7 @@ hidden = false; } else if (mode === 'addTrack') { selectedPlaylistId = null; + loadLocalTrackCounts(); } } }); @@ -298,7 +322,7 @@ {#each userPlaylists as pl (pl.id)} - + {/each} diff --git a/src/lib/components/Sidebar.svelte b/src/lib/components/Sidebar.svelte index 364e8ac35..2bddd157e 100644 --- a/src/lib/components/Sidebar.svelte +++ b/src/lib/components/Sidebar.svelte @@ -66,6 +66,7 @@ let userPlaylists = $state([]); let playlistSettings = $state>(new Map()); + let localTrackCounts = $state>(new Map()); let playlistsLoading = $state(false); let playlistsCollapsed = $state(false); let localLibraryCollapsed = $state(false); @@ -110,6 +111,12 @@ const playlistTooltipCache = new Map(); const tooltipLoadingIds = new Set(); + // Get total track count including local tracks + function getTotalTrackCount(playlist: Playlist): number { + const localCount = localTrackCounts.get(playlist.id) ?? 0; + return playlist.tracks_count + localCount; + } + // Fetch playlist artists for tooltip async function fetchPlaylistArtists(playlistId: number, trackCount: number): Promise { interface PlaylistDetails { @@ -152,8 +159,13 @@ const cached = playlistTooltipCache.get(playlist.id); if (cached) return cached; - // Return basic tooltip - fetch will happen on hover - return `${playlist.tracks_count} ${playlist.tracks_count === 1 ? 'Song' : 'Songs'}`; + // Return basic tooltip with combined count + const totalCount = getTotalTrackCount(playlist); + const localCount = localTrackCounts.get(playlist.id) ?? 0; + const countText = localCount > 0 + ? `${totalCount} Songs (${localCount} local)` + : `${totalCount} ${totalCount === 1 ? 'Song' : 'Songs'}`; + return countText; } // Load artist info for tooltip (called on hover, not during render) @@ -162,8 +174,14 @@ tooltipLoadingIds.add(playlist.id); - fetchPlaylistArtists(playlist.id, playlist.tracks_count).then(tooltip => { - playlistTooltipCache.set(playlist.id, tooltip); + const totalCount = getTotalTrackCount(playlist); + const localCount = localTrackCounts.get(playlist.id) ?? 0; + fetchPlaylistArtists(playlist.id, totalCount).then(tooltip => { + // Append local count info if there are local tracks + const finalTooltip = localCount > 0 + ? tooltip.replace(/(\d+) (Song|Songs)/, `$1 $2 (${localCount} local)`) + : tooltip; + playlistTooltipCache.set(playlist.id, finalTooltip); tooltipLoadingIds.delete(playlist.id); }); } @@ -246,6 +264,10 @@ loadPlaylistSettings(); } + export function refreshLocalTrackCounts() { + loadLocalTrackCounts(); + } + // Menu handling functions function closeMenu() { menuOpen = false; @@ -349,6 +371,7 @@ loadSortPreference(); loadUserPlaylists(); loadPlaylistSettings(); + loadLocalTrackCounts(); // Subscribe to offline state changes const unsubscribeOffline = subscribeOffline(() => { @@ -387,6 +410,19 @@ } } + async function loadLocalTrackCounts() { + try { + const counts = await invoke>('playlist_get_all_local_track_counts'); + const map = new Map(); + for (const [id, count] of Object.entries(counts)) { + map.set(Number(id), count); + } + localTrackCounts = map; + } catch (err) { + console.debug('Failed to load local track counts:', err); + } + } + function handleViewChange(view: string) { onNavigate(view); } diff --git a/src/lib/components/TrackRow.svelte b/src/lib/components/TrackRow.svelte index 7fa93c2b4..93575941f 100644 --- a/src/lib/components/TrackRow.svelte +++ b/src/lib/components/TrackRow.svelte @@ -179,11 +179,9 @@
{quality ?? ''}
- + {#if isLocal} -
- -
+
{:else if !hideFavorite}