-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeezer.rs
More file actions
1296 lines (1200 loc) Β· 49.6 KB
/
Copy pathdeezer.rs
File metadata and controls
1296 lines (1200 loc) Β· 49.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Tauri commands for Deezer metadata enrichment.
//!
//! Each command follows a **cache-first** strategy:
//! 1. Check if the local entity already has a `deezer_id`.
//! 2. If yes, check the `deezer_*` cache table for a non-expired entry.
//! 3. If the cache is valid, return it immediately (and resolve the local
//! artwork path from the stored hash so the UI can render offline).
//! 4. Otherwise, search or fetch from the Deezer public API, download the
//! artwork into the shared `metadata_artwork/` directory, upsert the cache
//! row (with the hash) and link the `deezer_id` on the local entity.
//!
//! On any network error the command returns an **empty enrichment** (all
//! fields `None`) rather than propagating an error β the frontend can
//! display local data without interruption.
use std::path::Path;
use chrono::Utc;
use serde::Serialize;
use sqlx::SqlitePool;
use tauri::{AppHandle, Emitter};
use waveflow_core::metadata::{
deezer::{is_placeholder_artist_picture, DeezerClient},
lastfm::LastfmClient,
name_match::{normalize_name, select_by_name},
theaudiodb::{make_summary, TheAudioDbClient},
};
// Shared with the scanner: takes a connection so the caller controls
// the transaction (see CLAUDE.md, "Single writer to SQLite"). This
// module used to carry a pool-taking copy of it, which is what kept
// these paths non-transactional.
use waveflow_core::scanner::upsert_artwork;
use crate::{
commands::integration::{read_bio_language, read_bio_source, read_lastfm_api_key, BioSource},
error::{AppError, AppResult},
metadata_artwork,
state::AppState,
};
/// TTL for cached Deezer entries: 30 days in milliseconds.
const CACHE_TTL_MS: i64 = 30 * 24 * 60 * 60 * 1000;
fn now_ms() -> i64 {
Utc::now().timestamp_millis()
}
// ββ Album enrichment ββββββββββββββββββββββββββββββββββββββββββββββββ
#[derive(Debug, Clone, Serialize)]
pub struct DeezerAlbumEnrichment {
pub deezer_id: Option<i64>,
pub label: Option<String>,
pub release_date: Option<String>,
/// Remote Deezer CDN URL β kept as a fallback for the (rare) case where
/// the local download failed. Frontend should prefer `cover_path`.
pub cover_url: Option<String>,
/// Absolute filesystem path to the locally-cached cover, or `None` if
/// the download has not happened yet (or failed).
pub cover_path: Option<String>,
pub cover_path_1x: Option<String>,
pub cover_path_2x: Option<String>,
}
impl DeezerAlbumEnrichment {
fn empty() -> Self {
Self {
deezer_id: None,
label: None,
release_date: None,
cover_url: None,
cover_path: None,
cover_path_1x: None,
cover_path_2x: None,
}
}
}
#[tauri::command]
pub async fn enrich_album_deezer(
state: tauri::State<'_, AppState>,
album_id: i64,
) -> AppResult<DeezerAlbumEnrichment> {
let pool = state.require_profile_pool().await?;
let artwork_dir = state.paths.metadata_artwork_dir.clone();
enrich_album_inner(&pool, &artwork_dir, album_id).await
}
/// Whether a fresh cached `metadata_album` row is a usable hit **for the needs
/// of the album being enriched**. A row with no `cover_hash` still counts as
/// complete when the local album has its own artwork (it will never need the
/// Deezer cover). But for an art-less album a cover-less row is *incomplete* β
/// it must trigger a re-fetch instead of serving a permanent miss. Without this
/// the #493 download-skip would poison the shared cache: a fresh cover-less row
/// (art removed, a different profile sharing the cache, or a prior failed
/// download) would block the cover from ever being fetched until the TTL lapsed.
fn metadata_album_cache_complete(cover_hash: Option<&str>, has_local_art: bool) -> bool {
cover_hash.is_some() || has_local_art
}
pub(crate) async fn enrich_album_inner(
pool: &SqlitePool,
artwork_dir: &Path,
album_id: i64,
) -> AppResult<DeezerAlbumEnrichment> {
let now = now_ms();
// 1. Read the local album + its existing deezer_id + whether it already
// has local artwork (issue #493 β see the cover-download guard below).
let local: Option<(String, Option<String>, Option<i64>, Option<i64>)> = sqlx::query_as(
"SELECT al.title, ar.name, al.deezer_id, al.artwork_id
FROM album al LEFT JOIN artist ar ON ar.id = al.artist_id
WHERE al.id = ?",
)
.bind(album_id)
.fetch_optional(pool)
.await?;
let Some((album_title, artist_name, existing_deezer_id, local_artwork_id)) = local else {
return Ok(DeezerAlbumEnrichment::empty());
};
// 2. Cache hit?
if let Some(did) = existing_deezer_id {
let cached: Option<(
Option<String>,
Option<String>,
Option<String>,
Option<String>,
i64,
)> = sqlx::query_as(
"SELECT label, release_date, cover_url, cover_hash, expires_at
FROM app.metadata_album WHERE deezer_id = ?",
)
.bind(did)
.fetch_optional(pool)
.await?;
if let Some((label, release_date, cover_url, cover_hash, expires_at)) = cached {
// A fresh row is a usable hit only when it's also complete for this
// album's needs β otherwise a cover-less row for an art-less album
// would block a re-fetch until the TTL lapsed (issue #493).
let usable = expires_at > now
&& metadata_album_cache_complete(cover_hash.as_deref(), local_artwork_id.is_some());
if usable {
let cover_path = cover_hash
.as_deref()
.and_then(|h| metadata_artwork::existing_path(artwork_dir, h));
let (cover_path_1x, cover_path_2x) = match cover_hash.as_deref() {
Some(h) => crate::thumbnails::thumbnail_paths_for(artwork_dir, h),
None => (None, None),
};
return Ok(DeezerAlbumEnrichment {
deezer_id: Some(did),
label,
release_date,
cover_url,
cover_path,
cover_path_1x,
cover_path_2x,
});
}
}
}
// 3. Fetch from Deezer API β short-circuit when offline mode is
// on. Returns whatever Deezer-id we already had (so the UI can
// still resolve cached artwork) plus empty enrichment fields.
if crate::offline::is_offline() {
return Ok(DeezerAlbumEnrichment {
deezer_id: existing_deezer_id,
..DeezerAlbumEnrichment::empty()
});
}
let client = DeezerClient::new();
let hit = if let Some(did) = existing_deezer_id {
match client.get_album(did).await {
Ok(h) => Some(h),
Err(err) => {
tracing::warn!(?err, "Deezer get_album failed");
return Ok(DeezerAlbumEnrichment {
deezer_id: Some(did),
..DeezerAlbumEnrichment::empty()
});
}
}
} else {
let query = match artist_name.as_deref() {
Some(artist) => format!("{album_title} {artist}"),
None => album_title.clone(),
};
match client.search_album(&query).await {
Ok(hits) => hits.into_iter().next(),
Err(err) => {
tracing::warn!(?err, "Deezer search_album failed");
return Ok(DeezerAlbumEnrichment::empty());
}
}
};
let Some(hit) = hit else {
return Ok(DeezerAlbumEnrichment::empty());
};
let cover_url = hit.cover_xl.clone().or_else(|| hit.cover_big.clone());
// 4. Download artwork into the shared cache (best-effort) β but ONLY for an
// album that has NO local cover of its own (issue #493). This function is
// fired automatically every time an album page opens (which only reads
// `label` + `release_date`) and by the Discord presence (which reads the
// remote `cover_url`); neither uses the downloaded file, and the album
// grid / detail header render the LOCAL artwork. Without this guard the
// shared `metadata_artwork` cache filled up with Deezer covers for albums
// the user already has artwork for β never displayed. The deliberate
// paths still work: `batch_fetch_missing_album_covers` only iterates
// `artwork_id IS NULL` albums, and a genuinely cover-less album still
// gets its fallback. `cover_url` always rides through for Discord + the
// cache row regardless.
let cover_hash = match (local_artwork_id.is_none(), cover_url.as_deref()) {
(true, Some(url)) => metadata_artwork::download_and_cache(url, artwork_dir).await,
_ => None,
};
let cover_path = cover_hash
.as_deref()
.and_then(|h| metadata_artwork::existing_path(artwork_dir, h));
let (cover_path_1x, cover_path_2x) = match cover_hash.as_deref() {
Some(h) => crate::thumbnails::thumbnail_paths_for(artwork_dir, h),
None => (None, None),
};
// 5. Upsert into cache (now stores the hash too).
let expires = now + CACHE_TTL_MS;
sqlx::query(
"INSERT INTO app.metadata_album
(deezer_id, title, release_date, cover_url, cover_hash, label, fetched_at, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(deezer_id) DO UPDATE SET
title = excluded.title,
release_date = excluded.release_date,
cover_url = excluded.cover_url,
-- Only overwrite the cached hash on a NEW successful download.
-- `excluded.cover_hash` is NULL when the download was skipped
-- (art-having album, #493) or failed transiently β in both cases
-- keep whatever cover was already cached rather than dropping a good
-- one over a network blip. The #493 cleanup is what deliberately
-- clears art-having albums' covers, not this best-effort upsert.
cover_hash = COALESCE(excluded.cover_hash, cover_hash),
label = excluded.label,
fetched_at = excluded.fetched_at,
expires_at = excluded.expires_at",
)
.bind(hit.id)
.bind(&hit.title)
.bind(hit.release_date.as_deref())
.bind(cover_url.as_deref())
.bind(cover_hash.as_deref())
.bind(hit.label.as_deref())
.bind(now)
.bind(expires)
.execute(pool)
.await?;
// 6. Link deezer_id on the local album.
if existing_deezer_id.is_none() {
sqlx::query("UPDATE album SET deezer_id = ? WHERE id = ?")
.bind(hit.id)
.bind(album_id)
.execute(pool)
.await?;
}
Ok(DeezerAlbumEnrichment {
deezer_id: Some(hit.id),
label: hit.label,
release_date: hit.release_date,
cover_url,
cover_path,
cover_path_1x,
cover_path_2x,
})
}
// ββ Artist enrichment βββββββββββββββββββββββββββββββββββββββββββββββ
#[derive(Debug, Clone, Serialize)]
pub struct DeezerArtistEnrichment {
pub deezer_id: Option<i64>,
/// Remote Deezer CDN URL β fallback when the local download failed.
pub picture_url: Option<String>,
/// Absolute filesystem path to the locally-cached picture.
pub picture_path: Option<String>,
pub picture_path_1x: Option<String>,
pub picture_path_2x: Option<String>,
pub fans_count: Option<i64>,
/// Short biography from Last.fm (if an API key is configured and
/// the artist matches). HTML stripped.
pub bio_short: Option<String>,
/// Full biography from Last.fm. HTML stripped.
pub bio_full: Option<String>,
/// Remote TheAudioDB URL of the wide artist fanart (issue #482) β
/// fallback when the local download failed.
pub background_url: Option<String>,
/// Absolute filesystem path to the locally-cached fanart. Feeds the
/// artist hero; `None` means the artist has no wide image and the
/// frontend falls back to blurring the square photo.
pub background_path: Option<String>,
}
impl DeezerArtistEnrichment {
fn empty() -> Self {
Self {
deezer_id: None,
picture_url: None,
picture_path: None,
picture_path_1x: None,
picture_path_2x: None,
fans_count: None,
bio_short: None,
bio_full: None,
background_url: None,
background_path: None,
}
}
}
#[tauri::command]
pub async fn enrich_artist_deezer(
state: tauri::State<'_, AppState>,
artist_id: i64,
) -> AppResult<DeezerArtistEnrichment> {
let pool = state.require_profile_pool().await?;
enrich_artist_deezer_with_pool(state, &pool, artist_id).await
}
/// Enrich an artist by **name**, for a remote artist (RFC-005) that has no
/// local row β the remote artist view and the "About the artist" panel use
/// it to show the Deezer photo, the TheAudioDB hero background and the
/// Last.fm bio the server itself does not carry. Same shared cache and
/// offline behaviour as [`enrich_artist_deezer`]; there's just no local
/// artist to link the resolved deezer_id back to.
#[tauri::command]
pub async fn enrich_artist_by_name(
state: tauri::State<'_, AppState>,
name: String,
) -> AppResult<DeezerArtistEnrichment> {
let name = name.trim().to_string();
if name.is_empty() {
return Ok(DeezerArtistEnrichment::empty());
}
let pool = state.require_profile_pool().await?;
// Reuse a previously-resolved Deezer id for this name so the None path
// doesn't re-hit the network on every remote track change / view open.
//
// A bounded, case-insensitive exact match evaluated inside SQLite β
// rather than loading the whole cache into Rust to fuzzy-match every
// row β catches the common same-name/different-case hit. A diacritic-
// only variant ("Beyonce" vs a cached "BeyoncΓ©") misses here and falls
// through to a fresh fetch, which does the accent-insensitive match
// against Deezer's own results and then caches it for next time.
let cached_deezer_id: Option<i64> = match sqlx::query_scalar::<_, i64>(
"SELECT deezer_id FROM app.metadata_artist
WHERE deezer_id IS NOT NULL AND name = ? COLLATE NOCASE
ORDER BY fetched_at DESC LIMIT 1",
)
.bind(&name)
.fetch_optional(&*pool)
.await
{
Ok(id) => id,
Err(err) => {
// A lookup failure is not fatal β fall through to a fresh fetch
// β but it is distinct from a clean cache miss, so log it.
tracing::debug!(%err, artist = %name, "cached deezer id lookup failed");
None
}
};
enrich_artist_named(state, (*pool).clone(), name, cached_deezer_id).await
}
/// Enrichment body, pinned to a caller-supplied pool.
///
/// Split out of [`enrich_artist_deezer`] so the batch path can enrich a
/// whole artist list against the pool it read that list from. Going
/// through the command wrapper instead would re-resolve the active
/// profile once per artist, and a `switch_profile` mid-batch would then
/// write the remaining artists into the *new* profile.
async fn enrich_artist_deezer_with_pool(
state: tauri::State<'_, AppState>,
pool: &sqlx::SqlitePool,
artist_id: i64,
) -> AppResult<DeezerArtistEnrichment> {
// Per-profile bio override (issue #323) wins over any fetched bio
// and works offline. We still let the inner path fetch + cache the
// online bio (keeping the shared cross-profile `metadata_artist`
// cache correct for profiles WITHOUT an override) and just swap the
// returned bio here. Offline mode short-circuits before the network
// inside, so the override is the only bio offline users ever see.
let custom_bio: Option<String> =
sqlx::query_scalar("SELECT custom_bio FROM artist WHERE id = ?")
.bind(artist_id)
.fetch_optional(pool)
.await?
.flatten()
.map(|b: String| b.trim().to_string())
.filter(|b| !b.is_empty());
// Pass the SAME pool into the inner so the custom_bio lookup and the
// enrichment stay scoped to one profile β re-resolving inside could
// straddle a switch_profile and apply one profile's override to
// another's artist.
let mut enrichment = enrich_artist_deezer_inner(state, pool.clone(), artist_id).await?;
if let Some(bio) = custom_bio {
// Synthesize a truncated lead-in the same way the online sources
// do (issue #343) β without it bio_short == bio_full verbatim and
// the frontend's length-based "Read more" toggle never appears.
enrichment.bio_short = Some(make_summary(&bio));
enrichment.bio_full = Some(bio);
}
Ok(enrichment)
}
async fn enrich_artist_deezer_inner(
state: tauri::State<'_, AppState>,
pool: sqlx::SqlitePool,
artist_id: i64,
) -> AppResult<DeezerArtistEnrichment> {
// 1. Read local artist.
let local: Option<(String, Option<i64>)> =
sqlx::query_as("SELECT name, deezer_id FROM artist WHERE id = ?")
.bind(artist_id)
.fetch_optional(&pool)
.await?;
let Some((artist_name, existing_deezer_id)) = local else {
return Ok(DeezerArtistEnrichment::empty());
};
let enrichment =
enrich_artist_named(state, pool.clone(), artist_name, existing_deezer_id).await?;
// 8. Link the discovered deezer_id back onto the local artist, so the
// next pass hits the cache by id instead of re-searching by name.
if existing_deezer_id.is_none() {
if let Some(did) = enrichment.deezer_id {
sqlx::query("UPDATE artist SET deezer_id = ? WHERE id = ?")
.bind(did)
.bind(artist_id)
.execute(&pool)
.await?;
}
}
Ok(enrichment)
}
/// Enrichment core keyed on an artist **name** rather than a local row.
///
/// A remote artist (RFC-005) has no local id, so this is what gives its
/// view the same Deezer photo, TheAudioDB hero background and Last.fm bio
/// as a library artist. Pass a known `deezer_id` to reuse the shared
/// `app.metadata_artist` cache; `None` searches Deezer by name. The result
/// is cached by the resolved deezer_id either way β the caller links it to
/// a local row when there is one.
async fn enrich_artist_named(
state: tauri::State<'_, AppState>,
pool: sqlx::SqlitePool,
artist_name: String,
existing_deezer_id: Option<i64>,
) -> AppResult<DeezerArtistEnrichment> {
let artwork_dir = state.paths.metadata_artwork_dir.clone();
let now = now_ms();
// Active bio provider + language (issue #295). Read up-front so the
// cache check can invalidate a bio fetched under a different source
// / language even when the rest of the row is still fresh.
let active_source = read_bio_source(&state).await?;
let active_lang = read_bio_language(&state).await?;
// 2. Cache hit? (includes bio fields populated in a previous pass)
if let Some(did) = existing_deezer_id {
#[allow(clippy::type_complexity)]
let cached: Option<(
Option<String>,
Option<String>,
Option<i64>,
Option<String>,
Option<String>,
Option<String>,
Option<String>,
Option<String>,
Option<String>,
Option<i64>,
i64,
)> = sqlx::query_as(
"SELECT picture_url, picture_hash, fans_count, bio_short, bio_full,
bio_source, bio_language,
background_url, background_hash, background_fetched_at, expires_at
FROM app.metadata_artist WHERE deezer_id = ?",
)
.bind(did)
.fetch_optional(&pool)
.await?;
if let Some((
picture_url,
picture_hash,
fans_count,
bio_short,
bio_full,
cached_bio_source,
cached_bio_language,
background_url,
background_hash,
background_fetched_at,
expires_at,
)) = cached
{
// The bio part is only reusable when it was fetched under the
// currently-selected source (and language, for TheAudioDB);
// otherwise we fall through and re-fetch it.
let bio_fresh = BioSource::parse(cached_bio_source.as_deref()) == active_source
&& (active_source != BioSource::TheAudioDb
|| cached_bio_language.as_deref() == Some(active_lang.as_str()));
// A row written before issue #482 never looked for fanart β
// `background_fetched_at IS NULL` is the marker, and a NULL
// hash alone can't say it apart from "looked, found nothing".
// Falling through backfills it once, then this stays true
// for the rest of the row's TTL.
let background_fresh = background_fetched_at.is_some();
if expires_at > now && bio_fresh && background_fresh {
// A row cached before #406 may hold a Deezer placeholder
// URL (and a grey-blob hash). Drop both so we surface the
// initial-letter avatar instead of the grey box; the row's
// own TTL refresh re-fetches through `best_picture`, and a
// placeholder means the artist has no real Deezer photo to
// heal to anyway.
let placeholder = picture_url
.as_deref()
.is_some_and(is_placeholder_artist_picture);
let (picture_url, picture_hash) = if placeholder {
(None, None)
} else {
(picture_url, picture_hash)
};
let picture_path = picture_hash
.as_deref()
.and_then(|h| metadata_artwork::existing_path(&artwork_dir, h));
let (picture_path_1x, picture_path_2x) = match picture_hash.as_deref() {
Some(h) => crate::thumbnails::thumbnail_paths_for(&artwork_dir, h),
None => (None, None),
};
let background_path = background_hash
.as_deref()
.and_then(|h| metadata_artwork::existing_path(&artwork_dir, h));
return Ok(DeezerArtistEnrichment {
deezer_id: Some(did),
picture_url,
picture_path,
picture_path_1x,
picture_path_2x,
fans_count,
bio_short,
bio_full,
background_url,
background_path,
});
}
}
}
// 3. Fetch from Deezer (picture + fans). Short-circuit when
// offline mode is on so we don't poke the network for stale
// cache entries.
if crate::offline::is_offline() {
return Ok(DeezerArtistEnrichment {
deezer_id: existing_deezer_id,
..DeezerArtistEnrichment::empty()
});
}
let client = DeezerClient::new();
let hit = if let Some(did) = existing_deezer_id {
match client.get_artist(did).await {
Ok(h) => Some(h),
Err(err) => {
tracing::warn!(?err, "Deezer get_artist failed");
return Ok(DeezerArtistEnrichment {
deezer_id: Some(did),
..DeezerArtistEnrichment::empty()
});
}
}
} else {
match client.search_artist(&artist_name).await {
Ok(hits) => {
// Share TheAudioDB's fuzzy matcher (#342): Deezer's search
// is accent-insensitive too, so an exact-equality filter
// dropped the picture/cover for "Celine Dion" β "CΓ©line
// Dion" and superset names like "Bob Marley & The Wailers".
select_by_name(hits, &normalize_name(&artist_name), |h| {
Some(h.name.as_str())
})
}
Err(err) => {
tracing::warn!(?err, "Deezer search_artist failed");
return Ok(DeezerArtistEnrichment::empty());
}
}
};
let Some(hit) = hit else {
return Ok(DeezerArtistEnrichment::empty());
};
// 4. TheAudioDB lookup β one call, two consumers. The wide fanart
// backing the artist hero (issue #482) is fetched whatever the
// selected bio source is: Last.fm has no equivalent image, so
// gating this on `bio_source` would leave every Last.fm user
// with no hero at all. The bio half of the same response is only
// used when TheAudioDB IS the selected source β one request
// instead of two, which matters on their rate-limited free key.
let audiodb_result = TheAudioDbClient::new()
.artist_info(&artist_name, &active_lang)
.await;
// A *reached* API β match or not β is what licenses stamping
// `background_fetched_at` below. A transport error leaves it NULL so
// the next visit retries instead of caching a network blip as "this
// artist has no fanart" for the whole 30-day TTL.
let audiodb_reached = audiodb_result.is_ok();
let audiodb = match audiodb_result {
Ok(info) => info,
Err(err) => {
tracing::warn!(?err, "TheAudioDB artist_info failed");
None
}
};
// 5. Fetch the bio from the selected source (issue #295). Network
// failures and missing matches are non-fatal β we still persist
// the Deezer portion so the next refresh doesn't spam the
// network. The source/language we used is stored alongside so a
// later switch re-fetches instead of serving the wrong bio.
let (bio_short, bio_full) = match active_source {
BioSource::Lastfm => match read_lastfm_api_key(&state).await? {
Some(api_key) => {
let lastfm = LastfmClient::new();
match lastfm.artist_get_info(&artist_name, &api_key).await {
Ok(Some(info)) => (info.bio_summary, info.bio_full),
Ok(None) => (None, None),
Err(err) => {
tracing::warn!(?err, "Last.fm artist_get_info failed");
(None, None)
}
}
}
None => (None, None),
},
BioSource::TheAudioDb => match audiodb.as_ref() {
Some(info) => (info.bio_short.clone(), info.bio_full.clone()),
None => (None, None),
},
};
let picture_url = hit.best_picture();
let background_url = audiodb.and_then(|info| info.fanart_url);
// 6. Download artwork into the shared cache (best-effort).
let picture_hash = match picture_url.as_deref() {
Some(url) => metadata_artwork::download_and_cache(url, &artwork_dir).await,
None => None,
};
let picture_path = picture_hash
.as_deref()
.and_then(|h| metadata_artwork::existing_path(&artwork_dir, h));
let (picture_path_1x, picture_path_2x) = match picture_hash.as_deref() {
Some(h) => crate::thumbnails::thumbnail_paths_for(&artwork_dir, h),
None => (None, None),
};
// The hero paints the fanart full-bleed behind the header, so it's
// the one image we deliberately keep at full resolution β hence the
// `_full_res` variant, which skips the `_1x` / `_2x` thumbnail job:
// downscaling would only soften the crop, and nothing reads the tiers.
let background_hash = match background_url.as_deref() {
Some(url) => metadata_artwork::download_and_cache_full_res(url, &artwork_dir).await,
None => None,
};
let background_path = background_hash
.as_deref()
.and_then(|h| metadata_artwork::existing_path(&artwork_dir, h));
// 7. Upsert into the metadata cache (Deezer + bio fields land in the
// unified `metadata_artist` table in app.db so every profile
// shares the same cache). `bio_source` / `bio_language` record
// which provider produced the bio so a later switch invalidates
// it (see the cache-hit check above). Language is only meaningful
// for TheAudioDB, so Last.fm stores NULL.
let expires = now + CACHE_TTL_MS;
let stored_lang: Option<&str> =
matches!(active_source, BioSource::TheAudioDb).then_some(active_lang.as_str());
sqlx::query(
"INSERT INTO app.metadata_artist
(deezer_id, name, picture_url, picture_hash, fans_count, bio_short, bio_full,
bio_source, bio_language, background_url, background_hash, background_fetched_at,
fetched_at, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(deezer_id) DO UPDATE SET
name = excluded.name,
picture_url = excluded.picture_url,
picture_hash = excluded.picture_hash,
fans_count = excluded.fans_count,
bio_short = excluded.bio_short,
bio_full = excluded.bio_full,
bio_source = excluded.bio_source,
bio_language = excluded.bio_language,
background_url = excluded.background_url,
background_hash = excluded.background_hash,
background_fetched_at = excluded.background_fetched_at,
fetched_at = excluded.fetched_at,
expires_at = excluded.expires_at",
)
.bind(hit.id)
.bind(&hit.name)
.bind(picture_url.as_deref())
.bind(picture_hash.as_deref())
.bind(hit.nb_fan)
.bind(bio_short.as_deref())
.bind(bio_full.as_deref())
.bind(active_source.as_str())
.bind(stored_lang)
.bind(background_url.as_deref())
.bind(background_hash.as_deref())
// Stamped even when the lookup came back empty β that's the whole
// point of the column: "we asked, TheAudioDB has nothing". Left NULL
// when the API couldn't be reached at all, so that retries.
.bind(audiodb_reached.then_some(now))
.bind(now)
.bind(expires)
.execute(&pool)
.await?;
Ok(DeezerArtistEnrichment {
deezer_id: Some(hit.id),
picture_url,
picture_path,
picture_path_1x,
picture_path_2x,
fans_count: hit.nb_fan,
bio_short,
bio_full,
background_url,
background_path,
})
}
// ββ Cover management ββββββββββββββββββββββββββββββββββββββββββββββββ
#[derive(Debug, Clone, Serialize)]
pub struct DeezerAlbumLite {
pub deezer_id: i64,
pub title: String,
pub artist: String,
pub cover_url: Option<String>,
}
#[tauri::command]
pub async fn search_albums_deezer(query: String) -> AppResult<Vec<DeezerAlbumLite>> {
if crate::offline::is_offline() {
return Ok(Vec::new());
}
let client = DeezerClient::new();
let hits = client
.search_album(&query)
.await
.map_err(|err| AppError::Other(format!("deezer search failed: {err}")))?;
let lite: Vec<DeezerAlbumLite> = hits
.into_iter()
.take(20)
.map(|h| DeezerAlbumLite {
deezer_id: h.id,
title: h.title,
artist: h.artist.map(|a| a.name).unwrap_or_default(),
cover_url: h.cover_xl.or(h.cover_medium),
})
.collect();
Ok(lite)
}
#[tauri::command]
pub async fn set_album_artwork_from_deezer(
state: tauri::State<'_, AppState>,
album_id: i64,
deezer_album_id: i64,
) -> AppResult<()> {
if crate::offline::is_offline() {
return Err(AppError::Other("offline mode is enabled".into()));
}
let pool = state.require_profile_pool().await?;
let profile_id = state.require_profile_id().await?;
let profile_artwork_dir = state.paths.profile_artwork_dir(profile_id);
std::fs::create_dir_all(&profile_artwork_dir)?;
let client = DeezerClient::new();
let hit = client
.get_album(deezer_album_id)
.await
.map_err(|err| AppError::Other(format!("deezer get_album failed: {err}")))?;
let cover_url = hit
.cover_xl
.clone()
.or_else(|| hit.cover_big.clone())
.or_else(|| hit.cover_medium.clone())
.ok_or_else(|| AppError::Other("deezer album has no cover".into()))?;
let bytes = download_image_bytes(&cover_url).await?;
let hash = blake3::hash(&bytes).to_hex().to_string();
let format = "jpg";
let target = profile_artwork_dir.join(format!("{hash}.{format}"));
if !target.exists() {
std::fs::write(&target, &bytes)?;
}
crate::thumbnails::spawn_thumbnail_job(target, profile_artwork_dir.clone(), hash.clone());
// One transaction so the artwork row and the album link land
// together β see `upsert_artwork`'s contract in CLAUDE.md.
let mut tx = pool.begin().await?;
let artwork_id = upsert_artwork(&mut tx, &hash, format, "deezer").await?;
let res =
sqlx::query("UPDATE album SET artwork_id = ?, artwork_source = 'deezer' WHERE id = ?")
.bind(artwork_id)
.bind(album_id)
.execute(&mut *tx)
.await?;
// Matching no row means the album is gone (stale UI, concurrent
// delete). Returning early leaves `tx` un-committed, so the artwork
// insert rolls back instead of landing with nothing pointing at it β
// and the caller hears about it rather than getting a silent success.
if res.rows_affected() == 0 {
return Err(AppError::Other(format!("album {album_id} not found")));
}
tx.commit().await?;
Ok(())
}
#[tauri::command]
pub async fn set_album_artwork_from_file(
state: tauri::State<'_, AppState>,
album_id: i64,
file_path: String,
) -> AppResult<()> {
let pool = state.require_profile_pool().await?;
let profile_id = state.require_profile_id().await?;
let profile_artwork_dir = state.paths.profile_artwork_dir(profile_id);
std::fs::create_dir_all(&profile_artwork_dir)?;
let bytes = std::fs::read(&file_path)?;
let format = detect_image_format(&bytes).ok_or_else(|| {
AppError::Other("unsupported image format (expected jpg/png/webp)".into())
})?;
let hash = blake3::hash(&bytes).to_hex().to_string();
let target = profile_artwork_dir.join(format!("{hash}.{format}"));
if !target.exists() {
std::fs::write(&target, &bytes)?;
}
crate::thumbnails::spawn_thumbnail_job(target, profile_artwork_dir.clone(), hash.clone());
// One transaction so the artwork row and the album link land
// together β see `upsert_artwork`'s contract in CLAUDE.md.
let mut tx = pool.begin().await?;
let artwork_id = upsert_artwork(&mut tx, &hash, format, "manual").await?;
let res =
sqlx::query("UPDATE album SET artwork_id = ?, artwork_source = 'manual' WHERE id = ?")
.bind(artwork_id)
.bind(album_id)
.execute(&mut *tx)
.await?;
// Matching no row means the album is gone (stale UI, concurrent
// delete). Returning early leaves `tx` un-committed, so the artwork
// insert rolls back instead of landing with nothing pointing at it β
// and the caller hears about it rather than getting a silent success.
if res.rows_affected() == 0 {
return Err(AppError::Other(format!("album {album_id} not found")));
}
tx.commit().await?;
Ok(())
}
// ββ Web Radio now-playing artwork βββββββββββββββββββββββββββββββββββ
/// Resolve cover art for a now-playing Web Radio song. The ICY
/// `StreamTitle` only gives us "Artist - Title" text, so we search
/// Deezer for the track and return its album cover URL. Unlike the
/// library enrichment paths this does NOT cache to disk β a radio
/// now-playing line is ephemeral (changes every song, no library row to
/// link), so a remote CDN URL the `<img>` loads directly is enough.
///
/// Returns `None` when offline, on a network error, or when nothing
/// matched β the frontend keeps the station favicon in that case.
#[tauri::command]
pub async fn fetch_radio_artwork(artist: String, title: String) -> AppResult<Option<String>> {
if crate::offline::is_offline() {
return Ok(None);
}
let query = format!("{artist} {title}");
let client = DeezerClient::new();
let hits = match client.search_track(&query).await {
Ok(hits) => hits,
Err(err) => {
tracing::warn!(?err, "Deezer search_track failed");
return Ok(None);
}
};
// First hit with an album cover wins β Deezer's relevance ranking
// already orders the best match first.
let cover = hits.into_iter().find_map(|h| {
h.album
.and_then(|a| a.cover_xl.or(a.cover_big).or(a.cover_medium))
});
Ok(cover)
}
// ββ Artist image management βββββββββββββββββββββββββββββββββββββββββ
#[derive(Debug, Clone, Serialize)]
pub struct DeezerArtistLite {
pub deezer_id: i64,
pub name: String,
pub picture_url: Option<String>,
pub nb_fan: Option<i64>,
}
/// Search Deezer artists for the artist-image picker. Capped to 20 hits
/// to keep the UI grid readable.
#[tauri::command]
pub async fn search_artists_deezer(query: String) -> AppResult<Vec<DeezerArtistLite>> {
if crate::offline::is_offline() {
return Ok(Vec::new());
}
let client = DeezerClient::new();
let hits = client
.search_artist(&query)
.await
.map_err(|err| AppError::Other(format!("deezer artist search failed: {err}")))?;
Ok(hits
.into_iter()
.take(20)
.map(|h| {
// Skip Deezer's empty-hash placeholder (#406) β borrow before
// `h.name` moves into the struct.
let picture_url = h.best_picture();
DeezerArtistLite {
deezer_id: h.id,
name: h.name,
picture_url,
nb_fan: h.nb_fan,
}
})
.collect())
}
/// Link a specific Deezer artist photo (by Deezer ID) to a local
/// `artist` row. Downloads the picture into the profile artwork cache
/// and overwrites `artist.artwork_id` unconditionally β explicit user
/// pick, so we override any existing image (local sidecar, prior fetch).
#[tauri::command]
pub async fn set_artist_artwork_from_deezer(
state: tauri::State<'_, AppState>,
artist_id: i64,
deezer_artist_id: i64,
) -> AppResult<()> {
if crate::offline::is_offline() {
return Err(AppError::Other("offline mode is enabled".into()));
}
let pool = state.require_profile_pool().await?;
let profile_id = state.require_profile_id().await?;
let profile_artwork_dir = state.paths.profile_artwork_dir(profile_id);
std::fs::create_dir_all(&profile_artwork_dir)?;
let client = DeezerClient::new();
let hit = client
.get_artist(deezer_artist_id)
.await
.map_err(|err| AppError::Other(format!("deezer get_artist failed: {err}")))?;
let picture_url = hit
.best_picture()
.ok_or_else(|| AppError::Other("deezer artist has no picture".into()))?;
let bytes = download_image_bytes(&picture_url).await?;
let hash = blake3::hash(&bytes).to_hex().to_string();
let format = "jpg";
let target = profile_artwork_dir.join(format!("{hash}.{format}"));
if !target.exists() {
std::fs::write(&target, &bytes)?;
}
crate::thumbnails::spawn_thumbnail_job(target, profile_artwork_dir.clone(), hash.clone());