feat(library): implement persistent artist images with Discogs fallback

- Add loadCachedArtistImages() to load from database
- Add fetchMissingArtistImages() with Qobuz + Discogs fallback
- Add discogs_search_artist command for artist lookups
- Artist images now persist between sessions
- Discogs used as fallback when Qobuz has no image

cp
This commit is contained in:
vicrodh committed 2026-01-15 10:06:52 -06:00
1 parent a5200d5d05
commit dd1df5bfee
4 files changed
+148 -26

No files matched your search

+41 -10
View File
@@ -16,19 +16,19 @@ pub struct DiscogsClient {
}
/// Search result from Discogs API
#[derive(Debug, Deserialize)]
struct SearchResponse {
results: Vec<SearchResult>,
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
pub struct SearchResponse {
pub results: Vec<SearchResult>,
}
#[derive(Debug, Deserialize)]
struct SearchResult {
id: u64,
cover_image: Option<String>,
thumb: Option<String>,
title: String,
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
pub struct SearchResult {
pub id: u64,
pub cover_image: Option<String>,
pub thumb: Option<String>,
pub title: String,
#[serde(rename = "type")]
result_type: String,
pub result_type: String,
}
// Compile-time embedded credentials (from build environment)
@@ -154,6 +154,37 @@ impl DiscogsClient {
None
}
/// Search for artists and return search results
pub async fn search_artist(&self, query: &str) -> Result<SearchResponse, String> {
if !self.has_credentials() {
return Err("Discogs credentials not configured".to_string());
}
let key = self.consumer_key.as_ref().unwrap();
let secret = self.consumer_secret.as_ref().unwrap();
let url = format!(
"https://api.discogs.com/database/search?q={}&type=artist&key={}&secret={}",
urlencoding::encode(query),
key,
secret
);
log::debug!("Searching Discogs for artist: {}", query);
let response = self.client.get(&url).send().await
.map_err(|e| format!("Failed to search Discogs: {}", e))?;
if !response.status().is_success() {
return Err(format!("Discogs search failed with status: {}", response.status()));
}
let search: SearchResponse = response.json().await
.map_err(|e| format!("Failed to parse Discogs response: {}", e))?;
Ok(search)
}
/// Download an image to the cache directory
async fn download_image(&self, url: &str, path: &Path) -> Option<()> {
log::debug!("Downloading Discogs artwork: {}", url);
+1
View File
@@ -383,6 +383,7 @@ pub fn run() {
library::commands::playlist_increment_play_count,
// Discogs artwork commands
library::commands::discogs_has_credentials,
library::commands::discogs_search_artist,
library::commands::library_fetch_missing_artwork,
library::commands::library_fetch_album_artwork,
library::commands::library_set_album_artwork,
+23
View File
@@ -821,6 +821,29 @@ pub async fn library_set_album_artwork(
Ok(cached_path)
}
/// Search for artists on Discogs
#[tauri::command]
pub async fn discogs_search_artist(
query: String,
api_keys: State<'_, ApiKeysState>,
) -> Result<crate::discogs::SearchResponse, String> {
log::info!("Command: discogs_search_artist query={}", query);
// Get user-provided credentials if available
let keys = api_keys.lock().await;
let discogs = DiscogsClient::with_user_credentials(
keys.discogs.client_id.clone(),
keys.discogs.client_secret.clone(),
);
drop(keys);
if !discogs.has_credentials() {
return Err("Discogs credentials not configured".to_string());
}
discogs.search_artist(&query).await
}
// === Album Settings ===
#[tauri::command]
@@ -268,11 +268,12 @@
loading = true;
try {
artists = await invoke<LocalArtist[]>('library_get_artists');
// Fetch Qobuz artist images in background (best-effort) if enabled
// Load cached artist images from database
await loadCachedArtistImages();
// Fetch missing images in background if enabled
const fetchEnabled = localStorage.getItem('qbz-fetch-artist-images') !== 'false';
if (fetchEnabled) {
const artistNames = artists.map(a => a.name);
fetchArtistImages(artistNames);
fetchMissingArtistImages();
}
} catch (err) {
console.error('Failed to load artists:', err);
@@ -933,14 +934,41 @@
}
/**
* Fetch artist images from Qobuz for local artists.
* Does a best-effort match and caches images by artist name.
* Load cached artist images from database.
*/
async function fetchArtistImages(artistNames: string[]): Promise<void> {
async function loadCachedArtistImages(): Promise<void> {
try {
const artistNames = artists.map(a => a.name);
const cachedImages = await invoke<Array<{
artist_name: string;
image_url: string | null;
source: string | null;
custom_image_path: string | null;
}>>('library_get_artist_images', { artistNames });
for (const cached of cachedImages) {
const imageUrl = cached.custom_image_path
? convertFileSrc(cached.custom_image_path)
: cached.image_url;
if (imageUrl) {
artistImages.set(cached.artist_name, imageUrl);
}
}
// Trigger re-render
artistImages = new Map(artistImages);
} catch (err) {
console.debug('Failed to load cached artist images:', err);
}
}
/**
* Fetch missing artist images from Qobuz and Discogs (fallback).
*/
async function fetchMissingArtistImages(): Promise<void> {
// Filter out artists we already have images for and "Various Artists"
const toFetch = artistNames.filter(name => {
const normalized = normalizeArtistName(name);
return normalized !== 'various artists' && !artistImages.has(name);
const toFetch = artists.filter(artist => {
const normalized = normalizeArtistName(artist.name);
return normalized !== 'various artists' && !artistImages.has(artist.name);
});
if (toFetch.length === 0) return;
@@ -949,29 +977,60 @@
const batchSize = 10;
for (let i = 0; i < toFetch.length; i += batchSize) {
const batch = toFetch.slice(i, i + batchSize);
const promises = batch.map(async (name) => {
const promises = batch.map(async (artist) => {
const name = artist.name;
try {
// Try Qobuz first
const results = await invoke<SearchResults<ArtistSearchResult>>('search_artists', {
query: name.trim(),
limit: 3,
offset: 0
});
if (!results.items.length) return;
if (results.items.length > 0) {
const normalizedQuery = normalizeArtistName(name);
const exactMatch = results.items.find(
artist => normalizeArtistName(artist.name) === normalizedQuery
item => normalizeArtistName(item.name) === normalizedQuery
);
const match = exactMatch ?? results.items[0];
// Get the best available image
const imageUrl = match.image?.large || match.image?.thumbnail || match.image?.small;
if (imageUrl) {
// Cache in database
await invoke('library_cache_artist_image', {
artistName: name,
imageUrl,
source: 'qobuz'
});
artistImages.set(name, imageUrl);
return;
}
}
// Fallback to Discogs if Qobuz failed and Discogs is available
if (hasDiscogsCredentials) {
try {
const discogsResults = await invoke<any>('discogs_search_artist', {
query: name.trim()
});
if (discogsResults && discogsResults.results && discogsResults.results.length > 0) {
const imageUrl = discogsResults.results[0].thumb || discogsResults.results[0].cover_image;
if (imageUrl && !imageUrl.includes('spacer.gif')) {
// Cache in database
await invoke('library_cache_artist_image', {
artistName: name,
imageUrl,
source: 'discogs'
});
artistImages.set(name, imageUrl);
}
}
} catch (discogsErr) {
console.debug('Discogs fallback failed for artist:', name, discogsErr);
}
}
} catch (err) {
// Silently fail for individual artists - it's best-effort
console.debug('Failed to fetch image for artist:', name, err);
}
});
@@ -982,6 +1041,14 @@
}
}
/**
* Legacy function - kept for compatibility but now calls new implementation.
* @deprecated Use fetchMissingArtistImages() instead
*/
async function fetchArtistImages(artistNames: string[]): Promise<void> {
await fetchMissingArtistImages();
}
function handleLocalAlbumLink(track: LocalTrack) {
if (!track.album_group_key) return;
const album = albums.find(item => item.id === track.album_group_key);