From 56285881aacc076845df714e47562678081babff Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Mon, 30 Nov 2026 23:24:55 -0500 Subject: [PATCH] fix(coverart): album art goes to Minstrel's data folder, never beside the music (#8286) Another program files the library now. The cover enricher wrote a cover.jpg into each album folder it found art for, from the files' tags or from a provider, and an admin's cover retry deleted that file again, even if the other program had since put its own cover at that path. The enricher now keeps every cover it writes under /album-art//cover.jpg, and a retry removes a cover only from there. A cover.jpg an older build left beside the music stays, and is read as the library's own. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- cmd/minstrel/main.go | 3 +- internal/api/admin_covers_test.go | 2 +- internal/coverart/enricher.go | 89 ++++++++++++++++-------------- internal/coverart/enricher_test.go | 65 +++++++++++++++++++--- 5 files changed, 108 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index cf931a16..635c05a2 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ ListenBrainz, email, metadata sources and recommendation tuning are set in the w ## Setup pitfalls -- **The library mount has to be writable by uid 1000.** Minstrel deletes a file only when an admin asks it to, such as merging duplicates. It never moves, renames or retags your files, so a tagger or download manager can keep filing into the same folder. Mount the library `:ro` to forbid writes: those actions then refuse and say why. +- **The library mount has to be writable by uid 1000.** Minstrel deletes a file only when an admin asks it to, such as merging duplicates. It never adds, moves, renames or retags files there (album art it finds or fetches is kept in its own data folder), so a tagger or download manager can keep filing into the same folder. Mount the library `:ro` to forbid writes: those actions then refuse and say why. - **`MINSTREL_LIBRARY_SCAN_PATHS` names the path inside the container** (`/music`), not the folder on your host. - **On the internet, put it behind HTTPS.** Plain `http://` is fine on a network you trust. For a public server, bind the port to `127.0.0.1` and put a reverse proxy in front: see [docs/hosting.md](docs/hosting.md). diff --git a/cmd/minstrel/main.go b/cmd/minstrel/main.go index 8263160e..0897983d 100644 --- a/cmd/minstrel/main.go +++ b/cmd/minstrel/main.go @@ -229,8 +229,7 @@ func run() error { logger.Info("coverart: registered provider set changed; version bumped", "new_version", newVer) } - coverEnricher := coverart.NewEnricher(pool, logger.With("component", "coverart"), coverSettings) - coverEnricher.DataDir = cfg.Storage.DataDir + coverEnricher := coverart.NewEnricher(pool, logger.With("component", "coverart"), coverSettings, cfg.Storage.DataDir) // Recommendation tuning: seeds the shipped defaults on first boot and // pushes the daily-mix weights and taste config into package playlists. diff --git a/internal/api/admin_covers_test.go b/internal/api/admin_covers_test.go index c611e1e4..0abe87b7 100644 --- a/internal/api/admin_covers_test.go +++ b/internal/api/admin_covers_test.go @@ -51,7 +51,7 @@ func testHandlersWithCovers(t *testing.T) (*handlers, *coverart.Enricher) { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - enricher := coverart.NewEnricher(pool, slog.Default(), settings) + enricher := coverart.NewEnricher(pool, slog.Default(), settings, t.TempDir()) h.coverart = enricher return h, enricher } diff --git a/internal/coverart/enricher.go b/internal/coverart/enricher.go index 19621ba2..14443e69 100644 --- a/internal/coverart/enricher.go +++ b/internal/coverart/enricher.go @@ -7,6 +7,7 @@ import ( "log/slog" "os" "path/filepath" + "strings" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" @@ -16,25 +17,40 @@ import ( ) // Enricher orchestrates the sidecar → provider chain → record cycle -// for one or many albums. Owns no DB pool itself; receives one per -// call so the boot backfill, post-scan trigger, and admin endpoints -// share state. +// for one or many albums. The boot backfill, the post-scan trigger and the +// admin endpoints share one. // -// DataDir is the optional managed-cache root. When set, sidecar writes -// that fail (e.g. read-only music mount) fall back to -// /album-art//cover.jpg so enrichment isn't gated -// on the music directory being writable. Empty disables fallback; -// tests use empty since they operate on writable tempdirs. +// It reads the library and never writes to it: other programs file music +// into the library, and a cover.jpg Minstrel dropped beside their files +// is one they did not put there. Art it pulls out of a file's tags or +// fetches from a provider goes into its own cache, +// /album-art//cover.jpg. type Enricher struct { pool *pgxpool.Pool logger *slog.Logger settings *SettingsService - DataDir string + dataDir string } -// NewEnricher constructs an Enricher. -func NewEnricher(pool *pgxpool.Pool, logger *slog.Logger, settings *SettingsService) *Enricher { - return &Enricher{pool: pool, logger: logger, settings: settings} +// NewEnricher constructs an Enricher that keeps the art it writes under +// dataDir. +func NewEnricher(pool *pgxpool.Pool, logger *slog.Logger, settings *SettingsService, dataDir string) *Enricher { + return &Enricher{pool: pool, logger: logger, settings: settings, dataDir: dataDir} +} + +// artCacheRoot is where the enricher keeps the album art it writes. +func (e *Enricher) artCacheRoot() string { + return filepath.Join(e.dataDir, "album-art") +} + +// inArtCache reports whether path is a file the enricher wrote into its +// own cache. Only those are its to remove. +func (e *Enricher) inArtCache(path string) bool { + if e.dataDir == "" || path == "" { + return false + } + rel, err := filepath.Rel(e.artCacheRoot(), path) + return err == nil && rel != "." && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) } // EnrichAlbum runs the chain for a single album. @@ -97,7 +113,7 @@ func (e *Enricher) EnrichAlbum(ctx context.Context, albumID pgtype.UUID) error { if row.TrackFilePath != nil && *row.TrackFilePath != "" { body, eerr := ExtractEmbeddedAlbumArt(*row.TrackFilePath) if eerr == nil { - dest, werr := e.writeAlbumArt(albumID, *row.TrackFilePath, body) + dest, werr := e.writeAlbumArt(albumID, body) if werr != nil { e.logger.Error("coverart: embedded write failed; leaving NULL", "album_id", uuidString(albumID), "err", werr) @@ -137,7 +153,7 @@ func (e *Enricher) EnrichAlbum(ctx context.Context, albumID pgtype.UUID) error { // crash. return e.recordAlbumCover(ctx, albumID, "", "none", currentVersion) } - dest, werr := e.writeAlbumArt(albumID, *row.TrackFilePath, body) + dest, werr := e.writeAlbumArt(albumID, body) if werr != nil { e.logger.Error("coverart: write file failed; leaving NULL", "album_id", uuidString(albumID), @@ -161,28 +177,21 @@ func (e *Enricher) EnrichAlbum(ctx context.Context, albumID pgtype.UUID) error { return nil // at least one transient failure; leave NULL for retry } -// writeAlbumArt persists art bytes for an album, preferring the sidecar -// location next to the track file. Falls back to the managed cache -// (/album-art//cover.jpg) when the sidecar location -// isn't writable (e.g. read-only music mount in a container) and -// DataDir is set. Returns the path that was actually written. -// -// Used by both the embedded-art layer and the external provider -// chain — both produce the same dest-and-fallback semantics. -func (e *Enricher) writeAlbumArt(albumID pgtype.UUID, trackFilePath string, body []byte) (string, error) { - albumDir := filepath.Dir(trackFilePath) - dest := filepath.Join(albumDir, "cover.jpg") - werr := os.WriteFile(dest, body, 0o644) - if werr != nil && e.DataDir != "" { - fallbackDir := filepath.Join(e.DataDir, "album-art", uuidString(albumID)) - if mkErr := os.MkdirAll(fallbackDir, 0o755); mkErr != nil { - return "", fmt.Errorf("managed-cache mkdir failed (sidecar: %v): %w", werr, mkErr) - } - dest = filepath.Join(fallbackDir, "cover.jpg") - werr = os.WriteFile(dest, body, 0o644) +// writeAlbumArt saves art for an album in the enricher's cache, +// /album-art//cover.jpg, and returns that path. The embedded-art +// layer and the provider chain both save through it. It never writes beside +// the music. +func (e *Enricher) writeAlbumArt(albumID pgtype.UUID, body []byte) (string, error) { + if e.dataDir == "" { + return "", errors.New("write cover: no data directory to keep album art in") } - if werr != nil { - return "", fmt.Errorf("write cover: %w", werr) + dir := filepath.Join(e.artCacheRoot(), uuidString(albumID)) + if err := os.MkdirAll(dir, 0o755); err != nil { + return "", fmt.Errorf("write cover: %w", err) + } + dest := filepath.Join(dir, "cover.jpg") + if err := os.WriteFile(dest, body, 0o644); err != nil { + return "", fmt.Errorf("write cover: %w", err) } return dest, nil } @@ -345,11 +354,11 @@ func (e *Enricher) RetryAlbum(ctx context.Context, albumID pgtype.UUID) error { } return fmt.Errorf("get album: %w", err) } - // Delete the file only if we wrote it (mbcaa or theaudiodb). Sidecar - // images placed beside the music stay. - if row.CoverArtSource != nil && - (*row.CoverArtSource == "mbcaa" || *row.CoverArtSource == "theaudiodb") && - row.CoverArtPath != nil && *row.CoverArtPath != "" { + // Remove the old cover only when it is in the enricher's own cache. + // Anything else is a library file, even one an older Minstrel wrote + // beside the music, and stays: another program may have replaced it + // with its own since. + if row.CoverArtPath != nil && e.inArtCache(*row.CoverArtPath) { if err := os.Remove(*row.CoverArtPath); err != nil && !os.IsNotExist(err) { e.logger.Warn("coverart: remove old file failed", "album_id", uuidString(albumID), diff --git a/internal/coverart/enricher_test.go b/internal/coverart/enricher_test.go index d06c42e9..7ccdbf15 100644 --- a/internal/coverart/enricher_test.go +++ b/internal/coverart/enricher_test.go @@ -36,7 +36,21 @@ func newTestEnricher(t *testing.T, pool *pgxpool.Pool) *Enricher { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - return NewEnricher(pool, discardLogger(), s) + return NewEnricher(pool, discardLogger(), s, t.TempDir()) +} + +// cachedCover is where e keeps the cover it writes for an album. +func cachedCover(e *Enricher, albumID pgtype.UUID) string { + return filepath.Join(e.artCacheRoot(), uuidString(albumID), "cover.jpg") +} + +// assertNoCoverBeside fails when a cover.jpg sits in the album's folder: +// the enricher reads the library and never writes into it. +func assertNoCoverBeside(t *testing.T, albumDir string) { + t.Helper() + if _, err := os.Stat(filepath.Join(albumDir, "cover.jpg")); !os.IsNotExist(err) { + t.Errorf("a cover.jpg was written beside the music in %s (stat err %v)", albumDir, err) + } } // seedAlbumWithTrack creates an artist + album + track triple in a temp @@ -145,7 +159,7 @@ func TestEnrichAlbum_ProviderFetchSuccess(t *testing.T) { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - e := NewEnricher(pool, discardLogger(), s) + e := NewEnricher(pool, discardLogger(), s, t.TempDir()) if err := e.EnrichAlbum(context.Background(), id); err != nil { t.Fatalf("enrich: %v", err) @@ -158,10 +172,11 @@ func TestEnrichAlbum_ProviderFetchSuccess(t *testing.T) { if row.CoverArtSource == nil || *row.CoverArtSource != "mbcaa" { t.Errorf("source = %v, want 'mbcaa'", row.CoverArtSource) } - expectedPath := filepath.Join(dir, "cover.jpg") + expectedPath := cachedCover(e, id) if row.CoverArtPath == nil || *row.CoverArtPath != expectedPath { t.Errorf("path = %v, want %s", row.CoverArtPath, expectedPath) } + assertNoCoverBeside(t, dir) body, err := os.ReadFile(expectedPath) if err != nil { t.Fatalf("read file: %v", err) @@ -193,7 +208,7 @@ func TestEnrichAlbum_All404_RecordsNone(t *testing.T) { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - e := NewEnricher(pool, discardLogger(), s) + e := NewEnricher(pool, discardLogger(), s, t.TempDir()) if err := e.EnrichAlbum(context.Background(), id); err != nil { t.Fatalf("enrich: %v", err) @@ -306,15 +321,16 @@ func TestRetryAlbum_DeletesWrittenFileAndRefetches(t *testing.T) { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - e := NewEnricher(pool, discardLogger(), s) + e := NewEnricher(pool, discardLogger(), s, t.TempDir()) if err := e.EnrichAlbum(context.Background(), id); err != nil { t.Fatalf("first enrich: %v", err) } - written := filepath.Join(dir, "cover.jpg") + written := cachedCover(e, id) if _, err := os.Stat(written); err != nil { t.Fatalf("expected file at %s: %v", written, err) } + assertNoCoverBeside(t, dir) if err := e.RetryAlbum(context.Background(), id); err != nil { t.Fatalf("retry: %v", err) @@ -328,6 +344,36 @@ func TestRetryAlbum_DeletesWrittenFileAndRefetches(t *testing.T) { } } +// A cover an older Minstrel wrote beside the music is recorded as fetched +// from a provider. Retrying the album leaves that file alone: it is in a +// folder another program files into, and may be that program's by now. +func TestRetryAlbum_LeavesACoverBesideTheMusic(t *testing.T) { + pool := dbtest.Pool(t) + id, dir := seedAlbumWithTrack(t, pool, "Beside", "Artist", "") + beside := filepath.Join(dir, "cover.jpg") + if err := os.WriteFile(beside, []byte("filed"), 0o644); err != nil { + t.Fatal(err) + } + mbcaa := "mbcaa" + if err := dbq.New(pool).SetAlbumCover(context.Background(), dbq.SetAlbumCoverParams{ + ID: id, Column2: beside, CoverArtSource: &mbcaa, + }); err != nil { + t.Fatal(err) + } + + e := newTestEnricher(t, pool) + if err := e.RetryAlbum(context.Background(), id); err != nil { + t.Fatalf("retry: %v", err) + } + if body, err := os.ReadFile(beside); err != nil || string(body) != "filed" { + t.Fatalf("the cover beside the music was removed or changed: body %q, err %v", body, err) + } + row, _ := dbq.New(pool).GetAlbumWithFirstTrackPath(context.Background(), id) + if row.CoverArtSource == nil || *row.CoverArtSource != "sidecar" { + t.Errorf("source after retry = %v, want 'sidecar' (the file is read as the library's own)", row.CoverArtSource) + } +} + func TestEnrichRetryMissing_DrainsNullAndNone(t *testing.T) { pool := dbtest.Pool(t) // Three albums: @@ -430,7 +476,7 @@ func TestEnrichAlbum_MultiProviderChain(t *testing.T) { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - e := NewEnricher(pool, discardLogger(), s) + e := NewEnricher(pool, discardLogger(), s, t.TempDir()) if err := e.EnrichAlbum(context.Background(), id); err != nil { t.Fatalf("enrich: %v", err) @@ -443,9 +489,10 @@ func TestEnrichAlbum_MultiProviderChain(t *testing.T) { if row.CoverArtSource == nil || *row.CoverArtSource != "test-provider-b" { t.Errorf("source = %v, want 'test-provider-b' (provider B should win)", row.CoverArtSource) } - if body, err := os.ReadFile(filepath.Join(dir, "cover.jpg")); err != nil || string(body) != "PROVIDER_B_BYTES" { + if body, err := os.ReadFile(cachedCover(e, id)); err != nil || string(body) != "PROVIDER_B_BYTES" { t.Errorf("cover.jpg body = %q, err = %v", body, err) } + assertNoCoverBeside(t, dir) } // TestEnrichAlbum_TransientLeavesNull verifies that a transient error @@ -472,7 +519,7 @@ func TestEnrichAlbum_TransientLeavesNull(t *testing.T) { if err != nil { t.Fatalf("NewSettingsService: %v", err) } - e := NewEnricher(pool, discardLogger(), s) + e := NewEnricher(pool, discardLogger(), s, t.TempDir()) if err := e.EnrichAlbum(context.Background(), id); err != nil { t.Fatalf("enrich: %v", err)