Commit Graph
708 Commits
Author SHA1 Message Date
yonlu 91214f9d54 fix: stop invalidating discography cache after every library scan
Root cause: OnAllScansComplete called InvalidateIndexDiscographies()
which deleted the discog_built timestamp. SoftScanAllLibraries
triggers a scan whenever file counts differ (even by 1 file), so
on most launches the hook fired and wiped the cache.

The invalidation was unnecessary — Tiers 2-4 are already incremental.
filterUnindexed skips artists that are already indexed, so new
library artists with freshly-populated MBIDs get picked up naturally
without forcing a full rebuild.

InvalidateIndexDiscographies is kept as a public API for manual
rebuild (future UI button) but no longer called automatically.

Combined with per-tier timestamps from the previous commit, the
index build now correctly skips completed tiers on restart.
2026-03-29 12:58:05 -04:00
yonlu e6692e9f1b fix: index build restarts from scratch every launch
Root cause: discog_built meta timestamp was only written after ALL
of Tiers 2-4 completed. If the app was closed mid-build (context
cancelled), the timestamp was never set, so the next launch re-ran
everything from Tier 2.

Fix: track each tier independently with tier2_built, tier3_built,
tier4_built timestamps. Each tier's timestamp is written immediately
after it completes, so progress survives app restarts.

On next launch, already-completed tiers are skipped. Combined with
the incremental filterUnindexed logic, a build interrupted at
Tier 4 with 80% of similar artists done will resume from the
remaining 20%.

Also adds getLibraryArtistMBIDs helper for Tier 4 when Tier 3
was skipped (needs library MBIDs without re-running Tier 3).

InvalidateDiscographies now clears all three per-tier timestamps.
2026-03-29 12:55:07 -04:00
yonlu 5bb1c89fba perf: optimize index build — permanent caches + faster MB rate limit
Three changes to reduce subsequent index build times:

1. Positive image/rels cache TTL: 30 days → 365 days
   Artist url-rels and resolved image URLs rarely change.
   Already-indexed artists make zero API calls on rebuild.

2. Negative cache (misses) stays at 30 days so new images
   are discovered within a month of being added upstream.

3. MB rate limiter for background indexing: 1.0 → 1.5 req/s
   url-rels lookups are lightweight; 1.5/s is well within
   what MB handles (Picard and Kodi both use similar rates).
   Cuts the MB-bound portion of index build by ~33%.

Also adds NewRateLimiterF for fractional rates and caches
MB rels fetch failures (30-day miss TTL) to avoid retrying
unreachable artists every build.
2026-03-29 12:00:36 -04:00
yonlu b251982e73 feat: add TheAudioDB as artist image source
TheAudioDB (theaudiodb.com) added as source #1, between fanart.tv
and Wikimedia. Uses free public API key (2) with MBID-based lookup
so matching is guaranteed — no name-based search ambiguity.

Fetches up to 4 images per artist: thumb (portrait), fanart1-3
(wider shots). Results cached 30 days in explore_cache.

Source priority order is now:
0. fanart.tv artistthumb
1. TheAudioDB thumb + fanart
2. MusicBrainz direct image rels (Wikimedia Commons)
3. Wikidata P18 (Wikimedia Commons)
4. Wikipedia lead image
2026-03-29 11:49:27 -04:00
yonlu 8eef182fe1 fix: .env loading syntax for /bin/sh compatibility
Use if/then/fi instead of && chain for POSIX sh compatibility.
Use ./.env (explicit relative path) instead of .env.
2026-03-29 10:54:11 -04:00
yonlu 51a2ebbfd8 chore: auto-load .env in make dev/dev-debug
Source .env file (if present) before launching wails dev so
FANART_TV_API_KEY and other env vars are available without
manual sourcing.
2026-03-29 10:23:09 -04:00
yonlu 37392e0a46 feat: add fanart.tv as artist image source (highest priority)
Fanart.tv artistthumb images are now the primary source for artist
photos. Up to 5 thumbnails fetched per artist (sorted by community
likes). Falls through to Wikimedia/Wikidata/Wikipedia if fanart.tv
has no images for the artist.

API key handling per fanart.tv project key terms:
- Project key loaded from FANART_TV_API_KEY env var (or build-time
  ldflags via fanartTVProjectKey variable)
- Users can provide their own personal key via FANART_TV_PERSONAL_KEY
  env var for higher rate limits (sent as client_key parameter)
- Results cached 30 days in explore_cache
- No bulk downloading — only fetched per-artist during index build

Source priority order:
1. fanart.tv artistthumb (best quality, community-curated)
2. MusicBrainz direct image rels (Wikimedia Commons)
3. Wikidata P18 (Wikimedia Commons)
4. Wikipedia lead image

Attribution: fanart.tv images are CC-BY-SA, contributed by the
fanart.tv community (https://fanart.tv).
2026-03-29 10:18:09 -04:00
yonlu 19a803d1fc feat: multi-source artist images with thumbnails + grid integration
Complete rewrite of the artist image pipeline:

STORAGE:
- Migration 16: artist_images table tracking source, URL, path,
  primary flag, dimensions per image (up to 10 per artist)
- Directory structure: artist-images/{mbid[:2]}/{mbid}/ with
  primary.jpg + primary_sm.jpg/_md.jpg/_lg.jpg thumbnails
- Miss marker (.miss file) prevents re-fetching artists with no image

SOURCES (priority order):
1. MusicBrainz direct image relations (Wikimedia Commons)
2. Wikidata P18 property (Wikimedia Commons)
3. Wikipedia lead image (NEW — via Wikidata sitelinks → Wikipedia API)

Each source is checked, deduplicated, and the first available
image becomes the primary with sm/md/lg thumbnail generation
(100px/200px/400px, matching cover art tier sizes).

ASSET SERVING:
- /artist-images/ path registered with Wails asset handler
- Serves files via http.FileServer from the artist-images directory
- Same pattern as /covers/ for cover art

ARTIST MODEL:
- Artist struct gains ImageSmall/ImageMedium/ImageLarge fields
- resolveArtistImages does bulk MBID lookup → disk stat for each
- Populated in GetAllArtists and GetAllArtistsByLibrary

GRID VIEW:
- artists-view uses model URLs directly (no more base64 data URLs)
- Size selection based on imageSize * devicePixelRatio (like cover-grid)
- Removed batch GetArtistImages call and in-memory cache — no longer needed
2026-03-29 08:33:32 -04:00
yonlu 7ec9785463 perf: batch artist image loading for library grid view
Replace per-artist sequential GetArtistMBID + GetArtistImageURL
calls (2 Wails round-trips × N artists) with a single batch
GetArtistImages(names[]) call that:

1. Resolves all names → MBIDs via AllArtistMBIDs() (one DB query)
2. Checks disk cache for each MBID via GetCachedImage (no network)
3. Returns map[name]→dataURL in one Wails bridge round-trip

Only returns already-cached images from the disk cache populated
by the index build. No network fetches triggered — artists whose
images haven't been cached yet keep the initial letter fallback
until the index build resolves them in the background.

Result: all cached artist images appear simultaneously on first
render instead of loading one-by-one over several seconds.
2026-03-28 15:22:22 -04:00
yonlu df1d1785e9 feat: artist images in library artists grid view
The local artists grid now shows Wikimedia artist photos in the
circular avatars. Each visible artist card triggers an async load:
GetArtistMBID(name) → GetArtistImageURL(mbid) → cached data URL.

Images load progressively — the initial letter placeholder shows
immediately, replaced by the photo when it resolves. Results are
cached in-memory per session. Artists without MBIDs or without
Wikimedia photos keep the initial letter fallback.

Uses the same disk-cached artist image pipeline as the explore
views — no extra network requests for previously resolved artists.
2026-03-28 13:50:24 -04:00
yonlu 7f0c6d362a feat: personalized search ranking — library > similar > neither
Migration 15: add in_library and is_similar INTEGER columns to
explore_index. Backfills in_library from existing library MBIDs.

Search index FTS5 query now includes personalization in scoring:
  ORDER BY bm25(...) - (ln(pop+1) * 1.5)
           - (in_library * 3.0) - (is_similar * 1.5)

For equal text+popularity scores:
  - Library artist beats unrelated by 3.0 points
  - Similar artist beats unrelated by 1.5 points
  - Library > Similar > Neither

Tier 3 (library) entries get in_library=1 via markInLibrary.
Tier 4 (similar) entries get is_similar=1 via markSimilar.

MB result reranking (boostWithIndexPopularity) adds a 10M
popularity bonus for library artists, ensuring they always
rank above non-library artists with equal text relevance.
2026-03-28 12:50:57 -04:00
yonlu 15a0b94348 fix: invalidate index discographies after library rescan
The search index's Tier 3 (library artists) depends on MBIDs from
the artists table. If the index built before a rescan populated
those MBIDs, library artists like Flatbush Zombies wouldn't be
indexed — they're not in the sitewide top 1000 and their name
didn't match via fuzzy matching.

Fix: OnAllScansComplete hook now calls InvalidateIndexDiscographies
before StartIndexBuild. This clears the discog_built timestamp so
Tiers 2-4 re-run incrementally, picking up any new library artists
whose MBIDs were just populated by the scan.

The rebuild is incremental — only artists not already in the index
get their discographies fetched.
2026-03-28 12:40:23 -04:00
yonlu 48a8713091 refactor: remove Top Results section from explore search
Remove the mixed Top Results section that showed a blend of artists
and recordings. Search results now show three clean categories:
Artists, Albums, Tracks — each sorted by their own scoring.

Removed: ScoredItem interface, TOP_RESULTS_COUNT, getTopResults,
renderTopResults, renderTopCard, and .top-card CSS.
2026-03-28 12:34:40 -04:00
yonlu 6820e781e7 feat: rerank MB results with index popularity, increase popularity weight
Two changes:

1. Rerank MB results using index popularity (no API calls):
   When the index is ready, boostWithIndexPopularity looks up each
   MB result's MBID in the local index to get cached listen counts,
   then reranks using the same blended score formula. This was
   previously skipped entirely for speed, leaving MB results sorted
   by text relevance only — obscure exact matches beat popular
   partial matches.

2. Increase popularity weight across both scoring systems:
   - Blended score: 60% popularity / 40% relevance (was 40/60)
   - FTS5 index: ln(pop+1) * 1.5 factor (was 0.5)

   Result: 'flatbush' → Flatbush Zombies (97) beats 'Flatbush'
   nobody (61). Popular artists with partial name matches now
   reliably outrank obscure exact matches.
2026-03-28 12:25:29 -04:00
yonlu acb84660f0 fix: drain scan queue after FullRescan's direct scanInternal call
FullRescan calls scanInternal directly (not via startScan) to get
ScanMetrics back. But startScan is what calls drainQueue when it
finishes. Without drainQueue, any libraries queued via ScanLibrary
sat in the queue forever — scanActive remained true, the queued
library never scanned.

Fix: call drainQueue in a goroutine after queuing the remaining
libraries. This processes the queue sequentially and eventually
sets scanActive=false + fires OnAllScansComplete.
2026-03-28 10:32:34 -04:00
yonlu 3c3102aac6 fix: start index build only after ALL library scans complete
FullRescan scans the first library directly, then queues the rest.
The PostScan hook was restarting the index build after the FIRST
library, which starved the queued libraries for DB access — they
never scanned, leaving the library with only 6 tracks.

Fix: move StartIndexBuild to the OnAllScansComplete hook, which
fires when drainQueue finds no more libraries to scan. This ensures
ALL libraries finish scanning before the index build starts.

For startup soft scans: if no scans were queued (library unchanged),
start the index build directly. If scans WERE queued, the hook
handles it.

Added OnAllScansComplete callback to ScanHooks. Called from
drainQueue when the scan pipeline goes idle.
2026-03-28 10:25:04 -04:00
yonlu 9a841cd173 feat: MusicBrainz verification badge + MBID links in track details
Track details dialog now shows:

1. Green checkmark badge next to the track title when the recording
   has a MusicBrainz ID (hover: 'Metadata verified by MusicBrainz')

2. MusicBrainz section at the bottom with clickable MBID links for:
   - Recording (track) → musicbrainz.org/recording/{mbid}
   - Release Group (album) → musicbrainz.org/release-group/{mbid}
   - Artist → musicbrainz.org/artist/{mbid}

   Links open in the system browser. Only shown for entities that
   have MBIDs from audio file tags.

Backend: GetTrackMBIDs(filePath) Wails binding queries recording,
release_group, and artist mbid columns via a single JOIN query.
Frontend: loaded async when the dialog opens, non-blocking.
2026-03-28 10:11:52 -04:00
yonlu 54b074eae7 feat: artist aliases in FTS5 index + BM25 blended scoring
Migration 14: add aliases TEXT column to explore_index, rebuild FTS5
with 3 columns (title, artist_name, aliases), recreate sync triggers.
Clears index build timestamps to force alias population on next build.

Artist image provider fetches inc=url-rels+aliases (single call, no
extra cost). GetAliases() extracts alias names from cached MB rels.
indexOneArtist stores aliases as space-separated text after image
resolution populates the cache.

Search query now uses BM25 blended scoring:
  ORDER BY bm25(fts, 3.0, 1.0, 0.5) - (ln(popularity+1) * 0.5)

Column weights: title=3.0, artist_name=1.0, aliases=0.5
- Title matches score 3x higher than artist name matches
- Alias matches are helpful but don't dominate
- Popularity is a log-scaled boost, not an override
- Exact title match on niche entity beats weak match on mega-popular

Enables: 'rhcp' → Red Hot Chili Peppers, 'gnr' → Guns N' Roses,
'sabbath' → Black Sabbath (once index build runs with aliases).
2026-03-28 09:46:54 -04:00
yonlu bb015092d4 fix: prevent search index build from starving library scan for DB access
The search index build and library scan both write to the same
single-connection SQLite DB. The index build runs continuous batch
transactions that can starve the scan's clearLibraryTables call,
causing the scan to silently hang without logging.

Fix: decouple index build from SetContext. The build now starts
AFTER the soft scan completes on startup. For full rescans, the
PreClear hook stops the index build, and PostScan restarts it.

Also made StartBuild/StopBuild safe for multiple calls:
- StartBuild is a no-op if already running
- StopBuild is a no-op if not running (no deadlock on done channel)
- done channel created per-build, not in constructor
2026-03-26 15:21:01 -04:00
yonlu 71516df651 fix: strip null bytes from ID3v2 TXXX/UFID tag values
The dhowden/tag library's Comm.Text and UFID.Identifier fields
include trailing null bytes from the C-style strings in the ID3v2
binary format. strings.TrimSpace doesn't strip \x00, so MBIDs
stored from MP3 files had invisible null bytes appended.

This caused WHERE mbid = ? queries to fail — the stored value
'uuid\x00' didn't match the clean 'uuid' from search results.
FLAC files (Vorbis comments with plain strings) were unaffected.

Fix: use strings.TrimRight with explicit \x00 in the cutset.
Requires a full rescan to fix existing corrupted MBIDs.
2026-03-26 15:05:13 -04:00
yonlu 1797eef844 feat: 'In Library' badges on explore artist detail page
Add CheckLibraryMBIDs call after artist data loads. Checks all
release group MBIDs from the discography against the local library.
Matching albums show a green 'In Library' badge in the album meta
section alongside the year.

Fires after Promise.allSettled completes (same timing as artist
image fetch). Non-blocking — badge appears on re-render when the
check completes.
2026-03-26 12:10:26 -04:00
yonlu de51a62677 fix: handle ID3v2 TXXX frames and UFID in MBID extraction
The dhowden/tag library returns ID3v2 TXXX frames as *tag.Comm
structs (key='TXXX_N', Description='MusicBrainz Artist Id',
Text='uuid'), not plain strings. Vorbis comments are plain strings
(key='musicbrainz_artistid', value='uuid').

Previous code only handled the string case — all MP3 files silently
got empty MBIDs. Now handles three value types:
- string: Vorbis comments (FLAC/OGG) — key is the tag name
- *tag.Comm: ID3v2 TXXX frames (MP3) — Description is the tag name
- *tag.UFID: ID3v2 UFID frame (MP3) — MusicBrainz recording ID

Requires a full rescan to backfill MBIDs for MP3 files.
2026-03-26 11:04:44 -04:00
yonlu ad6104132d fix: use transaction for MBID updates to prevent SQLite deadlock
updateMBIDs was calling l.db.ExecContext (main connection) while
inside a transaction that held the write lock. With SQLite's
SetMaxOpenConns(1), this deadlocked — the UPDATE waited for the
transaction to release the lock, but the transaction waited for
the UPDATE to complete.

Fix: pass *sql.Tx through processMetadata to updateMBIDs and use
tx.ExecContext instead. All MBID writes now happen within the same
transaction as the entity upserts.
2026-03-26 09:52:38 -04:00
yonlu 8f6a4c6a8e feat: 'In Library' badges, artist images on local pages, MBID-based Tier 3
Three features wired together:

1. 'In Library' badges on explore search results:
   CheckLibraryMBIDs Wails binding batch-checks which search result
   MBIDs exist in the local library. Green badges render on matching
   artist cards and album cards.

2. Artist images on local artist-details page:
   Local artist pages now call GetArtistMBID(name) to resolve the
   MBID from tags, then GetArtistImageURL(mbid) to fetch the cached
   Wikimedia photo. Falls back to initial-letter avatar.

3. Tier 3 search index uses direct MBIDs from tags:
   buildTier3Library now reads artists.mbid column (from audio tags)
   for direct MBID matching, falling back to name matching for
   untagged artists. Eliminates false matches and catches artists
   that name matching misses.
2026-03-26 09:34:57 -04:00
yonlu b941057a46 feat: extract MusicBrainz IDs from audio tags and store in library DB
Migration 13 adds nullable mbid TEXT columns to artists,
release_groups, and recordings with partial indexes.

Metadata extraction (tags.go) now reads MusicBrainz IDs from Raw()
tags — handles both Vorbis (musicbrainz_artistid) and ID3v2
(MusicBrainz Artist Id) key formats.

Scan pipeline (library.go) updates MBIDs after entity upsert via
raw SQL UPDATE. Only sets mbid if currently NULL (preserves existing
values on rescan).

LibraryMBIDIndex (librarymbid.go) provides:
- CheckMBIDs: batch lookup for 'In Library' badges
- GetArtistMBID: single artist name→MBID lookup
- AllArtistMBIDs: full dump for search index Tier 3

MBIDs will be populated on next library rescan. Existing files
need a rescan to backfill.
2026-03-26 09:24:39 -04:00
yonlu 806de8fd45 feat: migration 13 — add MBID columns to artists, release_groups, recordings
Add nullable TEXT mbid column to artists, release_groups, and
recordings tables. Partial indexes on each (WHERE mbid IS NOT NULL)
for fast MBID lookups without bloating the index for rows without
MBIDs.

Enables linking local library entities to MusicBrainz/ListenBrainz
explore data, artist image sharing, and 'In Library' badges.
2026-03-26 09:17:55 -04:00
yonlu c9b3c86f37 perf: unified per-artist indexing — discography + image in parallel
Restructure indexOneArtist to run LB discography fetches and MB
artist image resolution concurrently. They use different rate
limiters (LB: 3 req/s, MB: 1 req/s) so they overlap without
contention.

Per artist, the indexer now runs two parallel pipelines:
  LB pipeline: top-release-groups + top-recordings
  MB pipeline: url-rels → Wikidata P18 → Wikimedia image fetch

All artist images are pre-cached during the index build instead
of being resolved on-demand during search. Total build time
drops from ~105 min (sequential) to ~63 min (parallel, MB-bound).

SearchIndex now takes ArtistImageProvider as a dependency. The
Service constructor creates artistImg before the index so both
can share it.
2026-03-26 08:54:43 -04:00
yonlu 963269b753 feat: artist image disk cache + fix top results artist photos
Two changes:

1. Artist image disk cache: ArtistImageProvider now fetches the
   actual image bytes from Wikimedia Commons and caches them on
   disk (~/.local/share/yellowjacket/artist-image-cache/{mbid}.jpg).
   Returns base64 data URLs, same pattern as CoverArtProxy.
   First lookup: resolve URL via MB/Wikidata + fetch image (~2s).
   Subsequent: instant from disk cache.
   404s cached as empty files to avoid re-fetching.

2. Top results artist photos: the Top Results section now shows
   artist images from the artistImageCache, same as the Artists
   section. Also shows englishName in the top card display name.
2026-03-25 22:28:52 -04:00
yonlu 9b88b88523 fix: rate-limit MB url-rels fetches, serialize frontend image loads
Artist image resolution was hitting musicbrainz.org with 10
concurrent unthrottled requests per search — enough to trigger
MB's rate limit rejection. Two fixes:

Backend: add dedicated 1 req/s RateLimiter for MB url-rels fetches
in ArtistImageProvider. Each fetch waits on the limiter before
the HTTP call. Results are cached 30 days so repeat lookups are
instant.

Frontend: switch loadArtistImages from concurrent fire-all to
sequential await loop. Each artist image loads one at a time,
images appear progressively as they resolve instead of all
failing from rate limit rejection.
2026-03-25 22:19:18 -04:00
yonlu 104e469774 fix: simplify artist image provider, remove unnecessary LookupArtist call
The previous implementation called LookupArtist (rate-limited MB API)
before fetching url-rels, wasting a rate limiter slot. The fetchURL
for rels also bypassed the MB rate limiter, risking 503 rejections.

Rewrite: fetch MB url-rels once (direct HTTP, cached 30 days), parse
both image and wikidata relations from the same response, resolve
Wikimedia thumb URL. No dependency on MusicBrainzClient — just the
Cache for storage and a plain http.Client.

Also cleared 34 stale cached empty results from previous failed
resolution attempts that were blocking image lookup.
2026-03-25 20:13:23 -04:00
yonlu 55473dd52a feat: artist images from MusicBrainz/Wikidata/Wikimedia Commons
Add ArtistImageProvider that resolves artist MBIDs to photo URLs:
1. MB url-rels 'image' type → extract Commons filename → thumb URL
2. MB url-rels 'wikidata' type → Wikidata P18 property → thumb URL
3. No image → falls back to initial-letter avatar

Wikimedia Commons thumb URLs constructed via MD5 hash bucketing
(standard Commons URL scheme). Results cached in explore_cache
with 30-day TTL — subsequent lookups are instant.

Frontend: search results and artist detail page show artist photos
in the circular avatar when available. Images load async and
replace the initial-letter fallback on arrival. Artist detail page
fires the image fetch alongside the other 4 parallel data loads.

Architecture supports adding more sources (fanart.tv, etc.) by
extending the resolve() method's source chain.
2026-03-25 19:55:10 -04:00
yonlu 0e376abfbb perf: batch thumbnail loading — one Wails call for all album art
Replace per-card GetThumbnail calls (10 round-trips) with a single
GetThumbnails batch call that fetches all visible album thumbnails
in one Wails bridge round-trip.

Backend GetThumbnails accepts []ThumbnailRequest and returns
map[mbid]→dataURL. Each request still checks library → disk cache
→ CAA in order, but the bridge overhead is 1 call instead of 10.

Frontend fires loadThumbnails() once after search results arrive.
Album cards render immediately with CAA URL fallback, then re-render
once the batch resolves with cached/local data URLs.
2026-03-25 19:37:46 -04:00
yonlu 0761cff408 feat: use local library cover art for search results
CoverArtProxy now checks three sources in order:
1. Local library (instant) — matches by album+artist name against
   the release_groups/cover_art tables. Albums the user already
   owns show their local cover art immediately.
2. Disk cache (instant) — previously fetched CAA thumbnails.
3. Cover Art Archive (network) — fetches and caches to disk.

Library index is built once on first access (sync.Once) from a
single SQL query joining release_groups → cover_art → artists.
Keyed by lowercased 'album\x00artist' for exact name matching.

GetThumbnail now takes (mbid, albumName, artistName) so the proxy
can check the library before falling back to CAA. Frontend passes
the album title and artist credit from the search result.
2026-03-25 19:00:29 -04:00
yonlu d5f34f242f fix: don't cache transient cover art failures as permanent misses
The CAA proxy was caching all fetch failures (including 503s and
timeouts) as empty files, treating them as permanent 'no art' misses.
During Internet Archive outages, this meant every album got cached
as having no cover art, and the cache persisted after IA recovered.

Now only 404 responses (no cover art exists) are cached as permanent
misses. 503, timeouts, and other transient errors are not cached,
so the next request retries the fetch.

Also cleared 33 incorrectly cached 0-byte miss files from a
concurrent IA outage.
2026-03-25 14:14:30 -04:00
yonlu 49a26c6163 feat: cover art proxy with disk cache for instant thumbnail loading
Add CoverArtProxy that fetches cover art from CAA, caches the image
bytes on disk (~/.local/share/yellowjacket/cover-art-cache/), and
returns base64 data URLs via the GetThumbnail Wails binding.

First load: fetches from CAA (rate-limited), caches to disk.
Subsequent loads: instant from disk cache, no network.
404s: cached as empty files to avoid re-fetching.

Frontend explore-view loads thumbnails async via GetThumbnail()
calls that fire during render. Cached thumbnails appear as data
URLs directly in img src, bypassing the browser's HTTP stack.
Uncached thumbnails fall back to the CAA URL while the proxy
fetches in the background, then re-render with the cached version.

Also stores caa_id and caa_release_mbid in the search index's
extra_json for future direct Internet Archive URL construction.
2026-03-25 14:09:30 -04:00
yonlu 1141febf29 perf: skip live LB popularity + cross-reference when index is ready
Phases 2 (3 LB popularity POST calls) and 3 (3 MB discography
browse calls) were adding ~3-6 seconds to every search through
rate-limited API calls. Now they only run as a fallback during
first launch before the search index is built.

Once the index is ready (after Tier 1, <5 seconds from startup):
  Phase 0: local FTS5 index query (instant)
  Phase 1: MB search (3 concurrent calls, ~1s)
  Phase 4: merge index hits (instant)
  Phase 5: filter and cap (instant)

Search drops from ~4-7s to ~1s. The index already carries
popularity data and covers discography cross-referencing,
making the live API calls redundant.
2026-03-25 13:55:26 -04:00
yonlu e4f4639ab7 feat: per-tier refresh intervals with incremental discography builds
Replace the single 7-day full rebuild with per-tier scheduling:

- Tier 1 (sitewide top lists): weekly refresh, 12 API calls
- Tiers 2-4 (discographies): monthly refresh, incremental —
  only fetches discographies for artists not already indexed

On subsequent runs:
- If T1 is fresh, load cached artists from the index (~0 calls)
- If discographies are fresh, skip Tiers 2-4 entirely (~0 calls)
- If discographies are stale, diff against indexed set and only
  fetch new artists that appeared in the sitewide lists

Add helpers: isMetaFresh (per-key freshness check),
loadCachedSitewideArtists (read artists from existing index),
filterUnindexed (diff artist list against indexed set).

After first build: typical startup is <5s (T1 cache load).
Monthly incremental: ~50-100 calls for newly appeared artists.
2026-03-25 13:43:00 -04:00
yonlu 59d5b7272e feat: popularity-scaled per-artist index budgets
Instead of fixed 20 RGs + 100 recordings for every artist, scale
the budget by popularity using a power curve (exponent 0.3):

  Radiohead (2.5M listens): 20 RGs, 100 recordings
  Hans Zimmer (715K):       15 RGs, 71 recordings
  Clutch (178K):            11 RGs, 50 recordings
  Similar (~10K):            7 RGs, 27 recordings
  Organic (unknown):         5 RGs, 10 recordings

Saves ~53% index size (~29 MB vs ~62 MB) with identical API calls.
The savings come from T4 similar artists (long tail) where full
discographies were wasteful. Top artists still get full coverage.
2026-03-25 13:11:15 -04:00
yonlu 48acede1bc feat: 5-tier search index with library + similar artist expansion
Rewrite SearchIndex with tiered background build:

Tier 1 — Sitewide instant (<5s, 12 calls): top artists, recordings,
  and release groups across 4 time ranges. Searchable immediately.

Tier 2 — Sitewide full discog (~16min, 2881 calls): top 20 RGs +
  top 100 recordings per sitewide artist (~1440 unique artists from
  all_time/this_year/this_month/this_week union).

Tier 3 — Library artists (~4min, 664 calls): match local library
  artist names against known MBIDs, index their full discographies.
  Catches the user's personal taste that sitewide misses.

Tier 4 — Similar artists (~24min, ~4300 calls): fetch similar
  artists from LB labs for each library artist, index their
  discographies. Fans out into the user's taste neighborhood.

Tier 5 — Organic growth (0 calls): BrowseReleaseGroups now writes
  to the search index in a background goroutine. Every artist page
  view adds that artist's discography to the index for free.

Other changes:
- indexRGsPerArtist bumped 10→20 (96% vs 88% coverage)
- indexRecsPerArtist bumped 10→100 (track-name searchability)
- indexMinPopularity = 50 (cuts noise from long tails)
- Dedicated 3 req/s rate limiter for indexer
- Labs similar-artists endpoint at labs.api.listenbrainz.org
- Each tier marks index as ready on completion so search improves
  progressively during the ~44min total build
2026-03-25 12:49:20 -04:00
yonlu cf40909313 feat: wire SearchIndex into Search() — Phase 0 index query + merge
Create SearchIndex in NewExploreService, start background build in
SetContext (on app startup). Search() now has 6 phases:

  Phase 0: query local FTS5 index (instant, no API calls)
  Phase 1: concurrent MB search
  Phase 2: LB popularity boost
  Phase 3: cross-reference artist discographies
  Phase 4: merge index hits (prepend new entries, dedup by MBID)
  Phase 5: filter and cap

Index hits for release groups/recordings not already in MB results
are prepended so popular albums surface even when MB search can't
find them. scalePopularity() maps raw listen counts to 0-100 scores
via log scaling for compatibility with the blended score system.
2026-03-25 09:41:55 -04:00
yonlu bba4e1f3de feat: SearchIndex — background build + FTS5 query for popularity index
New SearchIndex struct in searchindex.go:
- Background build fetches top 1000 LB artists, then their top 10
  release groups and top 10 recordings (2001 API calls total)
- Dedicated 3 req/s rate limiter for indexer (LB allows 30/10s)
- Bounded concurrency (3 goroutines) with progress logging
- Batch INSERTs in transactions of 100 rows
- FTS5 query with prefix matching ('for you' → 'for* you*')
- Results sorted by popularity descending
- Skips rebuild if index is < 7 days old
- Marks index ready from existing rows if build fails
- Context cancellation for clean shutdown
2026-03-25 09:39:22 -04:00
yonlu 57a07e96cb feat: migration 12 — explore_index + FTS5 search index schema
Add explore_index table (entity_type, mbid, title, artist_name,
artist_mbid, popularity, extra_json) with a unique index on
(entity_type, mbid). FTS5 virtual table explore_index_fts backed
by the content table with auto-sync triggers for insert/update/delete.
explore_index_meta table tracks build timestamps.
2026-03-25 09:35:35 -04:00
yonlu ba6185adc3 feat: cross-reference search — match query against top artists' discographies
After MB search + popularity reranking, browse the discographies of
the top 3 artists and fuzzy-match the full query against album titles.
Matching albums not already in results are injected at the front.

Fuzzy matching uses substring containment with word-level ratio
(handles 'for you tatsuro' → 'FOR YOU' at 0.667) and word overlap
as fallback. Threshold: 0.4 ratio.

Example: 'for you tatsuro' now finds FOR YOU by 山下達郎 even though
MB text search treats 'for' and 'you' as stop words and never
returns it. The album is found via Yamashita's cached discography.
2026-03-24 22:53:47 -04:00
yonlu f2a703ed52 feat: show English alias for non-Latin script artists
Extract primary English alias from MusicBrainz artist data when the
canonical name uses non-Latin script (CJK, Cyrillic, etc.). Display
it as the primary name in search results and artist detail header,
with the native script name as a subtitle beneath.

Example: 山下達郎 now shows 'Tatsuro Yamashita' prominently with
'山下達郎' as a subtitle. Artists with Latin names are unchanged.
2026-03-24 22:47:39 -04:00
yonlu 1e95ddee68 feat: score threshold + server-side result caps
Drop artists and recordings with blended score < 25 after popularity
reranking. Cap each entity slice to 15 server-side. Request 20 from
MB to allow filtering headroom. Reduces payload size and noise.
2026-03-24 22:42:54 -04:00
yonlu 5f8f6d6a26 feat: min 2-char query gate, result caps at 10 per section
Don't fire search for single-character queries — show 'Keep typing…'
instead. Cap rendered results at 10 per section (artists, albums,
tracks) to reduce noise. Top results already capped at 3.
2026-03-24 22:41:02 -04:00
yonlu 176ac26f91 feat: popularity-boosted search reranking via ListenBrainz
After MB search returns text-relevance-scored results, fetch bulk
popularity data from ListenBrainz (POST /1/popularity/{artist,
recording,release-group}) for all result MBIDs. Blend scores:

  final = 0.6 * mb_relevance + 0.4 * log10_popularity

Log-scale normalization ensures massive artists don't drown out
everything, but popular results rise above obscure exact matches.
Release groups (no MB score) sort by raw popularity.

Three LB POST calls run concurrently — each hits a different
endpoint. All are rate-limited and cached (24h TTL).

Example: searching 'tatsuro' now ranks Tatsuro Yamashita (2.5M LB
listens, score 97) above 'tatsuro' vocaloid producer (4 listens,
score 64) despite the latter being an exact name match on MB.
2026-03-24 22:07:16 -04:00
yonlu 4ddd252e1e fix: don't double-pluralize Albums/Other Albums section headers 2026-03-24 21:43:35 -04:00
yonlu 450f6002a2 feat: split artist discography into Albums vs Other Albums
Use MusicBrainz secondaryTypes to distinguish studio albums from
compilations, soundtracks, live albums, remixes, etc. Albums with
no non-studio secondary types show under 'Albums'; everything else
under 'Other Albums'. EPs and Singles remain their own sections.

Section order: Albums → EP → Single → Other Albums → ...rest.
2026-03-24 21:40:25 -04:00
yonlu eabcf8395e fix: unmarshal LB top recordings from snake_case wire format, cap at 10
The ListenBrainz popularity API returns snake_case JSON fields
(recording_name, artist_name, total_listen_count, recording_mbid)
but LBTopRecording used camelCase JSON tags for Wails serialization.
All fields silently deserialized as zero values — empty strings and
zero counts — producing ~8000 blank rows in the top tracks section.

Fix: add lbTopRecordingWire with snake_case tags for API unmarshal,
convert to LBTopRecording (camelCase) for Wails. Cap results at 10
to avoid rendering thousands of rows for prolific artists.
2026-03-24 19:35:34 -04:00