diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index c494dd135..bd98413b6 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -548,6 +548,7 @@ pub fn run() { library::commands::library_get_artist_images, library::commands::library_cache_artist_image, library::commands::library_set_custom_artist_image, + library::commands::library_get_canonical_names, // Playlist local content analysis commands (offline mode) library::commands::playlist_analyze_local_content, library::commands::playlist_get_local_content_status, diff --git a/src-tauri/src/library/commands.rs b/src-tauri/src/library/commands.rs index 256a99ccf..944c6b159 100644 --- a/src-tauri/src/library/commands.rs +++ b/src-tauri/src/library/commands.rs @@ -1570,6 +1570,7 @@ pub struct ArtistImageInfo { pub image_url: Option, pub source: Option, pub custom_image_path: Option, + pub canonical_name: Option, } /// Get cached artist image @@ -1598,17 +1599,33 @@ pub async fn library_get_artist_images( Ok(results) } -/// Cache artist image from Qobuz +/// Get all canonical artist names mapping +#[tauri::command] +pub async fn library_get_canonical_names( + state: State<'_, LibraryState>, +) -> Result, String> { + let db = state.db.lock().await; + db.get_all_canonical_names().map_err(|e| e.to_string()) +} + +/// Cache artist image from Qobuz/Discogs with canonical name #[tauri::command] pub async fn library_cache_artist_image( artist_name: String, image_url: String, source: String, + canonical_name: Option, state: State<'_, LibraryState>, ) -> Result<(), String> { let db = state.db.lock().await; - db.cache_artist_image(&artist_name, Some(&image_url), &source, None) - .map_err(|e| e.to_string()) + db.cache_artist_image_with_canonical( + &artist_name, + Some(&image_url), + &source, + None, + canonical_name.as_deref(), + ) + .map_err(|e| e.to_string()) } /// Set custom artist image diff --git a/src-tauri/src/library/database.rs b/src-tauri/src/library/database.rs index c102a3055..bd7f4a1c1 100644 --- a/src-tauri/src/library/database.rs +++ b/src-tauri/src/library/database.rs @@ -486,6 +486,23 @@ impl LibraryDatabase { log::info!("Migration completed: sample_rate is now REAL"); } + // Migration: Add canonical_name column to artist_images for artist name normalization + let has_canonical_name: bool = self.conn + .query_row( + "SELECT COUNT(*) FROM pragma_table_info('artist_images') WHERE name = 'canonical_name'", + [], + |row| row.get::<_, i32>(0), + ) + .map(|count| count > 0) + .unwrap_or(false); + + 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)))?; + } + Ok(()) } @@ -2281,7 +2298,7 @@ impl LibraryDatabase { /// Get cached artist image 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 FROM artist_images WHERE artist_name = ?1", + "SELECT artist_name, image_url, source, custom_image_path, canonical_name FROM artist_images WHERE artist_name = ?1", params![artist_name], |row| { Ok(crate::library::commands::ArtistImageInfo { @@ -2289,6 +2306,7 @@ impl LibraryDatabase { image_url: row.get(1)?, source: row.get(2)?, custom_image_path: row.get(3)?, + canonical_name: row.get(4)?, }) } ).optional() @@ -2296,13 +2314,44 @@ impl LibraryDatabase { Ok(result) } - /// Cache artist image + /// Get all canonical artist names mapping (for bulk lookup) + 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 mut map = std::collections::HashMap::new(); + for row in rows { + if let Ok((artist_name, canonical_name)) = row { + map.insert(artist_name, canonical_name); + } + } + Ok(map) + } + + /// Cache artist image with optional canonical name pub fn cache_artist_image( &self, artist_name: &str, image_url: Option<&str>, source: &str, custom_image_path: Option<&str>, + ) -> Result<(), LibraryError> { + self.cache_artist_image_with_canonical(artist_name, image_url, source, custom_image_path, None) + } + + /// Cache artist image with canonical name from Qobuz/Discogs + pub fn cache_artist_image_with_canonical( + &self, + artist_name: &str, + image_url: Option<&str>, + source: &str, + custom_image_path: Option<&str>, + canonical_name: Option<&str>, ) -> Result<(), LibraryError> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -2311,9 +2360,9 @@ impl LibraryDatabase { self.conn.execute( "INSERT OR REPLACE INTO artist_images - (artist_name, image_url, source, custom_image_path, fetched_at, updated_at) - VALUES (?1, ?2, ?3, ?4, ?5, ?6)", - params![artist_name, image_url, source, custom_image_path, now, now], + (artist_name, image_url, source, custom_image_path, canonical_name, fetched_at, updated_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![artist_name, image_url, source, custom_image_path, canonical_name, now, now], ) .map_err(|e| LibraryError::Database(format!("Failed to cache artist image: {}", e)))?; Ok(()) diff --git a/src/lib/components/VirtualizedArtistGrid.svelte b/src/lib/components/VirtualizedArtistGrid.svelte index 7ee50da02..7b4816c7b 100644 --- a/src/lib/components/VirtualizedArtistGrid.svelte +++ b/src/lib/components/VirtualizedArtistGrid.svelte @@ -227,6 +227,7 @@
{#each item.artists as artist (artist.name)} {@const artistImage = artistImages.get(artist.name)} + {@const displayName = artist.displayName || artist.name}
{#if artistImage} - {artist.name} + {displayName} {:else} {/if} @@ -250,7 +251,7 @@ {/if} -
{artist.name}
+
{displayName}
{artist.album_count} albums • {artist.track_count} tracks
diff --git a/src/lib/components/VirtualizedArtistList.svelte b/src/lib/components/VirtualizedArtistList.svelte index cee52bdaa..35d922180 100644 --- a/src/lib/components/VirtualizedArtistList.svelte +++ b/src/lib/components/VirtualizedArtistList.svelte @@ -204,6 +204,7 @@
{:else if item.type === 'artist'} {@const artistImage = artistImages.get(item.artist.name)} + {@const displayName = item.artist.displayName || item.artist.name}
{#if artistImage} - {item.artist.name} + {displayName} {:else} {/if}
-
{item.artist.name}
+
{displayName}
{item.artist.album_count} albums • {item.artist.track_count} tracks
diff --git a/src/lib/components/views/LocalLibraryView.svelte b/src/lib/components/views/LocalLibraryView.svelte index 3b1f57e30..e5ac51db2 100644 --- a/src/lib/components/views/LocalLibraryView.svelte +++ b/src/lib/components/views/LocalLibraryView.svelte @@ -236,21 +236,27 @@ return artists.filter(artist => artist.name.toLowerCase().includes(needle)); }); - // Memoized grouped artists with alpha index + // Memoized grouped artists with alpha index and display names let groupedArtistsMemo = $derived.by(() => { const filtered = filteredArtistsMemo; + // Add display names from canonical names mapping + const withDisplayNames = filtered.map(artist => ({ + ...artist, + displayName: canonicalNames.get(artist.name) || artist.name + })); + if (!artistGroupingEnabled) { return { - grouped: [{ key: '', id: 'ungrouped', artists: filtered }], + grouped: [{ key: '', id: 'ungrouped', artists: withDisplayNames }], alphaGroups: new Set() }; } - // Group by first letter - const groups = new Map(); - for (const artist of filtered) { - const key = alphaGroupKey(artist.name); + // Group by first letter of DISPLAY name (canonical name if available) + const groups = new Map(); + for (const artist of withDisplayNames) { + const key = alphaGroupKey(artist.displayName); let group = groups.get(key); if (!group) { group = []; @@ -269,7 +275,10 @@ const grouped = keys.map(key => ({ key, id: `artist-alpha-${key}`, - artists: groups.get(key) ?? [] + // Sort artists within group by display name + artists: (groups.get(key) ?? []).sort((a, b) => + a.displayName.localeCompare(b.displayName) + ) })); return { @@ -397,6 +406,9 @@ // Qobuz artist images cache (artist name -> image URL) let artistImages = $state>(new Map()); + // Canonical artist names mapping (local name -> Qobuz/Discogs canonical name) + let canonicalNames = $state>(new Map()); + // Album edit modal state let showAlbumEditModal = $state(false); let editingAlbumTitle = $state(''); @@ -1678,7 +1690,7 @@ } /** - * Load cached artist images from database. + * Load cached artist images and canonical names from database. */ async function loadCachedArtistImages(): Promise { try { @@ -1688,6 +1700,7 @@ image_url: string | null; source: string | null; custom_image_path: string | null; + canonical_name: string | null; }>>('library_get_artist_images', { artistNames }); for (const cached of cachedImages) { @@ -1697,14 +1710,26 @@ if (imageUrl) { artistImages.set(cached.artist_name, imageUrl); } + // Store canonical name if available and different + if (cached.canonical_name && cached.canonical_name !== cached.artist_name) { + canonicalNames.set(cached.artist_name, cached.canonical_name); + } } // Trigger re-render artistImages = new Map(artistImages); + canonicalNames = new Map(canonicalNames); } catch (err) { console.debug('Failed to load cached artist images:', err); } } + /** + * Get the display name for an artist (canonical if available, otherwise original). + */ + function getArtistDisplayName(name: string): string { + return canonicalNames.get(name) || name; + } + /** * Fetch missing artist images from Qobuz only (Discogs disabled due to rate limiting). * Fetches sequentially with delays to avoid API abuse. @@ -1774,18 +1799,26 @@ ); const match = exactMatch ?? results.items[0]; const imageUrl = match.image?.large || match.image?.thumbnail || match.image?.small; + // Store canonical name from Qobuz (properly capitalized) + const canonicalName = match.name; if (imageUrl) { - // Cache in database + // Cache in database with canonical name await invoke('library_cache_artist_image', { artistName: name, imageUrl, - source: 'qobuz' + source: 'qobuz', + canonicalName }); artistImages.set(name, imageUrl); + // Also store canonical name mapping + if (canonicalName && canonicalName !== name) { + canonicalNames.set(name, canonicalName); + } // Update state periodically (every 5 artists) if (i % 5 === 4) { artistImages = new Map(artistImages); + canonicalNames = new Map(canonicalNames); } } } @@ -2648,6 +2681,7 @@
{#each filteredArtists as artist (artist.name)} {@const artistImage = artistImages.get(artist.name)} + {@const displayName = canonicalNames.get(artist.name) || artist.name}
{#if artistImage} - {artist.name} + {displayName} {:else} {/if} @@ -2671,7 +2705,7 @@ {/if} -
{artist.name}
+
{displayName}
{artist.album_count} albums • {artist.track_count} tracks