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:
1 parent
a5200d5d05
commit
dd1df5bfee
4 files changed
+148
-26
No files matched your search
@@ -16,19 +16,19 @@ pub struct DiscogsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Search result from Discogs API
|
/// Search result from Discogs API
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
|
||||||
struct SearchResponse {
|
pub struct SearchResponse {
|
||||||
results: Vec<SearchResult>,
|
pub results: Vec<SearchResult>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
|
||||||
struct SearchResult {
|
pub struct SearchResult {
|
||||||
id: u64,
|
pub id: u64,
|
||||||
cover_image: Option<String>,
|
pub cover_image: Option<String>,
|
||||||
thumb: Option<String>,
|
pub thumb: Option<String>,
|
||||||
title: String,
|
pub title: String,
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type")]
|
||||||
result_type: String,
|
pub result_type: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compile-time embedded credentials (from build environment)
|
// Compile-time embedded credentials (from build environment)
|
||||||
@@ -154,6 +154,37 @@ impl DiscogsClient {
|
|||||||
None
|
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
|
/// Download an image to the cache directory
|
||||||
async fn download_image(&self, url: &str, path: &Path) -> Option<()> {
|
async fn download_image(&self, url: &str, path: &Path) -> Option<()> {
|
||||||
log::debug!("Downloading Discogs artwork: {}", url);
|
log::debug!("Downloading Discogs artwork: {}", url);
|
||||||
|
|||||||
@@ -383,6 +383,7 @@ pub fn run() {
|
|||||||
library::commands::playlist_increment_play_count,
|
library::commands::playlist_increment_play_count,
|
||||||
// Discogs artwork commands
|
// Discogs artwork commands
|
||||||
library::commands::discogs_has_credentials,
|
library::commands::discogs_has_credentials,
|
||||||
|
library::commands::discogs_search_artist,
|
||||||
library::commands::library_fetch_missing_artwork,
|
library::commands::library_fetch_missing_artwork,
|
||||||
library::commands::library_fetch_album_artwork,
|
library::commands::library_fetch_album_artwork,
|
||||||
library::commands::library_set_album_artwork,
|
library::commands::library_set_album_artwork,
|
||||||
|
|||||||
@@ -821,6 +821,29 @@ pub async fn library_set_album_artwork(
|
|||||||
Ok(cached_path)
|
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 ===
|
// === Album Settings ===
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
|||||||
@@ -268,11 +268,12 @@
|
|||||||
loading = true;
|
loading = true;
|
||||||
try {
|
try {
|
||||||
artists = await invoke<LocalArtist[]>('library_get_artists');
|
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';
|
const fetchEnabled = localStorage.getItem('qbz-fetch-artist-images') !== 'false';
|
||||||
if (fetchEnabled) {
|
if (fetchEnabled) {
|
||||||
const artistNames = artists.map(a => a.name);
|
fetchMissingArtistImages();
|
||||||
fetchArtistImages(artistNames);
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to load artists:', err);
|
console.error('Failed to load artists:', err);
|
||||||
@@ -933,14 +934,41 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch artist images from Qobuz for local artists.
|
* Load cached artist images from database.
|
||||||
* Does a best-effort match and caches images by artist name.
|
|
||||||
*/
|
*/
|
||||||
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"
|
// Filter out artists we already have images for and "Various Artists"
|
||||||
const toFetch = artistNames.filter(name => {
|
const toFetch = artists.filter(artist => {
|
||||||
const normalized = normalizeArtistName(name);
|
const normalized = normalizeArtistName(artist.name);
|
||||||
return normalized !== 'various artists' && !artistImages.has(name);
|
return normalized !== 'various artists' && !artistImages.has(artist.name);
|
||||||
});
|
});
|
||||||
|
|
||||||
if (toFetch.length === 0) return;
|
if (toFetch.length === 0) return;
|
||||||
@@ -949,29 +977,60 @@
|
|||||||
const batchSize = 10;
|
const batchSize = 10;
|
||||||
for (let i = 0; i < toFetch.length; i += batchSize) {
|
for (let i = 0; i < toFetch.length; i += batchSize) {
|
||||||
const batch = toFetch.slice(i, 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 {
|
||||||
|
// Try Qobuz first
|
||||||
const results = await invoke<SearchResults<ArtistSearchResult>>('search_artists', {
|
const results = await invoke<SearchResults<ArtistSearchResult>>('search_artists', {
|
||||||
query: name.trim(),
|
query: name.trim(),
|
||||||
limit: 3,
|
limit: 3,
|
||||||
offset: 0
|
offset: 0
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!results.items.length) return;
|
if (results.items.length > 0) {
|
||||||
|
|
||||||
const normalizedQuery = normalizeArtistName(name);
|
const normalizedQuery = normalizeArtistName(name);
|
||||||
const exactMatch = results.items.find(
|
const exactMatch = results.items.find(
|
||||||
artist => normalizeArtistName(artist.name) === normalizedQuery
|
item => normalizeArtistName(item.name) === normalizedQuery
|
||||||
);
|
);
|
||||||
const match = exactMatch ?? results.items[0];
|
const match = exactMatch ?? results.items[0];
|
||||||
|
|
||||||
// Get the best available image
|
|
||||||
const imageUrl = match.image?.large || match.image?.thumbnail || match.image?.small;
|
const imageUrl = match.image?.large || match.image?.thumbnail || match.image?.small;
|
||||||
|
|
||||||
if (imageUrl) {
|
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);
|
artistImages.set(name, imageUrl);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
} catch (discogsErr) {
|
||||||
|
console.debug('Discogs fallback failed for artist:', name, discogsErr);
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Silently fail for individual artists - it's best-effort
|
|
||||||
console.debug('Failed to fetch image for artist:', name, err);
|
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) {
|
function handleLocalAlbumLink(track: LocalTrack) {
|
||||||
if (!track.album_group_key) return;
|
if (!track.album_group_key) return;
|
||||||
const album = albums.find(item => item.id === track.album_group_key);
|
const album = albums.find(item => item.id === track.album_group_key);
|
||||||
|
|||||||
Reference in new issue
Block a user