feat(artwork): explain disc and media file artwork from the CLI

`artwork explain` rejected `dc` and `mf` because it validated against RecheckKinds,
the list of kinds the backfill revisits. Those are different questions: a kind with no
recheck path still has artwork someone can report as wrong.

Disc artwork now walks DiscArtPriority under a trace, so explain reports which entry won
and why the others lost, including entries that map to no source at all (external is
unsupported, a disc with no subtitle, an album folder with no images). Media file artwork
traces its single embedded candidate, separating "EnableMediaFileCoverArt is off" from
"the track has no embedded art" — stored state cannot tell those apart.

Each command now validates against the kinds it can actually serve: explain takes all six,
refresh takes artwork.RefreshableKinds (which nativeapi now shares instead of keeping its
own copy), reprocess still takes RecheckKinds. Disc artwork stays out of refresh: the
worker cannot resolve it, so the queue row would be rejected on every drain.

WalksPriorityChain becomes Explainable, and ResolveArtist/ResolveAlbum collapse into
Resolve(kind, id).
This commit is contained in:
Deluan 2026-08-14 18:20:31 -04:00
commit 947eb5de85
9 changed files with 484 additions and 109 deletions

View file

@ -37,7 +37,7 @@ func init() {
artworkExplainCmd.Flags().BoolVar(&explainLive, "live", false,
"perform real external lookups instead of reporting what would be tried")
artworkReprocessCmd.Flags().StringSliceVar(&reprocessKinds, "kind", nil,
"kinds to reprocess (ar, al, pl, ra); repeatable")
"kinds to reprocess ("+kindPrefixes(artwork.RecheckKinds)+"); repeatable")
artworkReprocessCmd.Flags().StringSliceVar(&reprocessSources, "source", nil,
"only items currently resolved from these sources (e.g. folder, external:deezer, absent)")
artworkReprocessCmd.Flags().BoolVar(&reprocessAll, "all", false, "reprocess every kind")
@ -59,9 +59,12 @@ var artworkCmd = &cobra.Command{
var artworkExplainCmd = &cobra.Command{
Use: "explain <kind> <id>",
Short: "Explain why an item's artwork resolved the way it did",
Args: cobra.ExactArgs(2),
Long: "Explain why an item's artwork resolved the way it did.\n\n" +
"<kind> is one of: " + kindPrefixes(explainKinds) + ".\n" +
"A disc artwork id is the album id and the disc number, joined by a colon: <albumID>:2",
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
kind, err := parseArtworkKind(args[0])
kind, err := parseArtworkKind(args[0], explainKinds)
if err != nil {
log.Fatal(cmd.Context(), err)
}
@ -74,7 +77,7 @@ var artworkRefreshCmd = &cobra.Command{
Short: "Clear an item's artwork state and re-resolve it",
Args: cobra.MinimumNArgs(2),
Run: func(cmd *cobra.Command, args []string) {
kind, err := parseArtworkKind(args[0])
kind, err := parseArtworkKind(args[0], artwork.RefreshableKinds)
if err != nil {
log.Fatal(cmd.Context(), err)
}
@ -290,7 +293,7 @@ func selectedKinds(kinds, sources []string, all bool) ([]model.Kind, error) {
}
out := make([]model.Kind, 0, len(kinds))
for _, k := range kinds {
kind, err := parseArtworkKind(k)
kind, err := parseArtworkKind(k, artwork.RecheckKinds)
if err != nil {
return nil, err
}
@ -488,13 +491,23 @@ func refreshItems(ctx context.Context, ds model.DataStore, kind model.Kind, ids
return failed
}
func parseArtworkKind(s string) (model.Kind, error) {
// explainKinds is every kind explain accepts: it reports stored state and config too, so a kind
// with no chain to walk still has something to answer with.
var explainKinds = []model.Kind{
model.KindArtistArtwork, model.KindAlbumArtwork, model.KindDiscArtwork,
model.KindMediaFileArtwork, model.KindPlaylistArtwork, model.KindRadioArtwork,
}
func kindPrefixes(kinds []model.Kind) string {
return strings.Join(slice.Map(kinds, func(k model.Kind) string { return k.Prefix() }), ", ")
}
func parseArtworkKind(s string, valid []model.Kind) (model.Kind, error) {
kind, ok := model.ParseKind(s)
if ok && slices.Contains(artwork.RecheckKinds, kind) {
if ok && slices.Contains(valid, kind) {
return kind, nil
}
valid := slice.Map(artwork.RecheckKinds, func(k model.Kind) string { return k.Prefix() })
return kind, fmt.Errorf("invalid kind %q, expected one of: %s", s, strings.Join(valid, ", "))
return kind, fmt.Errorf("invalid kind %q, expected one of: %s", s, kindPrefixes(valid))
}
// explainAgents accounts for every configured agent: one the CLI cannot construct (a plugin, or a
@ -560,24 +573,42 @@ func explainResult(source string, steps []artwork.TraceStep) string {
return "not resolved"
}
// keepsArtworkState reports whether a kind is recorded in item_artwork and the queue at all. Disc
// artwork is resolved on every request and cached by content key, so it has neither.
func keepsArtworkState(kind model.Kind) bool { return kind != model.KindDiscArtwork }
// explainConfig names the setting that decides where a kind's artwork comes from, and its value.
func explainConfig(kind model.Kind) (name, value string) {
switch kind {
case model.KindArtistArtwork:
return "ArtistArtPriority", conf.Server.ArtistArtPriority
case model.KindAlbumArtwork:
return "CoverArtPriority", conf.Server.CoverArtPriority
case model.KindDiscArtwork:
return "DiscArtPriority", conf.Server.DiscArtPriority
case model.KindMediaFileArtwork:
return "EnableMediaFileCoverArt", strconv.FormatBool(conf.Server.EnableMediaFileCoverArt)
}
return "", ""
}
type explainReport struct {
kind model.Kind
id string
name string
stored *model.ItemArtwork
queued *model.ArtworkQueueItem
priorityName string
priority string
agents string
steps []artwork.TraceStep
source string
resolveErr error
kind model.Kind
id string
name string
stored *model.ItemArtwork
queued *model.ArtworkQueueItem
agents string
steps []artwork.TraceStep
source string
resolveErr error
}
func formatExplain(rep explainReport) string {
var sb strings.Builder
w := newTabWriter(&sb)
walksChain := artwork.WalksPriorityChain(rep.kind)
explainable := artwork.Explainable(rep.kind)
stateful := keepsArtworkState(rep.kind)
fmt.Fprintln(w, "Item")
fmt.Fprintf(w, " Kind:\t%s (%s)\n", rep.kind, rep.kind.Prefix())
@ -585,9 +616,12 @@ func formatExplain(rep explainReport) string {
fmt.Fprintf(w, " Name:\t%s\n", rep.name)
fmt.Fprintln(w, "\nStored")
if rep.stored == nil {
switch {
case !stateful:
fmt.Fprintf(w, " (%s artwork is resolved on every request and never recorded)\n", rep.kind)
case rep.stored == nil:
fmt.Fprintln(w, " (no artwork state recorded)")
} else {
default:
fmt.Fprintf(w, " Source:\t%s\n", displaySource(rep.stored.Source))
fmt.Fprintf(w, " Hash:\t%s\n", cmp.Or(rep.stored.Hash, "(absent)"))
if rep.stored.SourcePath != "" {
@ -597,24 +631,29 @@ func formatExplain(rep explainReport) string {
}
fmt.Fprintln(w, "\nQueue")
if rep.queued == nil {
switch {
case !stateful:
fmt.Fprintln(w, " (never queued)")
case rep.queued == nil:
fmt.Fprintln(w, " (not queued)")
} else {
default:
fmt.Fprintf(w, " Priority:\t%s (%d)\n", priorityName(rep.queued.Priority), rep.queued.Priority)
fmt.Fprintf(w, " Attempts:\t%d\n", rep.queued.Attempts)
fmt.Fprintf(w, " Retry at:\t%s\n", formatTime(rep.queued.RetryAt))
}
fmt.Fprintln(w, "\nConfig")
if !walksChain {
fmt.Fprintln(w, " (no priority chain configuration applies)")
if setting, value := explainConfig(rep.kind); setting == "" {
fmt.Fprintln(w, " (no artwork source configuration applies)")
} else {
fmt.Fprintf(w, " %s:\t%s\n", rep.priorityName, rep.priority)
fmt.Fprintf(w, " Agents:\t%s\n", rep.agents)
fmt.Fprintf(w, " %s:\t%s\n", setting, value)
if rep.agents != "" {
fmt.Fprintf(w, " Agents:\t%s\n", rep.agents)
}
}
fmt.Fprintln(w, "\nChain")
if !walksChain {
if !explainable {
fmt.Fprintf(w, " (%s artwork does not walk a priority chain)\n", rep.kind)
} else {
fmt.Fprintln(w, " CANDIDATE\tOUTCOME\tDETAIL")
@ -628,7 +667,7 @@ func formatExplain(rep explainReport) string {
switch {
case rep.resolveErr != nil:
fmt.Fprintf(w, " resolution failed: %s\n", rep.resolveErr)
case !walksChain:
case !explainable:
fmt.Fprintln(w, " not evaluated (no chain was walked; see Stored above)")
default:
fmt.Fprintf(w, " %s\n", explainResult(rep.source, rep.steps))
@ -653,32 +692,24 @@ func runExplain(ctx context.Context, kind model.Kind, id string) {
if err != nil {
log.Fatal(ctx, "Item not found", "kind", kind, "id", id, err)
}
rep := explainReport{
kind: kind, id: id, name: name,
priorityName: "CoverArtPriority", priority: conf.Server.CoverArtPriority,
}
if kind == model.KindArtistArtwork {
rep.priorityName, rep.priority = "ArtistArtPriority", conf.Server.ArtistArtPriority
}
rep.stored, err = ds.Artwork(ctx).GetItemArtwork(kind, id, model.ImageTypePrimary)
if err != nil && !errors.Is(err, model.ErrNotFound) {
log.Fatal(ctx, "Failed to read artwork state", "kind", kind, "id", id, err)
}
rep.queued, err = ds.ArtworkQueue(ctx).Get(kind, id, model.ImageTypePrimary)
if err != nil && !errors.Is(err, model.ErrNotFound) {
log.Fatal(ctx, "Failed to read the artwork queue", "kind", kind, "id", id, err)
}
if artwork.WalksPriorityChain(kind) {
rep.agents = explainAgents(conf.Server.Agents, availableImageAgents(ds, kind))
trace := &artwork.ChainTrace{}
resolver := CreateArtworkResolver(trace, explainLive)
resolve := resolver.ResolveAlbum
if kind == model.KindArtistArtwork {
resolve = resolver.ResolveArtist
rep := explainReport{kind: kind, id: id, name: name}
if keepsArtworkState(kind) {
rep.stored, err = ds.Artwork(ctx).GetItemArtwork(kind, id, model.ImageTypePrimary)
if err != nil && !errors.Is(err, model.ErrNotFound) {
log.Fatal(ctx, "Failed to read artwork state", "kind", kind, "id", id, err)
}
rep.source, rep.resolveErr = resolve(ctx, id)
rep.queued, err = ds.ArtworkQueue(ctx).Get(kind, id, model.ImageTypePrimary)
if err != nil && !errors.Is(err, model.ErrNotFound) {
log.Fatal(ctx, "Failed to read the artwork queue", "kind", kind, "id", id, err)
}
}
if artwork.Explainable(kind) {
if kind == model.KindArtistArtwork || kind == model.KindAlbumArtwork {
rep.agents = explainAgents(conf.Server.Agents, availableImageAgents(ds, kind))
}
trace := &artwork.ChainTrace{}
rep.source, rep.resolveErr = CreateArtworkResolver(trace, explainLive).Resolve(ctx, kind, id)
rep.steps = trace.Steps()
}
@ -717,6 +748,31 @@ func artworkItemName(ctx context.Context, ds model.DataStore, kind model.Kind, i
return "", err
}
return rd.Name, nil
case model.KindMediaFileArtwork:
mf, err := ds.MediaFile(ctx).Get(id)
if err != nil {
return "", err
}
return mf.Title, nil
case model.KindDiscArtwork:
return discArtworkName(ctx, ds, id)
}
return "", fmt.Errorf("unsupported kind %q", kind.Prefix())
}
func discArtworkName(ctx context.Context, ds model.DataStore, id string) (string, error) {
albumID, discNumber, err := model.ParseDiscArtworkID(id)
if err != nil {
return "", err
}
al, err := ds.Album(ctx).Get(albumID)
if err != nil {
return "", err
}
name := fmt.Sprintf("%s (disc %d)", al.Name, discNumber)
// The subtitle is itself a DiscArtPriority candidate, so name it where the chain can be read against it.
if subtitle := strings.TrimSpace(al.Discs[discNumber]); subtitle != "" {
name += ": " + subtitle
}
return name, nil
}

View file

@ -19,20 +19,37 @@ import (
var _ = Describe("parseArtworkKind", func() {
It("accepts a supported kind", func() {
k, err := parseArtworkKind("ar")
k, err := parseArtworkKind("ar", artwork.RecheckKinds)
Expect(err).ToNot(HaveOccurred())
Expect(k).To(Equal(model.KindArtistArtwork))
})
It("rejects an unknown kind and lists the valid ones", func() {
_, err := parseArtworkKind("zz")
_, err := parseArtworkKind("zz", artwork.RecheckKinds)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("ar"))
Expect(err.Error()).To(ContainSubstring("al"))
})
It("rejects a known kind that has no artwork command", func() {
_, err := parseArtworkKind("mf")
It("rejects a known kind the command does not accept", func() {
_, err := parseArtworkKind("mf", artwork.RecheckKinds)
Expect(err).To(HaveOccurred())
})
DescribeTable("accepts the kinds each command supports",
func(prefix string, valid []model.Kind) {
_, err := parseArtworkKind(prefix, valid)
Expect(err).ToNot(HaveOccurred())
},
Entry("explain reads disc artwork", "dc", explainKinds),
Entry("explain reads media file artwork", "mf", explainKinds),
// Disc artwork has no state to clear and the worker cannot resolve it, so refresh must not
// accept it: the queue row would be rejected on every drain.
Entry("refresh re-queues media files", "mf", artwork.RefreshableKinds),
)
It("rejects disc artwork for refresh", func() {
_, err := parseArtworkKind("dc", artwork.RefreshableKinds)
Expect(err).To(HaveOccurred())
})
})
@ -141,13 +158,13 @@ var _ = Describe("formatExplain", func() {
var rep explainReport
BeforeEach(func() {
DeferCleanup(configtest.SetupConfig())
conf.Server.ArtistArtPriority = "external, artist.*"
rep = explainReport{
kind: model.KindArtistArtwork,
id: "ar-1",
name: "Radiohead",
priorityName: "ArtistArtPriority",
priority: "external, artist.*",
agents: "lastfm,spotify",
kind: model.KindArtistArtwork,
id: "ar-1",
name: "Radiohead",
agents: "lastfm,spotify",
steps: []artwork.TraceStep{
{Candidate: "upload", Outcome: "skipped", Detail: "no uploaded image"},
{Candidate: "external:deezer", Outcome: "would-try"},
@ -204,9 +221,10 @@ var _ = Describe("formatExplain", func() {
})
It("says a kind that does not walk a chain has no chain, without an empty table", func() {
conf.Server.CoverArtPriority = "cover.*, embedded"
rep.kind = model.KindPlaylistArtwork
rep.steps = nil
rep.priorityName, rep.priority = "CoverArtPriority", "cover.*, embedded"
rep.agents = ""
out := formatExplain(rep)
Expect(out).To(ContainSubstring("does not walk a priority chain"))
@ -217,6 +235,86 @@ var _ = Describe("formatExplain", func() {
Expect(out).ToNot(ContainSubstring("CoverArtPriority"),
"the priority chain config does not govern this kind")
})
It("says disc artwork keeps no state instead of reporting it as unresolved state", func() {
conf.Server.DiscArtPriority = "cover.jpg, embedded"
rep = explainReport{
kind: model.KindDiscArtwork, id: "al-1:2", name: "OK Computer (disc 2)",
steps: []artwork.TraceStep{{Candidate: "cover.jpg", Outcome: "hit", Detail: "/music/cover.jpg"}},
source: "folder",
}
out := formatExplain(rep)
Expect(out).To(ContainSubstring("never recorded"))
Expect(out).To(ContainSubstring("never queued"))
Expect(out).ToNot(ContainSubstring("no artwork state recorded"),
"a missing row would read as a lookup that failed, when disc artwork has no row by design")
Expect(out).To(ContainSubstring("DiscArtPriority"))
Expect(out).ToNot(ContainSubstring("Agents:"), "disc artwork never asks an agent")
Expect(out).To(ContainSubstring("resolved from folder"))
})
It("reports the setting that governs media file artwork", func() {
conf.Server.EnableMediaFileCoverArt = false
rep = explainReport{
kind: model.KindMediaFileArtwork, id: "mf-1", name: "Airbag",
steps: []artwork.TraceStep{
{Candidate: "embedded", Outcome: "skipped", Detail: "EnableMediaFileCoverArt is off"},
},
}
out := formatExplain(rep)
Expect(out).To(ContainSubstring("EnableMediaFileCoverArt"))
Expect(out).To(ContainSubstring("false"))
Expect(out).To(ContainSubstring("not resolved"))
Expect(out).To(ContainSubstring("no artwork state recorded"), "media files do keep state")
})
})
var _ = Describe("explainConfig", func() {
BeforeEach(func() {
DeferCleanup(configtest.SetupConfig())
conf.Server.DiscArtPriority = "cover.jpg"
conf.Server.EnableMediaFileCoverArt = true
})
DescribeTable("names the setting that decides where a kind's artwork comes from",
func(kind model.Kind, setting, value string) {
gotSetting, gotValue := explainConfig(kind)
Expect(gotSetting).To(Equal(setting))
Expect(gotValue).To(Equal(value))
},
Entry("disc", model.KindDiscArtwork, "DiscArtPriority", "cover.jpg"),
Entry("media file", model.KindMediaFileArtwork, "EnableMediaFileCoverArt", "true"),
Entry("playlist has none", model.KindPlaylistArtwork, "", ""),
)
})
var _ = Describe("discArtworkName", func() {
var ds *tests.MockDataStore
BeforeEach(func() {
albumRepo := tests.CreateMockAlbumRepo()
albumRepo.SetData(model.Albums{{ID: "al-1", Name: "Sandinista!", Discs: model.Discs{2: "Side Three"}}})
ds = &tests.MockDataStore{MockedAlbum: albumRepo}
})
It("names the album, the disc and its subtitle", func() {
name, err := artworkItemName(context.Background(), ds, model.KindDiscArtwork, "al-1:2")
Expect(err).ToNot(HaveOccurred())
Expect(name).To(Equal("Sandinista! (disc 2): Side Three"))
})
It("omits the subtitle when the disc has none", func() {
name, err := artworkItemName(context.Background(), ds, model.KindDiscArtwork, "al-1:1")
Expect(err).ToNot(HaveOccurred())
Expect(name).To(Equal("Sandinista! (disc 1)"))
})
It("rejects an id that is not <albumID>:<disc>", func() {
_, err := artworkItemName(context.Background(), ds, model.KindDiscArtwork, "al-1")
Expect(err).To(HaveOccurred())
})
})
var _ = Describe("artwork refresh command", func() {

View file

@ -406,12 +406,20 @@ func NewTracingResolver(ds model.DataStore, ag *agents.Agents, ffm ffmpeg.FFmpeg
return &TracingResolver{inner: newResolver(ds, ag, ffm, gate), trace: t}
}
func (r *TracingResolver) ResolveArtist(ctx context.Context, id string) (string, error) {
return r.explain(ctx, r.inner.resolveArtist, id)
}
func (r *TracingResolver) ResolveAlbum(ctx context.Context, id string) (string, error) {
return r.explain(ctx, r.inner.resolveAlbum, id)
// Resolve walks kind's sources for id, recording the walk, and reports the winning source
// ("" when none produced an image).
func (r *TracingResolver) Resolve(ctx context.Context, kind model.Kind, id string) (string, error) {
switch kind {
case model.KindArtistArtwork:
return r.explain(ctx, r.inner.resolveArtist, id)
case model.KindAlbumArtwork:
return r.explain(ctx, r.inner.resolveAlbum, id)
case model.KindDiscArtwork:
return r.explain(ctx, r.inner.resolveDisc, id)
case model.KindMediaFileArtwork:
return r.explain(ctx, r.inner.resolveMediaFile, id)
}
return "", fmt.Errorf("artwork: %s artwork has no chain to explain", kind)
}
// explain discards the bytes: nothing downstream persists this resolution, so nothing else

View file

@ -113,25 +113,53 @@ func newDiscArtworkReader(ctx context.Context, ds model.DataStore, artID model.A
}, nil
}
func (d *discArtworkReader) fromDiscArtPriority(ctx context.Context, ffmpeg ffmpeg.FFmpeg, priority string) []sourceFunc {
var ff []sourceFunc
// discCandidate is one DiscArtPriority entry. skip is set when the entry maps to no source at
// all, so a chain walk can say why instead of leaving a configured entry unaccounted for.
type discCandidate struct {
pattern string
sources []sourceFunc
skip string
}
func (d *discArtworkReader) discCandidates(ctx context.Context, ffmpeg ffmpeg.FFmpeg, priority string) []discCandidate {
var cc []discCandidate
for pattern := range strings.SplitSeq(strings.ToLower(priority), ",") {
pattern = strings.TrimSpace(pattern)
if pattern == "" {
continue
}
c := discCandidate{pattern: pattern}
switch {
case pattern == "embedded":
ff = append(ff,
c.sources = []sourceFunc{
fromTag(ctx, d.lib.FS, d.firstTrackRel),
fromFFmpegTag(ctx, ffmpeg, d.lib.Abs(d.firstTrackRel)),
)
case pattern == externalCandidate:
// Not supported for disc art, silently ignore
case pattern == "discsubtitle":
if subtitle := strings.TrimSpace(d.album.Discs[d.discNumber]); subtitle != "" {
ff = append(ff, d.fromDiscSubtitle(ctx, subtitle))
}
case len(d.imgFiles) > 0:
ff = append(ff, d.fromExternalFile(ctx, pattern))
case pattern == externalCandidate:
c.skip = "external sources are not supported for disc artwork"
case pattern == "discsubtitle":
subtitle := strings.TrimSpace(d.album.Discs[d.discNumber])
if subtitle == "" {
c.skip = "disc has no subtitle"
} else {
c.sources = []sourceFunc{d.fromDiscSubtitle(ctx, subtitle)}
}
case len(d.imgFiles) == 0:
c.skip = "no images in album folder"
default:
c.sources = []sourceFunc{d.fromExternalFile(ctx, pattern)}
}
cc = append(cc, c)
}
return cc
}
// fromDiscArtPriority flattens the candidates for the serving path, which needs the sources in
// order and has no walk to report.
func (d *discArtworkReader) fromDiscArtPriority(ctx context.Context, ffmpeg ffmpeg.FFmpeg, priority string) []sourceFunc {
var ff []sourceFunc
for _, c := range d.discCandidates(ctx, ffmpeg, priority) {
ff = append(ff, c.sources...)
}
return ff
}

View file

@ -26,6 +26,10 @@ var RecheckKinds = []model.Kind{
model.KindArtistArtwork, model.KindAlbumArtwork, model.KindPlaylistArtwork, model.KindRadioArtwork,
}
// RefreshableKinds is every kind Refresh can clear and re-queue. Media files are absent from
// RecheckKinds but belong here: the worker resolves them, it just never revisits them on its own.
var RefreshableKinds = append(slices.Clone(RecheckKinds), model.KindMediaFileArtwork)
// hasRecheckPath reports whether a periodic job will revisit this kind, making an absent settle recoverable.
func hasRecheckPath(prefix string) bool {
kind, ok := model.ParseKind(prefix)

View file

@ -9,6 +9,7 @@ import (
"io/fs"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/Masterminds/squirrel"
@ -108,10 +109,14 @@ func (r *resolver) resolve(ctx context.Context, item model.ArtworkQueueItem) (re
}
}
// WalksPriorityChain reports whether the resolver picks this kind's artwork from a configurable
// priority chain; playlists and radios resolve from a fixed order, so there is no walk to explain.
func WalksPriorityChain(kind model.Kind) bool {
return kind == model.KindArtistArtwork || kind == model.KindAlbumArtwork
// Explainable reports whether TracingResolver can walk this kind's sources and report which one
// won; playlists and radios resolve from a fixed internal order, with nothing configured to explain.
func Explainable(kind model.Kind) bool {
switch kind {
case model.KindArtistArtwork, model.KindAlbumArtwork, model.KindDiscArtwork, model.KindMediaFileArtwork:
return true
}
return false
}
// MayFetchExternal reports whether resolving this kind can issue an external request under the
@ -430,15 +435,62 @@ func (r *resolver) resolveMediaFile(ctx context.Context, id string) (resolution,
if err != nil {
return resolution{}, err
}
if !conf.Server.EnableMediaFileCoverArt || !mf.HasCoverArt {
chain := chainState{trace: traceFrom(ctx)}
switch {
case !conf.Server.EnableMediaFileCoverArt:
chain.record("embedded", OutcomeSkipped, "EnableMediaFileCoverArt is off")
return resolution{}, nil
case !mf.HasCoverArt:
chain.record("embedded", OutcomeMiss, "the track has no embedded cover art")
return resolution{}, nil
}
lib, err := loadLibraryView(ctx, r.ds, mf.LibraryID)
if err != nil {
return resolution{}, err
}
res, _ := resolveEmbedded(ctx, lib, r.ffmpeg, mf.Path)
return res, nil
res, ok := resolveEmbedded(ctx, lib, r.ffmpeg, mf.Path)
if res, ok = chain.try("embedded", res, ok); ok {
return res, nil
}
return chain.exhausted(), nil
}
// resolveDisc walks conf.Server.DiscArtPriority. Disc artwork keeps no state row and is never
// queued: the serving path reads it through on every request, so this only ever explains.
func (r *resolver) resolveDisc(ctx context.Context, id string) (resolution, error) {
dr, err := newDiscArtworkReader(ctx, r.ds, model.ArtworkID{Kind: model.KindDiscArtwork, ID: id})
if err != nil {
return resolution{}, err
}
chain := chainState{trace: traceFrom(ctx)}
for _, c := range dr.discCandidates(ctx, r.ffmpeg, conf.Server.DiscArtPriority) {
if c.skip != "" {
chain.record(c.pattern, OutcomeSkipped, c.skip)
continue
}
res, ok := openDiscCandidate(c, dr.lib)
if res, ok = chain.try(c.pattern, res, ok); ok {
return res, nil
}
}
return chain.exhausted(), nil
}
func openDiscCandidate(c discCandidate, lib libraryView) (resolution, bool) {
source := "folder"
if c.pattern == "embedded" {
source = "embedded"
}
for _, sf := range c.sources {
if rd, path, _ := sf(); rd != nil {
// The disc sources disagree on this: only ffmpeg hands back an absolute path.
if !filepath.IsAbs(path) {
path = lib.Abs(path)
}
return resolution{reader: rd, source: source, sourcePath: path}, true
}
}
return resolution{}, false
}
// resolveExternalStep runs a single external sourceFunc through the named gate. extErr excludes

View file

@ -653,15 +653,17 @@ var _ = Describe("decodeTile", func() {
})
})
var _ = Describe("WalksPriorityChain", func() {
var _ = Describe("Explainable", func() {
It("is true for the kinds the resolver walks", func() {
Expect(WalksPriorityChain(model.KindArtistArtwork)).To(BeTrue())
Expect(WalksPriorityChain(model.KindAlbumArtwork)).To(BeTrue())
Expect(Explainable(model.KindArtistArtwork)).To(BeTrue())
Expect(Explainable(model.KindAlbumArtwork)).To(BeTrue())
Expect(Explainable(model.KindDiscArtwork)).To(BeTrue())
Expect(Explainable(model.KindMediaFileArtwork)).To(BeTrue())
})
It("is false for the kinds resolved directly", func() {
Expect(WalksPriorityChain(model.KindPlaylistArtwork)).To(BeFalse())
Expect(WalksPriorityChain(model.KindRadioArtwork)).To(BeFalse())
It("is false for the kinds resolved from a fixed internal order", func() {
Expect(Explainable(model.KindPlaylistArtwork)).To(BeFalse())
Expect(Explainable(model.KindRadioArtwork)).To(BeFalse())
})
})

View file

@ -421,7 +421,7 @@ var _ = Describe("NewTracingResolver", func() {
})
It("reports the external tier without asking any agent", func() {
source, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, false).ResolveAlbum(context.Background(), "al1")
source, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, false).Resolve(context.Background(), model.KindAlbumArtwork, "al1")
Expect(err).ToNot(HaveOccurred())
Expect(source).To(Equal("embedded"))
@ -430,7 +430,7 @@ var _ = Describe("NewTracingResolver", func() {
})
It("records the local chain steps too", func() {
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, false).ResolveAlbum(context.Background(), "al1")
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, false).Resolve(context.Background(), model.KindAlbumArtwork, "al1")
Expect(err).ToNot(HaveOccurred())
last := t.Steps()[len(t.Steps())-1]
@ -439,7 +439,7 @@ var _ = Describe("NewTracingResolver", func() {
})
It("never persists artwork state", func() {
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, false).ResolveAlbum(context.Background(), "al1")
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, false).Resolve(context.Background(), model.KindAlbumArtwork, "al1")
Expect(err).ToNot(HaveOccurred())
Expect(artworkRepo.ItemData).To(BeEmpty(),
@ -448,7 +448,7 @@ var _ = Describe("NewTracingResolver", func() {
})
It("resolves an artist without persisting anything", func() {
source, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, false).ResolveArtist(context.Background(), "ar1")
source, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, false).Resolve(context.Background(), model.KindArtistArtwork, "ar1")
Expect(err).ToNot(HaveOccurred())
Expect(source).To(BeEmpty())
@ -465,7 +465,7 @@ var _ = Describe("NewTracingResolver", func() {
ID: "al2", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/no-such-file.mp3", FolderIDs: []string{"f1"},
}})
source, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, false).ResolveAlbum(context.Background(), "al2")
source, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, false).Resolve(context.Background(), model.KindAlbumArtwork, "al2")
Expect(err).ToNot(HaveOccurred())
Expect(source).To(Equal("embedded"))
@ -473,7 +473,7 @@ var _ = Describe("NewTracingResolver", func() {
})
It("propagates a lookup error", func() {
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, false).ResolveAlbum(context.Background(), "nope")
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, false).Resolve(context.Background(), model.KindAlbumArtwork, "nope")
Expect(err).To(MatchError(model.ErrNotFound))
})
})
@ -484,10 +484,145 @@ var _ = Describe("NewTracingResolver", func() {
ID: "al1", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"},
}})
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).ResolveAlbum(context.Background(), "al1")
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(context.Background(), model.KindAlbumArtwork, "al1")
Expect(err).ToNot(HaveOccurred())
Expect(fake.albumCalls).To(Equal(1))
Expect(t.Steps()).To(ContainElement(TraceStep{Candidate: "external:live-probe", Outcome: OutcomeMiss}))
})
})
var _ = Describe("resolveDisc tracing", func() {
var (
ctx context.Context
ds *tests.MockDataStore
albumRepo *tests.MockAlbumRepo
folderRepo *fakeFolderRepo
ffm *tests.MockFFmpeg
t *ChainTrace
)
BeforeEach(func() {
DeferCleanup(configtest.SetupConfig())
repoRoot, err := os.Getwd()
Expect(err).ToNot(HaveOccurred())
libRepo := &tests.MockLibraryRepo{}
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}})
albumRepo = tests.CreateMockAlbumRepo()
albumRepo.SetData(model.Albums{{ID: "al1", Name: "Album", FolderIDs: []string{"f1"}}})
folderRepo = &fakeFolderRepo{}
mfRepo := tests.CreateMockMediaFileRepo()
mfRepo.SetData(model.MediaFiles{{ID: "mf1", AlbumID: "al1", DiscNumber: 2, Path: "tests/fixtures/artist/an-album/test.mp3"}})
ds = &tests.MockDataStore{
MockedAlbum: albumRepo,
MockedMediaFile: mfRepo,
MockedFolder: folderRepo,
MockedLibrary: libRepo,
}
ffm = tests.NewMockFFmpeg("")
t = &ChainTrace{}
ctx = withTrace(context.Background(), t)
})
It("accounts for every configured entry, including the ones that map to no source", func() {
conf.Server.DiscArtPriority = "external, discsubtitle, cover.jpg"
res, err := newResolver(ds, nil, ffm, nil).resolveDisc(ctx, model.DiscArtworkID("al1", 2))
Expect(err).ToNot(HaveOccurred())
Expect(res.reader).To(BeNil())
Expect(t.Steps()).To(Equal([]TraceStep{
{Candidate: "external", Outcome: OutcomeSkipped, Detail: "external sources are not supported for disc artwork"},
{Candidate: "discsubtitle", Outcome: OutcomeSkipped, Detail: "disc has no subtitle"},
{Candidate: "cover.jpg", Outcome: OutcomeSkipped, Detail: "no images in album folder"},
}))
})
It("records the entry that won and stops there", func() {
conf.Server.DiscArtPriority = "disc*.*, cover.jpg, embedded"
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
res, err := newResolver(ds, nil, ffm, nil).resolveDisc(ctx, model.DiscArtworkID("al1", 2))
Expect(err).ToNot(HaveOccurred())
Expect(res.reader).ToNot(BeNil())
defer res.reader.Close()
Expect(res.source).To(Equal("folder"))
Expect(t.Steps()).To(HaveLen(2), "the walk must stop at the winner, and record nothing below it")
Expect(t.Steps()[0]).To(Equal(TraceStep{Candidate: "disc*.*", Outcome: OutcomeMiss}))
Expect(t.Steps()[1].Candidate).To(Equal("cover.jpg"))
Expect(t.Steps()[1].Outcome).To(Equal(OutcomeHit))
Expect(t.Steps()[1].Detail).To(HaveSuffix(filepath.FromSlash("tests/fixtures/artist/an-album/cover.jpg")))
Expect(t.Steps()[1].Detail).ToNot(Equal("tests/fixtures/artist/an-album/cover.jpg"),
"a library-relative path sends the operator looking in the wrong place")
})
It("reports an unparseable disc id rather than explaining another disc", func() {
conf.Server.DiscArtPriority = "cover.jpg"
_, err := newResolver(ds, nil, ffm, nil).resolveDisc(ctx, "al1")
Expect(err).To(HaveOccurred())
})
})
var _ = Describe("resolveMediaFile tracing", func() {
var (
ctx context.Context
ds *tests.MockDataStore
mfRepo *tests.MockMediaFileRepo
ffm *tests.MockFFmpeg
t *ChainTrace
)
BeforeEach(func() {
DeferCleanup(configtest.SetupConfig())
conf.Server.EnableMediaFileCoverArt = true
repoRoot, err := os.Getwd()
Expect(err).ToNot(HaveOccurred())
libRepo := &tests.MockLibraryRepo{}
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}})
mfRepo = tests.CreateMockMediaFileRepo()
mfRepo.SetData(model.MediaFiles{{
ID: "mf1", Title: "Song", HasCoverArt: true, Path: "tests/fixtures/artist/an-album/test.mp3",
}})
ds = &tests.MockDataStore{MockedMediaFile: mfRepo, MockedLibrary: libRepo}
ffm = tests.NewMockFFmpeg("")
t = &ChainTrace{}
ctx = withTrace(context.Background(), t)
})
It("separates a disabled setting from a track with nothing embedded", func() {
conf.Server.EnableMediaFileCoverArt = false
_, err := newResolver(ds, nil, ffm, nil).resolveMediaFile(ctx, "mf1")
Expect(err).ToNot(HaveOccurred())
Expect(t.Steps()).To(Equal([]TraceStep{
{Candidate: "embedded", Outcome: OutcomeSkipped, Detail: "EnableMediaFileCoverArt is off"},
}))
})
It("records a track with no embedded art as a miss", func() {
mfRepo.SetData(model.MediaFiles{{ID: "mf2", Title: "Song", HasCoverArt: false}})
_, err := newResolver(ds, nil, ffm, nil).resolveMediaFile(ctx, "mf2")
Expect(err).ToNot(HaveOccurred())
Expect(t.Steps()).To(Equal([]TraceStep{
{Candidate: "embedded", Outcome: OutcomeMiss, Detail: "the track has no embedded cover art"},
}))
})
It("records the embedded hit", func() {
res, err := newResolver(ds, nil, ffm, nil).resolveMediaFile(ctx, "mf1")
Expect(err).ToNot(HaveOccurred())
Expect(res.reader).ToNot(BeNil())
defer res.reader.Close()
Expect(res.source).To(Equal("embedded"))
Expect(t.Steps()).To(HaveLen(1))
Expect(t.Steps()[0].Outcome).To(Equal(OutcomeHit))
})
})

View file

@ -10,14 +10,6 @@ import (
"github.com/navidrome/navidrome/model"
)
var refreshableArtworkKinds = []model.Kind{
model.KindAlbumArtwork,
model.KindArtistArtwork,
model.KindPlaylistArtwork,
model.KindRadioArtwork,
model.KindMediaFileArtwork,
}
func (api *Router) addArtworkRoute(r chi.Router) {
r.Post("/artwork/{kind}/{id}/refresh", api.refreshArtwork())
}
@ -28,7 +20,7 @@ func (api *Router) refreshArtwork() http.HandlerFunc {
ctx := r.Context()
kind, _ := model.ParseKind(chi.URLParam(r, "kind"))
id := chi.URLParam(r, "id")
if !slices.Contains(refreshableArtworkKinds, kind) {
if !slices.Contains(artwork.RefreshableKinds, kind) {
http.Error(w, "invalid artwork kind", http.StatusBadRequest)
return
}