mirror of
https://github.com/navidrome/navidrome.git
synced 2026-08-31 07:30:32 +00:00
* feat(artwork): add a resolution chain trace collector * feat(artwork): trace the local priority chain * fix(artwork): record priority candidates the chain never evaluated * refactor(artwork): report never-evaluated candidates as skipped * feat(artwork): trace external agents at the gate seam * feat(artwork): add repository queries to enqueue by current source * feat(artwork): expose a tracing resolver for the CLI * feat(artwork): read a single queue row by item The explain CLI must report whether an item is queued, at what priority and when it retries; the queue repository could only be drained in eligibility batches, which cannot see a row that is still backing off. * feat(cli): add artwork explain Prints why an item has the artwork it has: the stored state, its queue row, the governing config, the resolver's priority-chain walk and the verdict. Offline by default so a diagnostic run cannot add load to an external provider; --live asks the agents for real. Playlists and radios do not walk a priority chain, so they report that instead of an empty chain table. * fix(artwork): trace an external tier that never reaches an agent A configured 'external' token vanished from the chain when no enabled agent provided images for that entity type, and for synthetic artists, leaving the trace unable to say whether the tier was even considered. * fix(cli): never state an artwork outcome the walk did not observe A transient external failure traced as 'error' fell through to 'not resolved', which is the most common state behind a missing-artwork report. It is now indeterminate, and an offline win that a skipped higher-priority external candidate could have taken says so instead of naming a winner the live chain might not pick. * feat(cli): add artwork refresh * feat(cli): add artwork reprocess Bulk re-enqueues artwork by kind and/or by the source an item currently resolves from, previewing the matched count and confirming before queueing. The preview counts with CountBySource (rows matched) and reports separately what EnqueueBySource inserted: its DO NOTHING conflict policy leaves an already-queued row untouched, so the two numbers differ and the output must not claim the skipped rows were re-queued. An unknown --source is rejected against the sources present in item_artwork, rather than silently matching nothing and printing a reassuring 0. * fix(cli): cover the reprocess selection rule and validate sources table-wide The reconciliation that makes --source alone target every kind was only exercised through runReprocess, which no test calls: mutating it to `all := reprocessAll` left the suite green. It is now reprocessSelectsAll, covered for all three selectors. Scoping source validation to the selected kinds made the same well-formed filter valid or invalid depending on which other kinds were selected, and its error read the same for a typo as for a source that simply does not apply to the chosen kind. Validation is now table-wide: a typo still aborts, while a valid-but-inapplicable source falls through to "Nothing matches". Also: the prompt now counts only the kinds that reach an external agent as external cost, and --dry-run on an empty selection reports a dry run. * fix(cli): cover the reprocess --yes guard and preview the external cost Mutating the --yes check to `if true` left the suite green, so the one bypass of the confirmation was unverified. The choice is now reprocessConfirm(yes, in), covered in both directions. The external estimate only reached the operator through the prompt, which --dry-run skips — hiding the number in the one mode that exists to show it before committing. The preview now carries it, and the prompt drops the clause when no lookup will be made. An empty selection says so again under --dry-run. * feat(artwork): add read-only queue and absent counters Both are needed by the artwork status CLI: a queue breakdown by kind and priority, and the absent totals split against the recheck cutoff. * feat(cli): add artwork status Reports the queue, where artwork currently resolves from, absent counts against the 24h recheck window, and the stored config fingerprint versus the current one — the line that turns 'why is my server re-resolving everything?' into one command. fingerprint() and staleAbsentAge are exported so the CLI reports the values backfill itself compares, instead of a second copy of the formula that can silently drift. * fix(cli): lead the artwork status backfill line with the queued backlog By the time anyone runs a diagnostic, backfill has usually already stored the new fingerprint, so 'up to date' was printed while thousands of items churned through external providers. The backlog is the finding; the fingerprint is context. Also echoes the config inputs the fingerprint covers, so a change can be traced to the setting that caused it, and pins the rendered rows: the Absent values, the queue TOTAL and a queue-scoped kind/priority pair were all unasserted, so kindName and priorityName were effectively untested. FingerprintInputs is now the single listing ConfigFingerprint hashes; a pinned hash proves the value did not change. * refactor(artwork): export the trace outcome vocabulary The CLI hardcoded the outcome literals and the "external:" prefix, so renaming a constant's value in core/artwork left cmd compiling and the suite green while `artwork explain` silently degraded its verdict. Renaming a value now fails the golden vocabulary test in core/artwork and the explainResult tests in cmd. * fix(cli): keep the re-enqueue warning when a backfill is already running A stale stored fingerprint with items already queued is the worst state the system can be in: a second full re-enqueue is pending on top of the one running. The line carried the weakest wording of the three, and was untested. * refactor(artwork): drop the unreachable breaker branch from the tracing gate --live wires the tracing gate straight to passthroughGate, so errBreakerOpen can never reach it; the test only passed by injecting a fake gate. * refactor(artwork): delete the never-emitted not-reached outcome Candidates after the winner are lower priority and say nothing about why a source won; the ones that matter sit above it and are already recorded. * refactor(artwork): make the trace nil-safe in one place only add already handles a nil trace, so record's own guard was dead; Steps was the odd one out and would panic where every other method tolerates nil. * refactor(artwork): export the trace types directly ChainTrace and TraceStep were unexported types re-exported through aliases, which existed only so the CLI had a name to refer to them by. The types are public API — Resolver.Steps returns []TraceStep and the CLI constructs a ChainTrace — so name them that way and drop the indirection. Encapsulation is unchanged: add, mu and steps stay unexported, so only this package can write a step. * refactor(cli): simplify parseArtworkKind with slices.Contains Replaces a nested loop and a manual append with slices.Contains and the repo's slice.Map helper. Same behaviour, same error message. * fix(cli): print the absent artwork source under the name --source accepts `artwork explain` rendered the stored empty source as "(absent)", while `artwork reprocess --source` only accepts "absent", so pasting what explain printed straight back into reprocess was rejected as an unknown source. * refactor(artwork): own the kind list and the chain predicate in the package Export RecheckKinds and add WalksPriorityChain so the CLI stops keeping its own copies of both, and unexport externalCandidate, which nothing outside the package consumes. * refactor(cli): drop the artwork command's duplicated state and formatting Reuse artwork.RecheckKinds and artwork.WalksPriorityChain, extract newTabWriter and externalEstimate, fold reprocessSelectsAll into selectedKinds, and derive the queue total and the walks-chain flag instead of carrying them in the report structs. * test(persistence): drop two artwork-queue specs that cannot fail One seeded hash and source together and then asserted the two counts agree, so its setup guaranteed the result; the other repeated the count-does-not- enqueue property already covered by the CountBySource spec. * refactor(artwork): rename Resolver to TracingResolver for clarity * fix(cli): count playlists in the artwork reprocess external estimate The estimate used WalksPriorityChain, which is true only for artist and album, so a playlist-only reprocess reported "External lookups: none" and the confirmation prompt dropped the external-cost warning. Playlists do reach the network: through the m3u ExternalImageURL fetch when EnableM3UExternalAlbumArt is on, and — verified by test — through the generated grid, whose tiles resolve album art via the full album priority chain. Adds artwork.MayFetchExternal, a config-aware predicate for "can this kind's resolver reach the network", and uses it for the estimate. WalksPriorityChain keeps its separate job of deciding whether explain prints a chain block. * fix(cli): estimate artwork reprocess external lookups per agent, not per item The reprocess prompt billed one external lookup per externally-capable item. fetchArtistImage/fetchAlbumImage try every enabled image agent and stop early only on a hit, and resolvePlaylist can fetch the m3u image and then resolve up to four sampled albums for the grid, each walking the album agents again. The number the operator confirmed could understate real provider traffic several fold, in the prompt whose whole job is to stop a provider flood. ExternalLookupsPerItem now multiplies by the visible image-agent count and adds the playlist grid factor. It stays a floor: the CLI never calls Manager.Start(), so the plugin registry is empty and plugin-provided agents are dropped by getEnabledAgentNames. On an install with 5 agents of which 3 are plugins the count is well under the truth, so the wording is now "at least N" rather than "up to N" — a zero visible count still bills one lookup for the same reason. Fixing the plugin visibility is out of scope: Manager.Start() needs a Subsonic router and writes to the DB via syncPlugins, breaking this command group's read-only guarantee. * fix(cli): state the artwork reprocess estimate as an estimate, not a bound Neither bound is true. A ceiling is false because plugin agents are invisible to a CLI that never starts the plugin manager, and a floor is false because a local hit ends the walk before any agent is asked and a hit on the first agent skips the rest. "at least N" traded one wrong claim for another. The line now names its blind spots instead: External lookups: ~340 estimated (plugin agents not counted; local hits may need fewer). The same line is reused in the confirmation prompt, and the zero case still reads "External lookups: none." with the prompt dropping the clause entirely. The count itself is unchanged. * fix(cli): account for every configured agent in artwork explain The Agents: line printed the raw config while the Chain only showed the agents the CLI could construct, with nothing explaining the gap: plugin agents are never registered in a CLI that does not start the plugin manager, and a built-in without credentials returns nil. Three of five agents could vanish, including ones ranked above the one shown. Also treat a live external error before the winning hit like the already-handled would-try case: the resolver serves such a hit provisionally and retries later, so the verdict is indeterminate. The Result line is still not qualified when an unavailable agent might have won; that needs agent ranking, and is left to the follow-up that makes the CLI load plugin agents for real. * fix(cli): do not call an external artwork win indeterminate explainResult qualified the verdict whenever an external OutcomeError appeared before the winning hit. When a later external agent returns an image, fetchArtistImage/fetchAlbumImage discard the earlier error, so extError is false: the worker settles the item and schedules no retry. Telling the operator it may resolve differently on a retry was wrong. The warning is only correct when a lower-priority local source won while an external error was recorded, which is the case that carries extError. * fix(cli): accept --source absent when nothing is currently absent validateSources checks the requested sources against the ones item_artwork actually uses, to catch a typo. The reserved empty source (spelled 'absent' on the CLI) is a valid filter even when it matches nothing, so a scheduled 'artwork reprocess --source absent --yes' stopped working the moment the library finished resolving. Treat it as intrinsically valid and let the existing zero-match path report it. * 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). * refactor(artwork): one disc-artwork walk for serving and explain resolveDisc duplicated the loop selectImageReader already ran: try each source in priority order, take the first that yields an image. The serving path and the CLI diverged on two details as a result — only selectImageReader checked ctx between candidates and logged each attempt. Both now call discArtworkReader.selectImage, which takes the chainState the CLI already uses for the other kinds. The serving path passes an untraced one, whose nil trace makes recording a no-op. selectImageReader had no other caller and is gone. The disc tests move from fromDiscArtPriority to discCandidates, so they assert the skip reason for an entry that maps to no source rather than that it silently vanished, and cancellation mid-walk is now covered. * fix(artwork): reject a nil reader in the resize cache instead of panicking resizedItem.Reader closes what open() hands back, so an open() that reports "no image" as (nil, nil) rather than an error takes the request down with a nil-pointer panic. Every caller returns an error today, and no test covered it: the resolution e2e harness stubs the resize reader out entirely, so no e2e path reaches this code at all. Guard it and cover Reader directly. * refactor(artwork): move the keeps-state fact into core, drop a redundant guard keepsArtworkState lived in package cmd and re-derived by hand what RefreshableKinds already encodes: the same five-of-six kinds. It is now artwork.KeepsState, beside the list, with a test pinning the two together — nothing else stopped them drifting, and a drift would have explain report stored state for a kind that keeps none. serveDisc's closure also hand-rolled a nil-reader error that both consumers of open() now produce themselves: serveSource for a full-size request, resizedItem.Reader for a resized one. * fix(artwork): route disc candidates through the shared resolvers openCandidate ran its own source loop and threw the error away, so a disc track that exists but cannot be parsed traced as "miss" — indistinguishable from a track with no embedded art. fromTag and fromFFmpegTag already report that case as errSourceUnreadable; only this loop was discarding it. Telling those two apart is what the trace is for. Candidates now carry a resolve func instead of raw sources: embedded goes to resolveEmbedded, and the folder-backed entries to resolveFolderSource, extracted from resolveFolderFile so both callers classify an unopenable file the same way. openCandidate and its absolute-path special case go away with it. Disc's own fromExternalFile and fromDiscSubtitle still swallow open errors, so folder candidates cannot report unreadable yet; that is a change to their error contracts. * fix(artwork): report an unreadable local candidate as indeterminate processor.acquire treats resolution.localError exactly as it treats extError: a fault is not a definitive "no image", so it retries instead of settling absent. explainResult qualified only the external case, so a chain that ended on an unreadable local candidate printed "not resolved" — the one verdict that says the walk was conclusive. The qualification belongs only to the unresolved branch. chainState.try stamps extErr onto a hit and deliberately drops localErr, so an unreadable step followed by a hit is settled as found and must not carry a warning; a test pins that. Found by Codex on 5f65d7cfa.
576 lines
19 KiB
Go
576 lines
19 KiB
Go
package artwork
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"image"
|
|
"io"
|
|
"io/fs"
|
|
"net/url"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/Masterminds/squirrel"
|
|
"github.com/navidrome/navidrome/conf"
|
|
"github.com/navidrome/navidrome/core/agents"
|
|
"github.com/navidrome/navidrome/core/ffmpeg"
|
|
"github.com/navidrome/navidrome/model"
|
|
)
|
|
|
|
// resolution is one attempted acquisition outcome for an entity.
|
|
type resolution struct {
|
|
reader io.ReadCloser // nil when no source yielded an image
|
|
source string // model.ItemArtwork.Source value: "folder", "embedded", "external", "upload", "generated"
|
|
sourcePath string // backing library/upload file (folder/upload: the image; embedded: the audio file); "" otherwise
|
|
refMtime int64 // sourcePath mtime (unix-nanoseconds) at resolution; 0 when no sourcePath
|
|
// external source errored/timed out. With no reader it forces failed (never absent);
|
|
// on a hit a higher-priority external step failed—serve this, but retry later.
|
|
extError bool
|
|
// a local source that should have been readable wasn't. With no reader it forces failed,
|
|
// so a transient I/O fault never records absent.
|
|
localError bool
|
|
}
|
|
|
|
// chainState carries what a priority walk has seen so far. A hit takes extErr with it so a
|
|
// transient external failure still retries; localErr is dropped, as the scanner re-lists changes.
|
|
type chainState struct {
|
|
extErr, localErr bool
|
|
trace *ChainTrace // nil unless the CLI asked for a trace
|
|
}
|
|
|
|
// try stamps the accumulated external failure onto a hit, and records the miss otherwise.
|
|
func (c *chainState) try(candidate string, res resolution, ok bool) (resolution, bool) {
|
|
if ok {
|
|
res.extError = c.extErr
|
|
c.record(candidate, OutcomeHit, res.sourcePath)
|
|
return res, true
|
|
}
|
|
c.localErr = c.localErr || res.localError
|
|
if res.localError {
|
|
c.record(candidate, OutcomeUnreadable, "")
|
|
} else {
|
|
c.record(candidate, OutcomeMiss, "")
|
|
}
|
|
return resolution{}, false
|
|
}
|
|
|
|
func (c *chainState) record(candidate string, out Outcome, detail string) {
|
|
c.trace.add(TraceStep{Candidate: candidate, Outcome: out, Detail: detail})
|
|
}
|
|
|
|
// exhausted is the outcome when no source in the chain yielded an image.
|
|
func (c *chainState) exhausted() resolution {
|
|
return resolution{extError: c.extErr, localError: c.localErr}
|
|
}
|
|
|
|
// externalSource holds the agents to ask and the rate limiter/circuit breaker to ask them through.
|
|
type externalSource struct {
|
|
agents *agents.Agents
|
|
gate gateFunc
|
|
}
|
|
|
|
// resolver walks a kind's priority chain and returns the first hit; a nil ext means local-only.
|
|
type resolver struct {
|
|
ds model.DataStore
|
|
ffmpeg ffmpeg.FFmpeg
|
|
ext *externalSource
|
|
}
|
|
|
|
func newResolver(ds model.DataStore, ag *agents.Agents, ffm ffmpeg.FFmpeg, gate gateFunc) *resolver {
|
|
if gate == nil {
|
|
gate = passthroughGate
|
|
}
|
|
return &resolver{ds: ds, ffmpeg: ffm, ext: &externalSource{agents: ag, gate: gate}}
|
|
}
|
|
|
|
// newLocalResolver builds a resolver that can neither reach the network nor sample album art
|
|
// for the worker-built grid.
|
|
func newLocalResolver(ds model.DataStore, ffm ffmpeg.FFmpeg) *resolver {
|
|
return &resolver{ds: ds, ffmpeg: ffm}
|
|
}
|
|
|
|
func (r *resolver) resolve(ctx context.Context, item model.ArtworkQueueItem) (resolution, error) {
|
|
kind, _ := model.ParseKind(item.ItemKind)
|
|
switch kind {
|
|
case model.KindAlbumArtwork:
|
|
return r.resolveAlbum(ctx, item.ItemID)
|
|
case model.KindArtistArtwork:
|
|
return r.resolveArtist(ctx, item.ItemID)
|
|
case model.KindPlaylistArtwork:
|
|
return r.resolvePlaylist(ctx, item.ItemID)
|
|
case model.KindRadioArtwork:
|
|
return r.resolveRadio(ctx, item.ItemID)
|
|
case model.KindMediaFileArtwork:
|
|
return r.resolveMediaFile(ctx, item.ItemID)
|
|
default:
|
|
return resolution{}, fmt.Errorf("artwork: kind %q is not resolvable by the worker", item.ItemKind)
|
|
}
|
|
}
|
|
|
|
// 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
|
|
// current config. Playlists inherit the album chain: the generated grid resolves album art.
|
|
func MayFetchExternal(kind model.Kind) bool {
|
|
switch kind {
|
|
case model.KindArtistArtwork:
|
|
return chainFetchesExternal(conf.Server.ArtistArtPriority)
|
|
case model.KindAlbumArtwork:
|
|
return chainFetchesExternal(conf.Server.CoverArtPriority)
|
|
case model.KindPlaylistArtwork:
|
|
return conf.Server.EnableM3UExternalAlbumArt || chainFetchesExternal(conf.Server.CoverArtPriority)
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
// ImageAgentCount is how many enabled agents provide artist and album images.
|
|
type ImageAgentCount struct{ Artist, Album int }
|
|
|
|
// ExternalLookupsPerItem reports what resolving one item of this kind can cost: every image agent is
|
|
// tried, and a zero count still bills one, so agents the caller cannot see never read as free.
|
|
func ExternalLookupsPerItem(kind model.Kind, agents ImageAgentCount) int64 {
|
|
if !MayFetchExternal(kind) {
|
|
return 0
|
|
}
|
|
switch kind {
|
|
case model.KindArtistArtwork:
|
|
return int64(max(agents.Artist, 1))
|
|
case model.KindAlbumArtwork:
|
|
return int64(max(agents.Album, 1))
|
|
case model.KindPlaylistArtwork:
|
|
var n int64
|
|
if conf.Server.EnableM3UExternalAlbumArt {
|
|
n++
|
|
}
|
|
if chainFetchesExternal(conf.Server.CoverArtPriority) {
|
|
n += PlaylistGridSamples * int64(max(agents.Album, 1))
|
|
}
|
|
return n
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func chainFetchesExternal(priority string) bool {
|
|
for pattern := range strings.SplitSeq(strings.ToLower(priority), ",") {
|
|
if strings.TrimSpace(pattern) == externalCandidate {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Album and artist fetches stop here when the resolver is local-only, rather than at each point in
|
|
// the chain walk; resolvePlaylist gates the third network path, the m3u image URL, itself.
|
|
func (r *resolver) fetchExternalAlbum(ctx context.Context, al model.Album) (io.ReadCloser, string, bool) {
|
|
if r.ext == nil {
|
|
return nil, "", false
|
|
}
|
|
return fetchAlbumImage(ctx, r.ext.agents, r.ext.gate, al)
|
|
}
|
|
|
|
func (r *resolver) fetchExternalArtist(ctx context.Context, ar model.Artist) (io.ReadCloser, string, bool) {
|
|
if r.ext == nil {
|
|
return nil, "", false
|
|
}
|
|
return fetchArtistImage(ctx, r.ext.agents, r.ext.gate, ar)
|
|
}
|
|
|
|
// resolveAlbum walks conf.Server.CoverArtPriority over the folder, embedded and external sources.
|
|
func (r *resolver) resolveAlbum(ctx context.Context, albumID string) (resolution, error) {
|
|
al, err := r.ds.Album(ctx).Get(albumID)
|
|
if err != nil {
|
|
return resolution{}, err
|
|
}
|
|
_, imgFiles, _, err := loadAlbumFoldersPaths(ctx, r.ds, *al)
|
|
if err != nil {
|
|
return resolution{}, err
|
|
}
|
|
lib, err := loadLibraryView(ctx, r.ds, al.LibraryID)
|
|
if err != nil {
|
|
return resolution{}, err
|
|
}
|
|
|
|
chain := chainState{trace: traceFrom(ctx)}
|
|
for pattern := range strings.SplitSeq(strings.ToLower(conf.Server.CoverArtPriority), ",") {
|
|
pattern = strings.TrimSpace(pattern)
|
|
if pattern == "" {
|
|
continue
|
|
}
|
|
switch {
|
|
case pattern == "embedded":
|
|
res, ok := resolveEmbedded(ctx, lib, r.ffmpeg, al.EmbedArtPath)
|
|
if res, ok = chain.try(pattern, res, ok); ok {
|
|
return res, nil
|
|
}
|
|
case pattern == externalCandidate:
|
|
if rd, name, isErr := r.fetchExternalAlbum(ctx, *al); rd != nil {
|
|
return resolution{reader: rd, source: ExternalPrefix + name}, nil
|
|
} else if isErr {
|
|
chain.extErr = true
|
|
}
|
|
case len(imgFiles) > 0:
|
|
res, ok := resolveFolderFile(ctx, lib, imgFiles, pattern)
|
|
if res, ok = chain.try(pattern, res, ok); ok {
|
|
return res, nil
|
|
}
|
|
default:
|
|
chain.record(pattern, OutcomeSkipped, "no images in album folder")
|
|
}
|
|
}
|
|
return chain.exhausted(), nil
|
|
}
|
|
|
|
// resolveArtist tries the uploaded image first, then walks conf.Server.ArtistArtPriority.
|
|
func (r *resolver) resolveArtist(ctx context.Context, artistID string) (resolution, error) {
|
|
ar, err := r.ds.Artist(ctx).Get(artistID)
|
|
if err != nil {
|
|
return resolution{}, err
|
|
}
|
|
chain := chainState{trace: traceFrom(ctx)}
|
|
upload, uploadOK := resolveLocalFile(ar.UploadedImagePath(), "upload")
|
|
if res, ok := chain.try("upload", upload, uploadOK); ok {
|
|
return res, nil
|
|
}
|
|
if upload.localError {
|
|
// The upload outranks every other source; falling through would persist a lower-priority
|
|
// image as if the upload were gone.
|
|
return upload, nil
|
|
}
|
|
|
|
// Only consider albums where the artist is the sole album artist.
|
|
als, err := r.ds.Album(ctx).GetAll(model.QueryOptions{
|
|
Filters: squirrel.And{
|
|
squirrel.Eq{"album_artist_id": artistID},
|
|
squirrel.Eq{"json_array_length(participants, '$.albumartist')": 1},
|
|
},
|
|
})
|
|
if err != nil {
|
|
return resolution{}, err
|
|
}
|
|
albumPaths, imgFiles, _, err := loadArtistAlbumRoots(ctx, r.ds, als)
|
|
if err != nil {
|
|
return resolution{}, err
|
|
}
|
|
artistFolder, _, err := loadArtistFolder(ctx, r.ds, als, albumPaths)
|
|
if err != nil {
|
|
return resolution{}, err
|
|
}
|
|
var lib libraryView
|
|
if len(als) > 0 {
|
|
lib, err = loadLibraryView(ctx, r.ds, als[0].LibraryID)
|
|
if err != nil {
|
|
return resolution{}, err
|
|
}
|
|
}
|
|
|
|
for pattern := range strings.SplitSeq(strings.ToLower(conf.Server.ArtistArtPriority), ",") {
|
|
pattern = strings.TrimSpace(pattern)
|
|
if pattern == "" {
|
|
continue
|
|
}
|
|
switch {
|
|
case pattern == externalCandidate:
|
|
if rd, name, isErr := r.fetchExternalArtist(ctx, *ar); rd != nil {
|
|
return resolution{reader: rd, source: ExternalPrefix + name}, nil
|
|
} else if isErr {
|
|
chain.extErr = true
|
|
}
|
|
case pattern == "image-folder":
|
|
res, ok := resolveArtistImageFolder(ar)
|
|
if res, ok = chain.try(pattern, res, ok); ok {
|
|
return res, nil
|
|
}
|
|
case strings.HasPrefix(pattern, "album/"):
|
|
if lib.FS == nil {
|
|
chain.record(pattern, OutcomeSkipped, "artist has no albums")
|
|
continue
|
|
}
|
|
res, ok := resolveFolderFile(ctx, lib, imgFiles, strings.TrimPrefix(pattern, "album/"))
|
|
if res, ok = chain.try(pattern, res, ok); ok {
|
|
return res, nil
|
|
}
|
|
default:
|
|
if lib.FS == nil {
|
|
chain.record(pattern, OutcomeSkipped, "artist has no albums")
|
|
continue
|
|
}
|
|
if artistFolder == "" {
|
|
chain.record(pattern, OutcomeSkipped, "no artist folder")
|
|
continue
|
|
}
|
|
res, ok := resolveArtistFolderPattern(ctx, lib, artistFolder, pattern)
|
|
if res, ok = chain.try(pattern, res, ok); ok {
|
|
return res, nil
|
|
}
|
|
}
|
|
}
|
|
return chain.exhausted(), nil
|
|
}
|
|
|
|
// PlaylistGridSamples is how many albums resolvePlaylist samples to build the generated grid.
|
|
const PlaylistGridSamples = 4
|
|
|
|
// resolvePlaylist tries the uploaded image, the sidecar and ExternalImageURL, then a generated grid.
|
|
func (r *resolver) resolvePlaylist(ctx context.Context, playlistID string) (resolution, error) {
|
|
pl, err := r.ds.Playlist(ctx).Get(playlistID)
|
|
if err != nil {
|
|
return resolution{}, err
|
|
}
|
|
|
|
var extErr bool
|
|
for _, src := range []struct{ path, source string }{
|
|
{pl.UploadedImagePath(), "upload"},
|
|
{findPlaylistSidecarPath(ctx, pl.Path), "folder"},
|
|
} {
|
|
res, ok := resolveLocalFile(src.path, src.source)
|
|
if ok {
|
|
return res, nil
|
|
}
|
|
if res.localError {
|
|
// These outrank the generated grid; falling through would replace them with it.
|
|
return res, nil
|
|
}
|
|
}
|
|
// A local ExternalImageURL is file-backed and served in place; only http(s) needs the gated fetch.
|
|
localImg, remoteImg := classifyPlaylistImage(pl.ExternalImageURL)
|
|
if localImg != "" {
|
|
res, ok := resolveLocalFile(localImg, "folder")
|
|
if ok {
|
|
return res, nil
|
|
}
|
|
if res.localError {
|
|
return res, nil
|
|
}
|
|
}
|
|
if r.ext == nil {
|
|
// The remote fetch and the generated grid are worker-only; a request must do neither.
|
|
return resolution{}, nil
|
|
}
|
|
if remoteImg != nil && conf.Server.EnableM3UExternalAlbumArt {
|
|
sf := func() (io.ReadCloser, string, error) { return fromURL(ctx, remoteImg) }
|
|
if res, ok, isErr := resolveExternalStep(r.ext.gate, "m3u", sf); ok {
|
|
return res, nil
|
|
} else if isErr {
|
|
extErr = true
|
|
}
|
|
}
|
|
|
|
albumIDs, err := r.ds.Playlist(ctx).Tracks(pl.ID, false).
|
|
GetAlbumIDs(model.QueryOptions{Max: PlaylistGridSamples, Sort: "random()"})
|
|
if err != nil {
|
|
return resolution{}, err
|
|
}
|
|
|
|
var tiles []image.Image
|
|
var tileErr error // first internal (non-external) tile failure, e.g. album deleted mid-flight
|
|
for _, albumID := range albumIDs {
|
|
res, err := r.resolveAlbum(ctx, albumID)
|
|
if err != nil {
|
|
if tileErr == nil {
|
|
tileErr = err
|
|
}
|
|
continue
|
|
}
|
|
if res.extError {
|
|
extErr = true
|
|
}
|
|
if res.reader == nil {
|
|
continue
|
|
}
|
|
tile, decErr := decodeTile(res.reader)
|
|
res.reader.Close()
|
|
if decErr == nil {
|
|
tiles = append(tiles, tile)
|
|
}
|
|
if len(tiles) == PlaylistGridSamples {
|
|
break
|
|
}
|
|
}
|
|
if len(tiles) == 0 {
|
|
// A tile-level failure must never resolve as a clean absent.
|
|
if tileErr != nil {
|
|
return resolution{}, fmt.Errorf("resolvePlaylist: sampled album art failed: %w", tileErr)
|
|
}
|
|
return resolution{extError: extErr}, nil
|
|
}
|
|
// Grow to 4 tiles by repeating what we have.
|
|
switch len(tiles) {
|
|
case 2:
|
|
tiles = append(tiles, tiles[1], tiles[0])
|
|
case 3:
|
|
tiles = append(tiles, tiles[0])
|
|
}
|
|
grid, err := assembleTiles(tiles)
|
|
if err != nil {
|
|
return resolution{extError: extErr}, nil //nolint:nilerr // encode failure is a soft "no image", not a resolution error
|
|
}
|
|
return resolution{reader: grid, source: "generated", extError: extErr}, nil
|
|
}
|
|
|
|
// resolveRadio serves only an uploaded image; there is no fallback.
|
|
func (r *resolver) resolveRadio(ctx context.Context, radioID string) (resolution, error) {
|
|
radio, err := r.ds.Radio(ctx).Get(radioID)
|
|
if err != nil {
|
|
return resolution{}, err
|
|
}
|
|
res, _ := resolveLocalFile(radio.UploadedImagePath(), "upload")
|
|
return res, nil
|
|
}
|
|
|
|
// resolveMediaFile resolves a track's own embedded art only, so disabled or missing cover art
|
|
// is a definitive absent.
|
|
func (r *resolver) resolveMediaFile(ctx context.Context, id string) (resolution, error) {
|
|
mf, err := r.ds.MediaFile(ctx).Get(id)
|
|
if err != nil {
|
|
return resolution{}, err
|
|
}
|
|
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, 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)}
|
|
return dr.selectImage(ctx, r.ffmpeg, conf.Server.DiscArtPriority, &chain)
|
|
}
|
|
|
|
// resolveExternalStep runs a single external sourceFunc through the named gate. extErr excludes
|
|
// a not-found, which is a definitive "no" rather than a failure.
|
|
func resolveExternalStep(gate gateFunc, name string, sf sourceFunc) (res resolution, ok bool, extErr bool) {
|
|
r, path, err := gate(name, sf)
|
|
if r != nil {
|
|
return resolution{reader: r, source: externalCandidate, sourcePath: path}, true, false
|
|
}
|
|
return resolution{}, false, err != nil && !errors.Is(err, model.ErrNotFound)
|
|
}
|
|
|
|
// classifyPlaylistImage splits a playlist ExternalImageURL into a local filesystem path or a
|
|
// remote http(s) URL; at most one is set.
|
|
func classifyPlaylistImage(imageURL string) (localPath string, remote *url.URL) {
|
|
if imageURL == "" {
|
|
return "", nil
|
|
}
|
|
u, err := url.Parse(imageURL)
|
|
if err != nil {
|
|
return imageURL, nil // unparseable → treat as a local path
|
|
}
|
|
switch u.Scheme {
|
|
case "http", "https":
|
|
return "", u
|
|
case "file":
|
|
return u.Path, nil
|
|
default:
|
|
return imageURL, nil
|
|
}
|
|
}
|
|
|
|
func resolveEmbedded(ctx context.Context, lib libraryView, ffm ffmpeg.FFmpeg, embedRel string) (resolution, bool) {
|
|
if embedRel == "" {
|
|
return resolution{}, false
|
|
}
|
|
abs := lib.Abs(embedRel)
|
|
var unreadable bool
|
|
for _, sf := range []sourceFunc{fromTag(ctx, lib.FS, embedRel), fromFFmpegTag(ctx, ffm, abs)} {
|
|
r, _, err := sf()
|
|
if r != nil {
|
|
return resolution{reader: r, source: "embedded", sourcePath: abs, refMtime: mtimeViaFS(lib.FS, embedRel)}, true
|
|
}
|
|
unreadable = unreadable || errors.Is(err, errSourceUnreadable)
|
|
}
|
|
return resolution{localError: unreadable}, false
|
|
}
|
|
|
|
// resolveFolderSource turns a source that yields a library-relative image path into a folder
|
|
// resolution, keeping an existing-but-unopenable file distinct from an absent one.
|
|
func resolveFolderSource(lib libraryView, sf sourceFunc) (resolution, bool) {
|
|
r, path, err := sf()
|
|
if r == nil {
|
|
return resolution{localError: errors.Is(err, errSourceUnreadable)}, false
|
|
}
|
|
return resolution{reader: r, source: "folder", sourcePath: lib.Abs(path), refMtime: mtimeViaFS(lib.FS, path)}, true
|
|
}
|
|
|
|
func resolveFolderFile(ctx context.Context, lib libraryView, imgFiles []string, pattern string) (resolution, bool) {
|
|
return resolveFolderSource(lib, fromExternalFile(ctx, lib.FS, imgFiles, pattern))
|
|
}
|
|
|
|
func resolveArtistImageFolder(ar *model.Artist) (resolution, bool) {
|
|
folder := conf.Server.ArtistImageFolder
|
|
if folder == "" {
|
|
return resolution{}, false
|
|
}
|
|
return resolveLocalFile(findImageInArtistFolder(folder, ar.MbzArtistID, ar.Name), "folder")
|
|
}
|
|
|
|
func resolveArtistFolderPattern(ctx context.Context, lib libraryView, artistFolder, pattern string) (resolution, bool) {
|
|
r, path, err := fromArtistFolder(ctx, lib.FS, lib.absRoot, artistFolder, pattern)()
|
|
if r == nil {
|
|
return resolution{localError: errors.Is(err, errSourceUnreadable)}, false
|
|
}
|
|
return resolution{reader: r, source: "folder", sourcePath: path, refMtime: mtimeOf(path)}, true
|
|
}
|
|
|
|
// resolveLocalFile opens an absolute path directly. A missing path is "no source"; any other
|
|
// open failure says nothing about whether the image exists.
|
|
func resolveLocalFile(path, source string) (resolution, bool) {
|
|
if path == "" {
|
|
return resolution{}, false
|
|
}
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return resolution{localError: !errors.Is(err, fs.ErrNotExist)}, false
|
|
}
|
|
return resolution{reader: f, source: source, sourcePath: path, refMtime: mtimeOf(path)}, true
|
|
}
|
|
|
|
func mtimeOf(path string) int64 {
|
|
info, err := os.Stat(path)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
return info.ModTime().UnixNano()
|
|
}
|
|
|
|
// mtimeViaFS stats through the library FS, since library roots in tests may not be real OS paths.
|
|
func mtimeViaFS(fsys fs.FS, name string) int64 {
|
|
if fsys == nil || name == "" {
|
|
return 0
|
|
}
|
|
info, err := fs.Stat(fsys, name)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
return info.ModTime().UnixNano()
|
|
}
|