mirror of
https://github.com/navidrome/navidrome.git
synced 2026-11-15 22:58:40 +01:00
Compare commits
16 commits
master
...
artwork-ex
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a76b13c39c | ||
|
|
59971d3eb6 | ||
|
|
71a1b3b5bd |
||
|
|
8ba8e7f2d7 | ||
|
|
f283da0630 | ||
|
|
fd46e594e1 | ||
|
|
687646809f | ||
|
|
eadbb442a8 | ||
|
|
e7f7e7bde9 | ||
|
|
d17ef212ab | ||
|
|
0fcce273a2 | ||
|
|
395f2f9ae5 | ||
|
|
b8c7f3cd2b | ||
|
|
03743a030b | ||
|
|
0ab549e1b2 | ||
|
|
3290759e62 |
79 changed files with 1721 additions and 1292 deletions
|
|
@ -388,11 +388,10 @@ func (l *lastfmAgent) Scrobble(ctx context.Context, userId string, s scrobbler.S
|
|||
return errors.Join(err, scrobbler.ErrNotAuthorized)
|
||||
}
|
||||
|
||||
if s.Duration <= float32(conf.Server().LastFM.MinScrobbleDuration.Seconds()) {
|
||||
if s.Duration <= 30 {
|
||||
log.Debug(ctx, "Skipping Last.fm scrobble for short song", "track", s.Title, "duration", s.Duration)
|
||||
return nil
|
||||
}
|
||||
|
||||
err = l.client.scrobble(ctx, sk, ScrobbleInfo{
|
||||
artist: l.getArtistForScrobble(&s.MediaFile, model.RoleArtist, s.Artist),
|
||||
track: s.Title,
|
||||
|
|
|
|||
|
|
@ -471,54 +471,14 @@ var _ = Describe("lastfmAgent", func() {
|
|||
})
|
||||
})
|
||||
|
||||
It("skips songs at the 30-second minimum", func() {
|
||||
track.Duration = 30
|
||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
||||
|
||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest).To(BeNil())
|
||||
})
|
||||
|
||||
It("sends the duration parameter for a 30.5-second song", func() {
|
||||
track.Duration = 30.5
|
||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"scrobbles":{"scrobble":{"ignoredMessage":{"code":"0"}},"@attr":{"accepted":1}}}`)), StatusCode: 200}
|
||||
|
||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
body, _ := io.ReadAll(httpClient.SavedRequest.Body)
|
||||
sentParams, _ := url.ParseQuery(string(body))
|
||||
Expect(sentParams.Has("duration")).To(BeTrue())
|
||||
Expect(sentParams.Get("duration")).To(Equal("30"))
|
||||
})
|
||||
|
||||
It("skips songs according to the configured minimum duration", func() {
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 60 * time.Second })
|
||||
track.Duration = 59
|
||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
||||
|
||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest).To(BeNil())
|
||||
})
|
||||
|
||||
It("does not skip short songs when the minimum duration is disabled", func() {
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 0 })
|
||||
It("skips songs with less than 31 seconds", func() {
|
||||
track.Duration = 29
|
||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
||||
|
||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest).ToNot(BeNil())
|
||||
|
||||
body, _ := io.ReadAll(httpClient.SavedRequest.Body)
|
||||
sentParams, _ := url.ParseQuery(string(body))
|
||||
Expect(sentParams.Has("duration")).To(BeFalse())
|
||||
Expect(httpClient.SavedRequest).To(BeNil())
|
||||
})
|
||||
|
||||
It("returns ErrNotAuthorized if user is not linked", func() {
|
||||
|
|
|
|||
|
|
@ -182,14 +182,7 @@ func (c *client) scrobble(ctx context.Context, sessionKey string, info ScrobbleI
|
|||
params.Add("album", info.album)
|
||||
params.Add("trackNumber", strconv.Itoa(info.trackNumber))
|
||||
params.Add("mbid", info.mbid)
|
||||
|
||||
// Last.fm requires a minimum duration of 30 seconds to scrobble a track. To circumvent this, only send the duration if it is greater than or equal to 30 seconds.
|
||||
if info.duration >= 30 {
|
||||
params.Add("duration", strconv.Itoa(info.duration))
|
||||
} else {
|
||||
log.Debug(ctx, "LastFM: scrobble duration is less than 30 seconds, duration will not be transmitted", "duration", info.duration)
|
||||
}
|
||||
|
||||
params.Add("duration", strconv.Itoa(info.duration))
|
||||
params.Add("albumArtist", info.albumArtist)
|
||||
params.Add("sk", sessionKey)
|
||||
resp, err := c.makeRequest(ctx, http.MethodPost, params, true)
|
||||
|
|
|
|||
276
cmd/artwork.go
276
cmd/artwork.go
|
|
@ -8,9 +8,7 @@ import (
|
|||
"io"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
|
|
@ -76,7 +74,7 @@ var artworkExplainCmd = &cobra.Command{
|
|||
Short: "Explain why an item's artwork resolved the way it did",
|
||||
Long: "Explain why an item's artwork resolved the way it did.\n\n" +
|
||||
"The item can be given as a bare id, a full artwork id (e.g. al-<id>), or a <kind> <id> pair.\n" +
|
||||
"<kind> is one of: " + kindPrefixes(explainKinds) + ".\n" +
|
||||
"<kind> is one of: " + kindPrefixes(artwork.ExplainKinds) + ".\n" +
|
||||
"A disc artwork id is the album id and the disc number, joined by a colon: <albumID>:2",
|
||||
Args: cobra.RangeArgs(1, 2),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
|
|
@ -264,7 +262,7 @@ func configState(rep statusReport) string {
|
|||
func printQueueStats(w io.Writer, stats []model.ArtworkQueueStat, total int64, countHeader, indent string) {
|
||||
fmt.Fprintf(w, "%sKIND\tPRIORITY\t%s\n", indent, countHeader)
|
||||
for _, s := range stats {
|
||||
fmt.Fprintf(w, "%s%s\t%s\t%d\n", indent, kindName(s.ItemKind), priorityName(s.Priority), s.Count)
|
||||
fmt.Fprintf(w, "%s%s\t%s\t%d\n", indent, kindName(s.ItemKind), artwork.PriorityName(s.Priority), s.Count)
|
||||
}
|
||||
fmt.Fprintf(w, "%sTOTAL\t\t%d\n", indent, total)
|
||||
}
|
||||
|
|
@ -276,37 +274,14 @@ func kindName(prefix string) string {
|
|||
return prefix
|
||||
}
|
||||
|
||||
type artworkPriority struct {
|
||||
name string
|
||||
value int
|
||||
}
|
||||
|
||||
// knownPriorities is the one listing behind both the name and the parse, so they cannot drift.
|
||||
var knownPriorities = []artworkPriority{
|
||||
{"bump", model.ArtworkPriorityBump},
|
||||
{"scan", model.ArtworkPriorityScan},
|
||||
{"recheck", model.ArtworkPriorityRecheck},
|
||||
{"backfill", model.ArtworkPriorityBackfill},
|
||||
}
|
||||
|
||||
// priorityName falls back to the number: a row written by a newer version still has to print.
|
||||
func priorityName(p int) string {
|
||||
for _, ap := range knownPriorities {
|
||||
if ap.value == p {
|
||||
return ap.name
|
||||
}
|
||||
}
|
||||
return strconv.Itoa(p)
|
||||
}
|
||||
|
||||
func priorityNames() string {
|
||||
return strings.Join(slice.Map(knownPriorities, func(ap artworkPriority) string { return ap.name }), ", ")
|
||||
return strings.Join(slice.Map(artwork.KnownPriorities, func(ap artwork.Priority) string { return ap.Name }), ", ")
|
||||
}
|
||||
|
||||
func parseArtworkPriority(s string) (int, error) {
|
||||
for _, ap := range knownPriorities {
|
||||
if ap.name == s {
|
||||
return ap.value, nil
|
||||
for _, ap := range artwork.KnownPriorities {
|
||||
if ap.Name == s {
|
||||
return ap.Value, nil
|
||||
}
|
||||
}
|
||||
return 0, fmt.Errorf("invalid priority %q, expected one of: %s", s, priorityNames())
|
||||
|
|
@ -678,13 +653,6 @@ func refreshItems(ctx context.Context, ds model.DataStore, targets []model.Artwo
|
|||
return failed
|
||||
}
|
||||
|
||||
// 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(model.KindPrefixes(kinds), ", ")
|
||||
}
|
||||
|
|
@ -746,106 +714,15 @@ func artworkKindAndID(ctx context.Context, ds model.DataStore, arg string) (mode
|
|||
return model.ArtworkID{Kind: kind, ID: arg}, nil
|
||||
}
|
||||
|
||||
// explainAgents accounts for every configured agent: one the CLI cannot construct (a plugin, or a
|
||||
// built-in missing its credentials) never reaches the Chain, so the raw list alone overstates it.
|
||||
func explainAgents(configured string, available []string) string {
|
||||
if strings.TrimSpace(configured) == "" {
|
||||
return "(none)"
|
||||
}
|
||||
var unavailable bool
|
||||
names := slice.Map(strings.Split(configured, ","), func(name string) string {
|
||||
name = strings.TrimSpace(name)
|
||||
if slices.Contains(available, name) {
|
||||
return name
|
||||
}
|
||||
unavailable = true
|
||||
return name + "*"
|
||||
})
|
||||
line := strings.Join(names, ", ")
|
||||
if unavailable {
|
||||
line += " (* not available to the CLI)"
|
||||
}
|
||||
return line
|
||||
}
|
||||
// cliUnavailableNote marks agents the CLI cannot construct; a running server loads them all.
|
||||
const cliUnavailableNote = " (* not available to the CLI)"
|
||||
|
||||
// availableImageAgents names the agents that can actually supply an image for kind.
|
||||
func availableImageAgents(ds model.DataStore, mgr *plugins.Manager, kind model.Kind) []string {
|
||||
ag := agents.GetAgents(ds, mgr)
|
||||
if kind == model.KindArtistArtwork {
|
||||
return slice.Map(ag.ArtistImageAgents(), func(a agents.ArtistImageAgent) string { return a.Name })
|
||||
// cliAgents words the CLI's own legend for the starred agents FormatAgents reports.
|
||||
func cliAgents(rep artwork.ExplainReport) string {
|
||||
if rep.AgentsIncomplete {
|
||||
return rep.Agents + cliUnavailableNote
|
||||
}
|
||||
return slice.Map(ag.AlbumImageAgents(), func(a agents.AlbumImageAgent) string { return a.Name })
|
||||
}
|
||||
|
||||
// explainResult states the verdict of the walk. A skipped or failed external tier, or a local
|
||||
// candidate that would not open, leaves the outcome unknown: nothing observed that there is no artwork.
|
||||
func explainResult(source string, steps []artwork.TraceStep) string {
|
||||
if source != "" {
|
||||
for _, s := range steps {
|
||||
if s.Outcome == artwork.OutcomeHit {
|
||||
break
|
||||
}
|
||||
// An external winner discards the earlier error, so the resolver settles it with no retry.
|
||||
if s.Outcome == artwork.OutcomeError && strings.HasPrefix(s.Candidate, artwork.ExternalPrefix) &&
|
||||
!strings.HasPrefix(source, artwork.ExternalPrefix) {
|
||||
return "resolved from " + source +
|
||||
" (indeterminate: a higher-priority external lookup failed; this may resolve differently on a retry)"
|
||||
}
|
||||
}
|
||||
return "resolved from " + source
|
||||
}
|
||||
for _, s := range steps {
|
||||
switch {
|
||||
case s.Outcome == artwork.OutcomeError && strings.HasPrefix(s.Candidate, artwork.ExternalPrefix):
|
||||
return "indeterminate (an external lookup failed; the item may resolve on a later attempt)"
|
||||
// A stage error or an unreadable candidate means a source was found but not processed; the
|
||||
// worker retries rather than settling absent, so neither reads as a clean miss.
|
||||
case s.Outcome == artwork.OutcomeError, s.Outcome == artwork.OutcomeUnreadable:
|
||||
return "indeterminate (a candidate was found but could not be processed; the worker retries rather than settling absent)"
|
||||
}
|
||||
}
|
||||
return "not resolved"
|
||||
}
|
||||
|
||||
// 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
|
||||
agents string
|
||||
// steps is the chain walk: recorded when the item was resolved, or performed just now when walked.
|
||||
steps []artwork.TraceStep
|
||||
source string
|
||||
walked bool
|
||||
resolveErr error
|
||||
}
|
||||
|
||||
// explainChainOrigin says whether the operator is reading history or a walk performed just now,
|
||||
// since the two can disagree after a config change.
|
||||
func explainChainOrigin(rep explainReport) string {
|
||||
if rep.walked {
|
||||
return "walked now"
|
||||
}
|
||||
if rep.stored != nil {
|
||||
return "recorded " + formatTime(rep.stored.AttemptedAt)
|
||||
}
|
||||
return "not recorded"
|
||||
return rep.Agents
|
||||
}
|
||||
|
||||
// writeSteps prints the trace rows. An empty last cell would end tabwriter's column block and
|
||||
|
|
@ -866,107 +743,100 @@ func writeStepTable(w io.Writer, title string, steps []artwork.TraceStep) {
|
|||
writeSteps(w, " ", steps)
|
||||
}
|
||||
|
||||
func formatExplain(rep explainReport) string {
|
||||
func formatExplain(rep artwork.ExplainReport) string {
|
||||
var sb strings.Builder
|
||||
w := newTabWriter(&sb)
|
||||
explainable := artwork.Explainable(rep.kind)
|
||||
stateful := artwork.KeepsState(rep.kind)
|
||||
unrecorded := !rep.walked && rep.stored == nil
|
||||
explainable := artwork.Explainable(rep.Kind)
|
||||
stateful := artwork.KeepsState(rep.Kind)
|
||||
unrecorded := !rep.Walked && rep.Stored == nil
|
||||
|
||||
fmt.Fprintln(w, "Item")
|
||||
fmt.Fprintf(w, " Kind:\t%s (%s)\n", rep.kind, rep.kind.Prefix())
|
||||
fmt.Fprintf(w, " ID:\t%s\n", rep.id)
|
||||
fmt.Fprintf(w, " Name:\t%s\n", rep.name)
|
||||
fmt.Fprintf(w, " Kind:\t%s (%s)\n", rep.Kind, rep.Kind.Prefix())
|
||||
fmt.Fprintf(w, " ID:\t%s\n", rep.ID)
|
||||
fmt.Fprintf(w, " Name:\t%s\n", rep.Name)
|
||||
|
||||
fmt.Fprintln(w, "\nStored")
|
||||
switch {
|
||||
case !stateful:
|
||||
fmt.Fprintf(w, " (%s artwork is resolved on every request and never recorded)\n", rep.kind)
|
||||
case rep.stored == nil:
|
||||
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)")
|
||||
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 != "" {
|
||||
fmt.Fprintf(w, " Source path:\t%s\n", rep.stored.SourcePath)
|
||||
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 != "" {
|
||||
fmt.Fprintf(w, " Source path:\t%s\n", rep.Stored.SourcePath)
|
||||
}
|
||||
fmt.Fprintf(w, " Attempted at:\t%s\n", formatTime(rep.stored.AttemptedAt))
|
||||
fmt.Fprintf(w, " Attempted at:\t%s\n", artwork.FormatTime(rep.Stored.AttemptedAt))
|
||||
}
|
||||
|
||||
fmt.Fprintln(w, "\nQueue")
|
||||
switch {
|
||||
case !stateful:
|
||||
fmt.Fprintln(w, " (never queued)")
|
||||
case rep.queued == nil:
|
||||
case rep.Queued == nil:
|
||||
fmt.Fprintln(w, " (not queued)")
|
||||
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.Fprintf(w, " Priority:\t%s (%d)\n", artwork.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", artwork.FormatTime(rep.Queued.RetryAt))
|
||||
}
|
||||
if rep.queued != nil {
|
||||
writeStepTable(w, "Last attempt failed", artwork.DecodeTrace(rep.queued.Trace, ""))
|
||||
if rep.Queued != nil {
|
||||
writeStepTable(w, "Last attempt failed", rep.LastAttemptFailed())
|
||||
}
|
||||
if rep.stored != nil {
|
||||
writeStepTable(w, "Gave up after", artwork.DecodeTrace(rep.stored.LastFailure, ""))
|
||||
if rep.Stored != nil {
|
||||
writeStepTable(w, "Gave up after", rep.GaveUpAfter())
|
||||
}
|
||||
|
||||
fmt.Fprintln(w, "\nConfig")
|
||||
if setting, value := explainConfig(rep.kind); setting == "" {
|
||||
if setting, value := artwork.ConfigFor(rep.Kind); setting == "" {
|
||||
fmt.Fprintln(w, " (no artwork source configuration applies)")
|
||||
} else {
|
||||
fmt.Fprintf(w, " %s:\t%s\n", setting, value)
|
||||
if rep.agents != "" {
|
||||
fmt.Fprintf(w, " Agents:\t%s\n", rep.agents)
|
||||
if rep.Agents != "" {
|
||||
fmt.Fprintf(w, " Agents:\t%s\n", cliAgents(rep))
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(w, "\nChain (%s)\n", explainChainOrigin(rep))
|
||||
fmt.Fprintf(w, "\nChain (%s)\n", rep.ChainOrigin())
|
||||
switch {
|
||||
case !explainable:
|
||||
fmt.Fprintf(w, " (%s artwork does not walk a priority chain)\n", rep.kind)
|
||||
fmt.Fprintf(w, " (%s artwork does not walk a priority chain)\n", rep.Kind)
|
||||
case unrecorded:
|
||||
fmt.Fprintln(w, " (no resolution recorded yet; re-run with --live to walk the chain now)")
|
||||
case !rep.walked && len(rep.steps) == 0 && rep.stored.Hash != "":
|
||||
case !rep.Walked && len(rep.Steps) == 0 && rep.Stored.Hash != "":
|
||||
// A stored image with no chain can only predate trace recording: a recorded resolution that
|
||||
// found an image always records its winning candidate.
|
||||
fmt.Fprintln(w, " (this item was resolved before traces were recorded; re-run with --live)")
|
||||
case !rep.walked && len(rep.steps) == 0:
|
||||
case !rep.Walked && len(rep.Steps) == 0:
|
||||
// Absent with no chain: an empty priority list walked nothing, or a pre-tracing absent row.
|
||||
fmt.Fprintln(w, " (no candidates were recorded; re-run with --live to walk the chain now)")
|
||||
default:
|
||||
fmt.Fprintln(w, " CANDIDATE\tOUTCOME\tDETAIL")
|
||||
writeSteps(w, " ", rep.steps)
|
||||
writeSteps(w, " ", rep.Steps)
|
||||
}
|
||||
|
||||
fmt.Fprintln(w, "\nResult")
|
||||
switch {
|
||||
case rep.resolveErr != nil:
|
||||
fmt.Fprintf(w, " resolution failed: %s\n", rep.resolveErr)
|
||||
case rep.ResolveErr != nil:
|
||||
fmt.Fprintf(w, " resolution failed: %s\n", rep.ResolveErr)
|
||||
case !explainable:
|
||||
fmt.Fprintln(w, " not evaluated (no chain was walked; see Stored above)")
|
||||
case unrecorded:
|
||||
fmt.Fprintln(w, " not evaluated (nothing recorded; re-run with --live to walk the chain now)")
|
||||
default:
|
||||
fmt.Fprintf(w, " %s\n", explainResult(rep.source, rep.steps))
|
||||
fmt.Fprintf(w, " %s\n", rep.Result())
|
||||
}
|
||||
|
||||
w.Flush()
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func formatTime(t time.Time) string {
|
||||
if t.IsZero() {
|
||||
return "-"
|
||||
}
|
||||
return t.Format(time.RFC3339)
|
||||
}
|
||||
|
||||
func runExplain(ctx context.Context, args []string) {
|
||||
defer db.Init(ctx)()
|
||||
ds, ctx := getAdminContext(ctx)
|
||||
|
||||
targets, failures, err := resolveArtworkTargets(ctx, ds, args, explainKinds)
|
||||
targets, failures, err := resolveArtworkTargets(ctx, ds, args, artwork.ExplainKinds)
|
||||
if err != nil {
|
||||
log.Fatal(ctx, err)
|
||||
}
|
||||
|
|
@ -978,45 +848,29 @@ func runExplain(ctx context.Context, args []string) {
|
|||
}
|
||||
kind, id := targets[0].Kind, targets[0].ID
|
||||
|
||||
name, err := artwork.ItemName(ctx, ds, kind, id)
|
||||
if err != nil {
|
||||
log.Fatal(ctx, "Item not found", "kind", kind, "id", id, err)
|
||||
var opts artwork.ExplainOptions
|
||||
// Only artist and album reach an agent, and the load must precede the resolver, which reads the
|
||||
// same manager. Leaving ag nil elsewhere avoids handing agents.GetAgents a not-yet-loaded manager.
|
||||
var ag *agents.Agents
|
||||
if kind == model.KindArtistArtwork || kind == model.KindAlbumArtwork {
|
||||
mgr := loadPluginAgents(ctx, explainLive)
|
||||
defer func() { _ = mgr.Stop() }()
|
||||
ag = agents.GetAgents(ds, mgr)
|
||||
}
|
||||
rep := explainReport{kind: kind, id: id, name: name}
|
||||
if artwork.KeepsState(kind) {
|
||||
rep.stored, err = ds.Artwork().GetItemArtwork(ctx, 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().Get(ctx, 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)
|
||||
// Disc artwork keeps no row, so it has no stored trace and can only be explained by walking now.
|
||||
if explainLive || !artwork.KeepsState(kind) {
|
||||
opts.Walk = func(t *artwork.ChainTrace) *artwork.TracingResolver {
|
||||
return CreateArtworkResolver(t, explainLive)
|
||||
}
|
||||
}
|
||||
rep, err := artwork.Explain(ctx, ds, ag, kind, id, opts)
|
||||
if err != nil {
|
||||
log.Fatal(ctx, "Failed to explain artwork", "kind", kind, "id", id, err)
|
||||
}
|
||||
|
||||
// Disc artwork keeps no row, so it has no stored trace and can only be explained by walking now.
|
||||
rep.walked = explainLive || !artwork.KeepsState(kind)
|
||||
if artwork.Explainable(kind) {
|
||||
// Only artist and album reach an agent, and the load must precede the resolver, which reads
|
||||
// the same manager.
|
||||
if kind == model.KindArtistArtwork || kind == model.KindAlbumArtwork {
|
||||
mgr := loadPluginAgents(ctx, explainLive)
|
||||
defer func() { _ = mgr.Stop() }()
|
||||
rep.agents = explainAgents(conf.Server().Agents, availableImageAgents(ds, mgr, kind))
|
||||
}
|
||||
switch {
|
||||
case rep.walked:
|
||||
trace := &artwork.ChainTrace{}
|
||||
rep.source, rep.resolveErr = CreateArtworkResolver(trace, explainLive).Resolve(ctx, kind, id)
|
||||
rep.steps = trace.Steps()
|
||||
case rep.stored != nil:
|
||||
rep.steps = artwork.DecodeTrace(rep.stored.Trace, rep.stored.SourcePath)
|
||||
rep.source = rep.stored.Source
|
||||
}
|
||||
}
|
||||
fmt.Print(formatExplain(rep))
|
||||
// The steps taken before a failed walk are the diagnosis, so report them before exiting.
|
||||
if rep.resolveErr != nil {
|
||||
log.Fatal(ctx, "Failed to resolve artwork", "kind", kind, "id", id, rep.resolveErr)
|
||||
if rep.ResolveErr != nil {
|
||||
log.Fatal(ctx, "Failed to resolve artwork", "kind", kind, "id", id, rep.ResolveErr)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,8 +40,8 @@ var _ = Describe("parseArtworkKind", func() {
|
|||
_, err := parseArtworkKind(prefix, valid)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
},
|
||||
Entry("explain reads disc artwork", "dc", explainKinds),
|
||||
Entry("explain reads media file artwork", "mf", explainKinds),
|
||||
Entry("explain reads disc artwork", "dc", artwork.ExplainKinds),
|
||||
Entry("explain reads media file artwork", "mf", artwork.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),
|
||||
|
|
@ -64,7 +64,7 @@ var _ = Describe("resolveArtworkTargets", func() {
|
|||
})
|
||||
|
||||
It("accepts the explicit <kind> <id> leader shared by every id", func() {
|
||||
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"al", "x", "y"}, explainKinds)
|
||||
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"al", "x", "y"}, artwork.ExplainKinds)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(failures).To(BeEmpty())
|
||||
Expect(targets).To(Equal([]model.ArtworkID{
|
||||
|
|
@ -77,20 +77,20 @@ var _ = Describe("resolveArtworkTargets", func() {
|
|||
})
|
||||
|
||||
It("resolves a bare id by looking it up across tables", func() {
|
||||
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"artist1"}, explainKinds)
|
||||
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"artist1"}, artwork.ExplainKinds)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(failures).To(BeEmpty())
|
||||
Expect(targets).To(Equal([]model.ArtworkID{{Kind: model.KindArtistArtwork, ID: "artist1"}}))
|
||||
})
|
||||
|
||||
It("reads the kind from a full artwork id prefix without a database lookup", func() {
|
||||
targets, _, err := resolveArtworkTargets(ctx, ds, []string{"al-realalbum"}, explainKinds)
|
||||
targets, _, err := resolveArtworkTargets(ctx, ds, []string{"al-realalbum"}, artwork.ExplainKinds)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(targets).To(Equal([]model.ArtworkID{{Kind: model.KindAlbumArtwork, ID: "realalbum"}}))
|
||||
})
|
||||
|
||||
It("strips the hash suffix from a full artwork id", func() {
|
||||
targets, _, err := resolveArtworkTargets(ctx, ds, []string{"al-realalbum_0123456789abcdef"}, explainKinds)
|
||||
targets, _, err := resolveArtworkTargets(ctx, ds, []string{"al-realalbum_0123456789abcdef"}, artwork.ExplainKinds)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(targets).To(Equal([]model.ArtworkID{{Kind: model.KindAlbumArtwork, ID: "realalbum"}}))
|
||||
})
|
||||
|
|
@ -104,7 +104,7 @@ var _ = Describe("resolveArtworkTargets", func() {
|
|||
})
|
||||
|
||||
It("collects an id that matches nothing and has no kind prefix", func() {
|
||||
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"nope"}, explainKinds)
|
||||
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"nope"}, artwork.ExplainKinds)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(targets).To(BeEmpty())
|
||||
Expect(failures).To(HaveLen(1))
|
||||
|
|
@ -112,7 +112,7 @@ var _ = Describe("resolveArtworkTargets", func() {
|
|||
})
|
||||
|
||||
It("resolves the valid ids and collects the unresolvable ones", func() {
|
||||
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"artist1", "nope", "al-realalbum"}, explainKinds)
|
||||
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"artist1", "nope", "al-realalbum"}, artwork.ExplainKinds)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(targets).To(Equal([]model.ArtworkID{
|
||||
{Kind: model.KindArtistArtwork, ID: "artist1"}, {Kind: model.KindAlbumArtwork, ID: "realalbum"}}))
|
||||
|
|
@ -121,125 +121,35 @@ var _ = Describe("resolveArtworkTargets", func() {
|
|||
})
|
||||
})
|
||||
|
||||
var _ = Describe("explainResult", func() {
|
||||
It("reports the winning source", func() {
|
||||
steps := []artwork.TraceStep{{Candidate: "folder", Outcome: "hit", Detail: "/music/a.jpg"}}
|
||||
Expect(explainResult("folder", steps)).To(ContainSubstring("resolved from folder"))
|
||||
})
|
||||
|
||||
It("reports not resolved when every candidate was tried and missed", func() {
|
||||
steps := []artwork.TraceStep{
|
||||
{Candidate: "artist.*", Outcome: "miss"},
|
||||
{Candidate: "external:deezer", Outcome: "miss"},
|
||||
}
|
||||
Expect(explainResult("", steps)).To(Equal("not resolved"))
|
||||
})
|
||||
|
||||
It("reports indeterminate when a local candidate exists but could not be read", func() {
|
||||
steps := []artwork.TraceStep{
|
||||
{Candidate: "cover.*", Outcome: "miss"},
|
||||
{Candidate: "embedded", Outcome: "unreadable"},
|
||||
}
|
||||
Expect(explainResult("", steps)).To(ContainSubstring("indeterminate"),
|
||||
"the worker retries an unreadable candidate instead of settling absent, so this is not a clean miss")
|
||||
})
|
||||
|
||||
It("reports indeterminate when a processing stage errored after a candidate was found", func() {
|
||||
steps := []artwork.TraceStep{
|
||||
{Candidate: "cover.*", Outcome: "hit", Detail: "/music/cover.jpg"},
|
||||
{Candidate: "store", Outcome: "error", Detail: "disk full"},
|
||||
}
|
||||
Expect(explainResult("", steps)).To(ContainSubstring("indeterminate"),
|
||||
"a stage error is a processing failure the worker retries, not a definitive miss")
|
||||
})
|
||||
|
||||
It("does not qualify a hit that an earlier unreadable candidate preceded", func() {
|
||||
// chainState.try stamps only the external error onto a hit and drops the local one, so the
|
||||
// worker settles this as found; warning about it would be a false alarm.
|
||||
steps := []artwork.TraceStep{
|
||||
{Candidate: "embedded", Outcome: "unreadable"},
|
||||
{Candidate: "cover.*", Outcome: "hit", Detail: "/music/cover.jpg"},
|
||||
}
|
||||
Expect(explainResult("folder", steps)).To(Equal("resolved from folder"))
|
||||
})
|
||||
|
||||
It("reports indeterminate when an external lookup failed transiently", func() {
|
||||
steps := []artwork.TraceStep{
|
||||
{Candidate: "artist.*", Outcome: "miss"},
|
||||
{Candidate: "external:deezer", Outcome: "error", Detail: "context deadline exceeded"},
|
||||
}
|
||||
Expect(explainResult("", steps)).To(ContainSubstring("indeterminate"),
|
||||
"a failed network call is not evidence that the item has no artwork")
|
||||
})
|
||||
|
||||
It("qualifies a win a failed higher-priority external lookup could have taken", func() {
|
||||
steps := []artwork.TraceStep{
|
||||
{Candidate: "external:deezer", Outcome: "error", Detail: "context deadline exceeded"},
|
||||
{Candidate: "artist.*", Outcome: "hit", Detail: "/music/artist.jpg"},
|
||||
}
|
||||
res := explainResult("artist.*", steps)
|
||||
Expect(res).To(ContainSubstring("resolved from artist.*"))
|
||||
Expect(res).To(ContainSubstring("indeterminate"),
|
||||
"the resolver serves this hit but retries later, so the winner is provisional")
|
||||
})
|
||||
|
||||
It("does not qualify an external win that followed a failed external lookup", func() {
|
||||
steps := []artwork.TraceStep{
|
||||
{Candidate: "external:deezer", Outcome: "error", Detail: "context deadline exceeded"},
|
||||
{Candidate: "external:lastfm", Outcome: "hit", Detail: "http://img"},
|
||||
}
|
||||
Expect(explainResult("external:lastfm", steps)).To(Equal("resolved from external:lastfm"),
|
||||
"a later agent supplying the image discards the earlier error, so there is no retry to warn about")
|
||||
})
|
||||
|
||||
It("does not qualify a win that outranked the failed external lookup", func() {
|
||||
steps := []artwork.TraceStep{
|
||||
{Candidate: "artist.*", Outcome: "hit"},
|
||||
{Candidate: "external:deezer", Outcome: "error", Detail: "context deadline exceeded"},
|
||||
}
|
||||
Expect(explainResult("artist.*", steps)).To(Equal("resolved from artist.*"))
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("explainAgents", func() {
|
||||
It("accounts for every configured agent, marking the ones the CLI could not use", func() {
|
||||
out := explainAgents("artist-nfo-metadata,apple-music,deezer,lastfm", []string{"deezer"})
|
||||
for _, name := range []string{"artist-nfo-metadata", "apple-music", "deezer", "lastfm"} {
|
||||
Expect(out).To(ContainSubstring(name),
|
||||
"a configured agent missing from this line reads as if it had never been configured")
|
||||
}
|
||||
Expect(out).To(ContainSubstring("not available to the CLI"))
|
||||
})
|
||||
|
||||
It("does not mark anything when every configured agent is available", func() {
|
||||
out := explainAgents("deezer, lastfm", []string{"lastfm", "deezer"})
|
||||
Expect(out).To(Equal("deezer, lastfm"))
|
||||
})
|
||||
|
||||
It("reports an empty configuration as none, not as an unavailable agent", func() {
|
||||
Expect(explainAgents("", nil)).To(Equal("(none)"))
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("formatExplain", func() {
|
||||
var rep explainReport
|
||||
var rep artwork.ExplainReport
|
||||
|
||||
BeforeEach(func() {
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external, artist.*" })
|
||||
rep = explainReport{
|
||||
kind: model.KindArtistArtwork,
|
||||
id: "ar-1",
|
||||
name: "Radiohead",
|
||||
agents: "lastfm,spotify",
|
||||
walked: true,
|
||||
steps: []artwork.TraceStep{
|
||||
rep = artwork.ExplainReport{
|
||||
Kind: model.KindArtistArtwork,
|
||||
ID: "ar-1",
|
||||
Name: "Radiohead",
|
||||
Agents: "lastfm,spotify",
|
||||
Walked: true,
|
||||
Steps: []artwork.TraceStep{
|
||||
{Candidate: "upload", Outcome: "skipped", Detail: "no uploaded image"},
|
||||
{Candidate: "external:deezer", Outcome: "error", Detail: "context deadline exceeded"},
|
||||
},
|
||||
source: "",
|
||||
Source: "",
|
||||
}
|
||||
})
|
||||
|
||||
It("explains the star on an agent the CLI could not construct", func() {
|
||||
rep.AgentsIncomplete = true
|
||||
|
||||
Expect(formatExplain(rep)).To(ContainSubstring("(* not available to the CLI)"))
|
||||
})
|
||||
|
||||
It("leaves the agent line unadorned when every agent is available", func() {
|
||||
Expect(formatExplain(rep)).ToNot(ContainSubstring("not available to the CLI"))
|
||||
})
|
||||
|
||||
It("reports the item, its config and the chain it walked", func() {
|
||||
out := formatExplain(rep)
|
||||
Expect(out).To(ContainSubstring("Radiohead"))
|
||||
|
|
@ -258,11 +168,11 @@ var _ = Describe("formatExplain", func() {
|
|||
|
||||
It("prints the stored state and the queue row when they exist", func() {
|
||||
attempted := time.Date(2026, 8, 13, 10, 0, 0, 0, time.UTC)
|
||||
rep.stored = &model.ItemArtwork{Source: "folder", Hash: "abc123",
|
||||
rep.Stored = &model.ItemArtwork{Source: "folder", Hash: "abc123",
|
||||
SourcePath: "/music/cover.jpg", AttemptedAt: attempted}
|
||||
rep.queued = &model.ArtworkQueueItem{Priority: model.ArtworkPriorityScan, Attempts: 2,
|
||||
rep.Queued = &model.ArtworkQueueItem{Priority: model.ArtworkPriorityScan, Attempts: 2,
|
||||
RetryAt: attempted.Add(time.Hour)}
|
||||
rep.source = "folder"
|
||||
rep.Source = "folder"
|
||||
|
||||
out := formatExplain(rep)
|
||||
Expect(out).To(ContainSubstring("abc123"))
|
||||
|
|
@ -273,12 +183,12 @@ var _ = Describe("formatExplain", func() {
|
|||
})
|
||||
|
||||
It("marks a known-absent stored state instead of printing an empty hash", func() {
|
||||
rep.stored = &model.ItemArtwork{AttemptedAt: time.Now()}
|
||||
rep.Stored = &model.ItemArtwork{AttemptedAt: time.Now()}
|
||||
Expect(formatExplain(rep)).To(ContainSubstring("absent"))
|
||||
})
|
||||
|
||||
It("reports a failed walk as failed, not as unresolved", func() {
|
||||
rep.resolveErr = errors.New("no such directory")
|
||||
rep.ResolveErr = errors.New("no such directory")
|
||||
|
||||
out := formatExplain(rep)
|
||||
Expect(out).To(ContainSubstring("resolution failed: no such directory"))
|
||||
|
|
@ -288,9 +198,9 @@ var _ = Describe("formatExplain", func() {
|
|||
|
||||
It("says a kind that does not walk a chain has no chain, without an empty table", func() {
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*, embedded" })
|
||||
rep.kind = model.KindPlaylistArtwork
|
||||
rep.steps = nil
|
||||
rep.agents = ""
|
||||
rep.Kind = model.KindPlaylistArtwork
|
||||
rep.Steps = nil
|
||||
rep.Agents = ""
|
||||
|
||||
out := formatExplain(rep)
|
||||
Expect(out).To(ContainSubstring("does not walk a priority chain"))
|
||||
|
|
@ -304,11 +214,11 @@ var _ = Describe("formatExplain", func() {
|
|||
|
||||
It("says disc artwork keeps no state instead of reporting it as unresolved state", func() {
|
||||
conf.Update(func(c *conf.Options) { c.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",
|
||||
walked: true,
|
||||
rep = artwork.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",
|
||||
Walked: true,
|
||||
}
|
||||
|
||||
out := formatExplain(rep)
|
||||
|
|
@ -323,15 +233,15 @@ var _ = Describe("formatExplain", func() {
|
|||
|
||||
Context("stored traces", func() {
|
||||
BeforeEach(func() {
|
||||
rep.walked = false
|
||||
rep.steps = nil
|
||||
rep.Walked = false
|
||||
rep.Steps = nil
|
||||
})
|
||||
|
||||
It("labels a recorded chain with when it was recorded, not as a walk done now", func() {
|
||||
attempted := time.Date(2026, 8, 13, 10, 0, 0, 0, time.UTC)
|
||||
rep.stored = &model.ItemArtwork{Source: "folder", Hash: "abc", AttemptedAt: attempted}
|
||||
rep.steps = []artwork.TraceStep{{Candidate: "artist.*", Outcome: "hit", Detail: "/music/artist.jpg"}}
|
||||
rep.source = "folder"
|
||||
rep.Stored = &model.ItemArtwork{Source: "folder", Hash: "abc", AttemptedAt: attempted}
|
||||
rep.Steps = []artwork.TraceStep{{Candidate: "artist.*", Outcome: "hit", Detail: "/music/artist.jpg"}}
|
||||
rep.Source = "folder"
|
||||
|
||||
out := formatExplain(rep)
|
||||
Expect(out).To(ContainSubstring("Chain (recorded 2026-08-13T10:00:00Z)"))
|
||||
|
|
@ -348,7 +258,7 @@ var _ = Describe("formatExplain", func() {
|
|||
})
|
||||
|
||||
It("distinguishes a row written before traces existed from one with an empty chain", func() {
|
||||
rep.stored = &model.ItemArtwork{Source: "folder", Hash: "abc", AttemptedAt: time.Now()}
|
||||
rep.Stored = &model.ItemArtwork{Source: "folder", Hash: "abc", AttemptedAt: time.Now()}
|
||||
|
||||
Expect(formatExplain(rep)).To(ContainSubstring("resolved before traces were recorded"))
|
||||
})
|
||||
|
|
@ -356,7 +266,7 @@ var _ = Describe("formatExplain", func() {
|
|||
It("does not call an absent row with an empty recorded chain a pre-tracing row", func() {
|
||||
// An empty priority list records a real but empty chain and resolves absent; that is not a
|
||||
// legacy row, so it must not be reported as resolved before tracing existed.
|
||||
rep.stored = &model.ItemArtwork{Source: "", Hash: "", AttemptedAt: time.Now()}
|
||||
rep.Stored = &model.ItemArtwork{Source: "", Hash: "", AttemptedAt: time.Now()}
|
||||
|
||||
out := formatExplain(rep)
|
||||
Expect(out).ToNot(ContainSubstring("resolved before traces were recorded"))
|
||||
|
|
@ -365,9 +275,9 @@ var _ = Describe("formatExplain", func() {
|
|||
})
|
||||
|
||||
It("prints why the last attempt failed and why it gave up", func() {
|
||||
rep.queued = &model.ArtworkQueueItem{Priority: model.ArtworkPriorityScan, Attempts: 3,
|
||||
rep.Queued = &model.ArtworkQueueItem{Priority: model.ArtworkPriorityScan, Attempts: 3,
|
||||
Trace: `[{"c":"decode","o":"error","d":"bad header"}]`}
|
||||
rep.stored = &model.ItemArtwork{Source: "folder", Hash: "abc", AttemptedAt: time.Now(),
|
||||
rep.Stored = &model.ItemArtwork{Source: "folder", Hash: "abc", AttemptedAt: time.Now(),
|
||||
LastFailure: `[{"c":"read","o":"error","d":"i/o timeout"}]`}
|
||||
|
||||
out := formatExplain(rep)
|
||||
|
|
@ -386,10 +296,10 @@ var _ = Describe("formatExplain", func() {
|
|||
|
||||
It("reports the setting that governs media file artwork", func() {
|
||||
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false })
|
||||
rep = explainReport{
|
||||
kind: model.KindMediaFileArtwork, id: "mf-1", name: "Airbag",
|
||||
walked: true,
|
||||
steps: []artwork.TraceStep{
|
||||
rep = artwork.ExplainReport{
|
||||
Kind: model.KindMediaFileArtwork, ID: "mf-1", Name: "Airbag",
|
||||
Walked: true,
|
||||
Steps: []artwork.TraceStep{
|
||||
{Candidate: "embedded", Outcome: "skipped", Detail: "EnableMediaFileCoverArt is off"},
|
||||
},
|
||||
}
|
||||
|
|
@ -402,26 +312,6 @@ var _ = Describe("formatExplain", func() {
|
|||
})
|
||||
})
|
||||
|
||||
var _ = Describe("explainConfig", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DiscArtPriority = "cover.jpg"
|
||||
c.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("artwork refresh command", func() {
|
||||
It("requires at least one argument", func() {
|
||||
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{})).To(HaveOccurred())
|
||||
|
|
@ -494,8 +384,8 @@ var _ = Describe("explain/reprocess source round trip", func() {
|
|||
Expect(art.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: model.KindArtistArtwork.Prefix(),
|
||||
ItemID: "ar-1", ImageType: model.ImageTypePrimary})).To(Succeed())
|
||||
|
||||
shown := storedSource(formatExplain(explainReport{kind: model.KindArtistArtwork, id: "ar-1",
|
||||
stored: &model.ItemArtwork{AttemptedAt: time.Now()}}))
|
||||
shown := storedSource(formatExplain(artwork.ExplainReport{Kind: model.KindArtistArtwork, ID: "ar-1",
|
||||
Stored: &model.ItemArtwork{AttemptedAt: time.Now()}}))
|
||||
|
||||
q := ds.ArtworkQueue()
|
||||
Expect(validateSources(ctx, q, repositorySources([]string{shown}))).To(Succeed(),
|
||||
|
|
@ -1063,7 +953,7 @@ var _ = Describe("parseArtworkPriority", func() {
|
|||
It("accepts every name status prints", func() {
|
||||
for _, p := range []int{model.ArtworkPriorityRecheck, model.ArtworkPriorityBackfill,
|
||||
model.ArtworkPriorityScan, model.ArtworkPriorityBump} {
|
||||
Expect(parseArtworkPriority(priorityName(p))).To(Equal(p))
|
||||
Expect(parseArtworkPriority(artwork.PriorityName(p))).To(Equal(p))
|
||||
}
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -82,7 +82,7 @@ func CreateNativeAPIRouter(ctx context.Context) *nativeapi.Router {
|
|||
matcherMatcher := matcher.New(dataStore)
|
||||
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher, broker)
|
||||
quickConnect := quickconnect.GetInstance()
|
||||
router := nativeapi.New(dataStore, share, playlistsPlaylists, insights, library, user, maintenance, manager, uploader, provider, quickConnect)
|
||||
router := nativeapi.New(dataStore, share, playlistsPlaylists, insights, library, user, maintenance, manager, uploader, provider, quickConnect, agentsAgents)
|
||||
return router
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -176,7 +176,6 @@ type scannerOptions struct {
|
|||
GroupAlbumReleases bool // Deprecated: Use PID.Album instead
|
||||
FollowSymlinks bool // Whether to follow symlinks when scanning directories
|
||||
IgnoreDotFolders bool // Whether to ignore folders whose name starts with a dot when scanning
|
||||
RespectNoMedia bool // Whether to skip folders (and their subfolders) containing a .nomedia file
|
||||
PurgeMissing string // Values: "never", "always", "full"
|
||||
}
|
||||
|
||||
|
|
@ -211,7 +210,6 @@ type lastfmOptions struct {
|
|||
Secret string //nolint:gosec
|
||||
Language string
|
||||
ScrobbleFirstArtistOnly bool
|
||||
MinScrobbleDuration time.Duration
|
||||
|
||||
// Computed values
|
||||
Languages []string `conf:"-"` // Computed from Language, split by comma
|
||||
|
|
@ -426,8 +424,6 @@ func Load(noConfigDump bool) {
|
|||
durationNonNegativeOrDefault(&s.DevInsightsInitialDelay, consts.InsightsInitialDelay)
|
||||
durationNonNegativeOrDefault(&s.DevPluginCompilationTimeout, consts.DefaultPluginCompilationTimeout)
|
||||
|
||||
durationNonNegativeOrDefault(&s.LastFM.MinScrobbleDuration, consts.DefaultMinScrobbleDuration)
|
||||
|
||||
// Log deprecated, removed and unknown options
|
||||
for _, o := range deprecatedOptions {
|
||||
logDeprecatedOptions(o.name, o.replacement)
|
||||
|
|
@ -1058,7 +1054,6 @@ func setViperDefaults() {
|
|||
viper.SetDefault("scanner.groupalbumreleases", false)
|
||||
viper.SetDefault("scanner.followsymlinks", true)
|
||||
viper.SetDefault("scanner.ignoredotfolders", true)
|
||||
viper.SetDefault("scanner.respectnomedia", false)
|
||||
viper.SetDefault("scanner.purgemissing", consts.PurgeMissingNever)
|
||||
viper.SetDefault("subsonic.appendsubtitle", true)
|
||||
viper.SetDefault("subsonic.appendalbumversion", true)
|
||||
|
|
@ -1076,7 +1071,6 @@ func setViperDefaults() {
|
|||
viper.SetDefault("lastfm.apikey", "")
|
||||
viper.SetDefault("lastfm.secret", "")
|
||||
viper.SetDefault("lastfm.scrobblefirstartistonly", false)
|
||||
viper.SetDefault("lastfm.minscrobbleduration", consts.DefaultMinScrobbleDuration)
|
||||
viper.SetDefault("deezer.enabled", true)
|
||||
viper.SetDefault("deezer.language", consts.DefaultInfoLanguage)
|
||||
viper.SetDefault("listenbrainz.enabled", true)
|
||||
|
|
|
|||
|
|
@ -404,31 +404,6 @@ var _ = Describe("Configuration", func() {
|
|||
})
|
||||
})
|
||||
|
||||
Describe("MinScrobbleDuration", func() {
|
||||
It("defaults to 30 seconds", func() {
|
||||
conf.Load(true)
|
||||
Expect(conf.Server().LastFM.MinScrobbleDuration).To(Equal(consts.DefaultMinScrobbleDuration))
|
||||
})
|
||||
|
||||
It("sets negative values to default", func() {
|
||||
viper.SetDefault("lastfm.minscrobbleduration", "-10s")
|
||||
conf.Load(true)
|
||||
Expect(conf.Server().LastFM.MinScrobbleDuration).To(Equal(consts.DefaultMinScrobbleDuration))
|
||||
})
|
||||
|
||||
It("disables with zero value", func() {
|
||||
viper.SetDefault("lastfm.minscrobbleduration", "0s")
|
||||
conf.Load(true)
|
||||
Expect(conf.Server().LastFM.MinScrobbleDuration).To(Equal(time.Duration(0)))
|
||||
})
|
||||
|
||||
It("preserves positive values", func() {
|
||||
viper.SetDefault("lastfm.minscrobbleduration", "45s")
|
||||
conf.Load(true)
|
||||
Expect(conf.Server().LastFM.MinScrobbleDuration).To(Equal(45 * time.Second))
|
||||
})
|
||||
})
|
||||
|
||||
Describe("Scanner.Extractor", func() {
|
||||
BeforeEach(func() {
|
||||
viper.Reset()
|
||||
|
|
|
|||
|
|
@ -83,8 +83,6 @@ const (
|
|||
|
||||
DefaultInfoLanguage = "en"
|
||||
|
||||
DefaultMinScrobbleDuration = 30 * time.Second
|
||||
|
||||
ArtistInfoTimeToLive = 24 * time.Hour
|
||||
AlbumInfoTimeToLive = 7 * 24 * time.Hour
|
||||
UpdateLastAccessFrequency = time.Minute
|
||||
|
|
@ -92,7 +90,6 @@ const (
|
|||
|
||||
I18nFolder = "i18n"
|
||||
ScanIgnoreFile = ".ndignore"
|
||||
NoMediaFile = ".nomedia"
|
||||
ArtworkFolder = "artwork"
|
||||
// HashedArtworkFolder is a subtree of ArtworkFolder, kept apart from the name-addressed
|
||||
// upload folders beside it so Prune's sweep never reaches them.
|
||||
|
|
|
|||
215
core/artwork/explain.go
Normal file
215
core/artwork/explain.go
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
package artwork
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/utils/slice"
|
||||
)
|
||||
|
||||
// Result states the verdict of the walk. A skipped or failed external tier, or a local candidate
|
||||
// that would not open, leaves the outcome unknown: nothing observed that there is no artwork.
|
||||
func Result(source string, steps []TraceStep) string {
|
||||
if source != "" {
|
||||
for _, s := range steps {
|
||||
if s.Outcome == OutcomeHit {
|
||||
break
|
||||
}
|
||||
// An external winner discards the earlier error, so the resolver settles it with no retry.
|
||||
if s.Outcome == OutcomeError && strings.HasPrefix(s.Candidate, ExternalPrefix) &&
|
||||
!strings.HasPrefix(source, ExternalPrefix) {
|
||||
return "resolved from " + source +
|
||||
" (indeterminate: a higher-priority external lookup failed; this may resolve differently on a retry)"
|
||||
}
|
||||
}
|
||||
return "resolved from " + source
|
||||
}
|
||||
for _, s := range steps {
|
||||
switch {
|
||||
case s.Outcome == OutcomeError && strings.HasPrefix(s.Candidate, ExternalPrefix):
|
||||
return "indeterminate (an external lookup failed; the item may resolve on a later attempt)"
|
||||
case s.Outcome == OutcomeError, s.Outcome == OutcomeUnreadable:
|
||||
return "indeterminate (a candidate was found but could not be processed; the worker retries rather than settling absent)"
|
||||
}
|
||||
}
|
||||
return "not resolved"
|
||||
}
|
||||
|
||||
// ConfigFor names the setting that decides where a kind's artwork comes from, and its value.
|
||||
func ConfigFor(kind model.Kind) (setting, 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 "", ""
|
||||
}
|
||||
|
||||
// ImageAgentNames names the agents that can actually supply an image for kind.
|
||||
func ImageAgentNames(ag *agents.Agents, kind model.Kind) []string {
|
||||
if kind == model.KindArtistArtwork {
|
||||
return slice.Map(ag.ArtistImageAgents(), func(a agents.ArtistImageAgent) string { return a.Name })
|
||||
}
|
||||
return slice.Map(ag.AlbumImageAgents(), func(a agents.AlbumImageAgent) string { return a.Name })
|
||||
}
|
||||
|
||||
// FormatAgents accounts for every configured agent: one that cannot be constructed never reaches
|
||||
// the chain, so the raw list alone overstates it. Those are starred, and the bool lets each
|
||||
// caller word its own legend.
|
||||
func FormatAgents(configured string, available []string) (string, bool) {
|
||||
if strings.TrimSpace(configured) == "" {
|
||||
return "(none)", false
|
||||
}
|
||||
var unavailable bool
|
||||
names := slice.Map(strings.Split(configured, ","), func(name string) string {
|
||||
name = strings.TrimSpace(name)
|
||||
if slices.Contains(available, name) {
|
||||
return name
|
||||
}
|
||||
unavailable = true
|
||||
return name + "*"
|
||||
})
|
||||
return strings.Join(names, ", "), unavailable
|
||||
}
|
||||
|
||||
// ExplainOptions configures a single explain. The zero value reads history and never
|
||||
// touches the network.
|
||||
type ExplainOptions struct {
|
||||
// Walk builds a resolver that records into the trace; nil reads the recorded trace instead.
|
||||
Walk func(*ChainTrace) *TracingResolver
|
||||
}
|
||||
|
||||
// ExplainReport is everything known about how one item's artwork resolved.
|
||||
type ExplainReport struct {
|
||||
Kind model.Kind
|
||||
ID string
|
||||
Name string
|
||||
Stored *model.ItemArtwork
|
||||
Queued *model.ArtworkQueueItem
|
||||
Steps []TraceStep
|
||||
Source string
|
||||
Agents string
|
||||
// AgentsIncomplete reports that some configured agent is starred in Agents.
|
||||
AgentsIncomplete bool
|
||||
Walked bool
|
||||
ResolveErr error
|
||||
}
|
||||
|
||||
// Explain gathers everything known about how kind/id's artwork resolved: stored state, the
|
||||
// queue row, and either the recorded trace or a fresh walk, depending on opts.Walk.
|
||||
func Explain(ctx context.Context, ds model.DataStore, ag *agents.Agents, kind model.Kind, id string,
|
||||
opts ExplainOptions) (ExplainReport, error) {
|
||||
name, err := ItemName(ctx, ds, kind, id)
|
||||
if err != nil {
|
||||
return ExplainReport{}, err
|
||||
}
|
||||
rep := ExplainReport{Kind: kind, ID: id, Name: name}
|
||||
|
||||
if KeepsState(kind) {
|
||||
rep.Stored, err = ds.Artwork().GetItemArtwork(ctx, kind, id, model.ImageTypePrimary)
|
||||
if err != nil && !errors.Is(err, model.ErrNotFound) {
|
||||
return ExplainReport{}, fmt.Errorf("reading artwork state: %w", err)
|
||||
}
|
||||
rep.Queued, err = ds.ArtworkQueue().Get(ctx, kind, id, model.ImageTypePrimary)
|
||||
if err != nil && !errors.Is(err, model.ErrNotFound) {
|
||||
return ExplainReport{}, fmt.Errorf("reading the artwork queue: %w", err)
|
||||
}
|
||||
}
|
||||
// Set even for a kind the chain never walks, so a caller that asked to walk (e.g. --live on a
|
||||
// playlist) is reported as having tried.
|
||||
rep.Walked = opts.Walk != nil
|
||||
if !Explainable(kind) {
|
||||
return rep, nil
|
||||
}
|
||||
if ag != nil && (kind == model.KindArtistArtwork || kind == model.KindAlbumArtwork) {
|
||||
rep.Agents, rep.AgentsIncomplete = FormatAgents(conf.Server().Agents, ImageAgentNames(ag, kind))
|
||||
}
|
||||
|
||||
switch {
|
||||
case rep.Walked:
|
||||
trace := &ChainTrace{}
|
||||
rep.Source, rep.ResolveErr = opts.Walk(trace).Resolve(ctx, kind, id)
|
||||
rep.Steps = trace.Steps()
|
||||
case rep.Stored != nil:
|
||||
rep.Steps = DecodeTrace(rep.Stored.Trace, rep.Stored.SourcePath)
|
||||
rep.Source = rep.Stored.Source
|
||||
}
|
||||
return rep, nil
|
||||
}
|
||||
|
||||
// Result reports this report's verdict; see the package-level Result for the rules.
|
||||
func (r ExplainReport) Result() string { return Result(r.Source, r.Steps) }
|
||||
|
||||
// ChainOrigin says whether the report reads history or a walk performed just now, since the two
|
||||
// can disagree after a config change.
|
||||
func (r ExplainReport) ChainOrigin() string {
|
||||
if r.Walked {
|
||||
return "walked now"
|
||||
}
|
||||
if r.Stored != nil {
|
||||
return "recorded " + FormatTime(r.Stored.AttemptedAt)
|
||||
}
|
||||
return "not recorded"
|
||||
}
|
||||
|
||||
// FormatTime renders a timestamp for the report: a zero time reads as unset, not as year 1.
|
||||
func FormatTime(t time.Time) string {
|
||||
if t.IsZero() {
|
||||
return "-"
|
||||
}
|
||||
return t.Format(time.RFC3339)
|
||||
}
|
||||
|
||||
// LastAttemptFailed decodes why the queued row's last attempt failed, if there is one queued.
|
||||
func (r ExplainReport) LastAttemptFailed() []TraceStep {
|
||||
if r.Queued == nil {
|
||||
return nil
|
||||
}
|
||||
return DecodeTrace(r.Queued.Trace, "")
|
||||
}
|
||||
|
||||
// GaveUpAfter decodes the trace of the attempt that exhausted the retry budget, if the stored
|
||||
// state recorded one.
|
||||
func (r ExplainReport) GaveUpAfter() []TraceStep {
|
||||
if r.Stored == nil {
|
||||
return nil
|
||||
}
|
||||
return DecodeTrace(r.Stored.LastFailure, "")
|
||||
}
|
||||
|
||||
// Priority names one of the queue's fixed priority levels.
|
||||
type Priority struct {
|
||||
Name string
|
||||
Value int
|
||||
}
|
||||
|
||||
// KnownPriorities is the one listing behind both the name and the parse, so they cannot drift.
|
||||
var KnownPriorities = []Priority{
|
||||
{"bump", model.ArtworkPriorityBump},
|
||||
{"scan", model.ArtworkPriorityScan},
|
||||
{"recheck", model.ArtworkPriorityRecheck},
|
||||
{"backfill", model.ArtworkPriorityBackfill},
|
||||
}
|
||||
|
||||
// PriorityName falls back to the number: a row written by a newer version still has to print.
|
||||
func PriorityName(p int) string {
|
||||
for _, ap := range KnownPriorities {
|
||||
if ap.Value == p {
|
||||
return ap.Name
|
||||
}
|
||||
}
|
||||
return strconv.Itoa(p)
|
||||
}
|
||||
211
core/artwork/explain_test.go
Normal file
211
core/artwork/explain_test.go
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
package artwork_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/core/artwork"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Result", func() {
|
||||
It("reports the source when one was found", func() {
|
||||
steps := []artwork.TraceStep{{Candidate: "cover.*", Outcome: artwork.OutcomeHit}}
|
||||
Expect(artwork.Result("folder", steps)).To(Equal("resolved from folder"))
|
||||
})
|
||||
|
||||
It("flags a local win that a failed external lookup could have outranked", func() {
|
||||
steps := []artwork.TraceStep{
|
||||
{Candidate: artwork.ExternalPrefix + "deezer", Outcome: artwork.OutcomeError, Detail: "timeout"},
|
||||
{Candidate: "cover.*", Outcome: artwork.OutcomeHit},
|
||||
}
|
||||
Expect(artwork.Result("folder", steps)).To(ContainSubstring("indeterminate"))
|
||||
})
|
||||
|
||||
It("does not flag an external winner", func() {
|
||||
steps := []artwork.TraceStep{
|
||||
{Candidate: artwork.ExternalPrefix + "lastfm", Outcome: artwork.OutcomeError},
|
||||
{Candidate: artwork.ExternalPrefix + "deezer", Outcome: artwork.OutcomeHit},
|
||||
}
|
||||
Expect(artwork.Result(artwork.ExternalPrefix+"deezer", steps)).
|
||||
To(Equal("resolved from external:deezer"))
|
||||
})
|
||||
|
||||
It("is indeterminate when an external lookup failed and nothing resolved", func() {
|
||||
steps := []artwork.TraceStep{{Candidate: artwork.ExternalPrefix + "deezer", Outcome: artwork.OutcomeError}}
|
||||
Expect(artwork.Result("", steps)).To(ContainSubstring("an external lookup failed"))
|
||||
})
|
||||
|
||||
It("is indeterminate when a candidate could not be processed", func() {
|
||||
steps := []artwork.TraceStep{{Candidate: "cover.*", Outcome: artwork.OutcomeUnreadable}}
|
||||
Expect(artwork.Result("", steps)).To(ContainSubstring("could not be processed"))
|
||||
})
|
||||
|
||||
It("reports a clean miss", func() {
|
||||
steps := []artwork.TraceStep{{Candidate: "cover.*", Outcome: artwork.OutcomeMiss}}
|
||||
Expect(artwork.Result("", steps)).To(Equal("not resolved"))
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("ConfigFor", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external" })
|
||||
})
|
||||
|
||||
It("names the setting for a kind that has one", func() {
|
||||
setting, value := artwork.ConfigFor(model.KindArtistArtwork)
|
||||
Expect(setting).To(Equal("ArtistArtPriority"))
|
||||
Expect(value).To(Equal("external"))
|
||||
})
|
||||
|
||||
It("names the setting for the album kind", func() {
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*, embedded" })
|
||||
setting, value := artwork.ConfigFor(model.KindAlbumArtwork)
|
||||
Expect(setting).To(Equal("CoverArtPriority"))
|
||||
Expect(value).To(Equal("cover.*, embedded"))
|
||||
})
|
||||
|
||||
It("returns nothing for a kind with no source configuration", func() {
|
||||
setting, _ := artwork.ConfigFor(model.KindPlaylistArtwork)
|
||||
Expect(setting).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("FormatAgents", func() {
|
||||
It("reports none when nothing is configured", func() {
|
||||
line, incomplete := artwork.FormatAgents(" ", nil)
|
||||
Expect(line).To(Equal("(none)"))
|
||||
Expect(incomplete).To(BeFalse())
|
||||
})
|
||||
|
||||
It("keeps the configured order and marks what is unavailable", func() {
|
||||
got, incomplete := artwork.FormatAgents("spotify, lastfm", []string{"lastfm"})
|
||||
Expect(incomplete).To(BeTrue())
|
||||
Expect(got).To(Equal("spotify*, lastfm"))
|
||||
})
|
||||
|
||||
It("reports complete when every configured agent is available", func() {
|
||||
line, incomplete := artwork.FormatAgents("lastfm", []string{"lastfm"})
|
||||
Expect(line).To(Equal("lastfm"))
|
||||
Expect(incomplete).To(BeFalse())
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("PriorityName", func() {
|
||||
It("names a known priority", func() {
|
||||
Expect(artwork.PriorityName(model.ArtworkPriorityScan)).To(Equal("scan"))
|
||||
})
|
||||
|
||||
It("falls back to the number for an unknown priority", func() {
|
||||
Expect(artwork.PriorityName(999)).To(Equal("999"))
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("Explain", func() {
|
||||
var ds *tests.MockDataStore
|
||||
var artRepo *tests.MockArtworkRepo
|
||||
var queueRepo *tests.MockArtworkQueueRepo
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
artRepo = tests.CreateMockArtworkRepo()
|
||||
queueRepo = tests.CreateMockArtworkQueueRepo()
|
||||
ds = &tests.MockDataStore{MockedArtwork: artRepo, MockedArtworkQueue: queueRepo}
|
||||
Expect(ds.Artist().Put(ctx, &model.Artist{ID: "ar-1", Name: "Radiohead"})).To(Succeed())
|
||||
})
|
||||
|
||||
It("returns an error when the item does not exist", func() {
|
||||
_, err := artwork.Explain(ctx, ds, nil, model.KindArtistArtwork, "nope", artwork.ExplainOptions{})
|
||||
Expect(err).To(MatchError(model.ErrNotFound))
|
||||
})
|
||||
|
||||
It("reads the recorded trace when no walker is supplied", func() {
|
||||
// Storage shape mirrors storedStep in trace.go: c=candidate, o=outcome, d=detail.
|
||||
trace := `[{"c":"external:deezer","o":"hit","d":"https://cdn/x.jpg"}]`
|
||||
Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{
|
||||
ItemKind: model.KindArtistArtwork.Prefix(), ItemID: "ar-1", ImageType: model.ImageTypePrimary,
|
||||
Hash: "abc", Source: "external:deezer",
|
||||
Trace: trace,
|
||||
AttemptedAt: time.Date(2026, 9, 1, 10, 0, 0, 0, time.UTC),
|
||||
})).To(Succeed())
|
||||
|
||||
rep, err := artwork.Explain(ctx, ds, nil, model.KindArtistArtwork, "ar-1", artwork.ExplainOptions{})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(rep.Name).To(Equal("Radiohead"))
|
||||
Expect(rep.Walked).To(BeFalse())
|
||||
Expect(rep.Steps).To(Equal([]artwork.TraceStep{
|
||||
{Candidate: "external:deezer", Outcome: artwork.OutcomeHit, Detail: "https://cdn/x.jpg"},
|
||||
}))
|
||||
Expect(rep.Source).To(Equal("external:deezer"))
|
||||
Expect(rep.Result()).To(Equal("resolved from external:deezer"))
|
||||
Expect(rep.ChainOrigin()).To(ContainSubstring("recorded"))
|
||||
})
|
||||
|
||||
It("renders a zero attempted-at as unset, not as year 1", func() {
|
||||
rep := artwork.ExplainReport{Stored: &model.ItemArtwork{Source: "folder"}}
|
||||
Expect(rep.ChainOrigin()).To(Equal("recorded -"))
|
||||
})
|
||||
|
||||
It("reports nothing recorded when there is no stored state", func() {
|
||||
rep, err := artwork.Explain(ctx, ds, nil, model.KindArtistArtwork, "ar-1", artwork.ExplainOptions{})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(rep.Stored).To(BeNil())
|
||||
Expect(rep.Steps).To(BeEmpty())
|
||||
Expect(rep.ChainOrigin()).To(Equal("not recorded"))
|
||||
})
|
||||
|
||||
It("includes the queue row and its failure trace", func() {
|
||||
failure := `[{"c":"external:lastfm","o":"error","d":"429"}]`
|
||||
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
|
||||
ItemKind: model.KindArtistArtwork.Prefix(), ItemID: "ar-1", ImageType: model.ImageTypePrimary,
|
||||
Priority: model.ArtworkPriorityScan,
|
||||
})).To(Succeed())
|
||||
queueRepo.SetTrace(model.KindArtistArtwork, "ar-1", model.ImageTypePrimary, failure)
|
||||
|
||||
rep, err := artwork.Explain(ctx, ds, nil, model.KindArtistArtwork, "ar-1", artwork.ExplainOptions{})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(rep.Queued).ToNot(BeNil())
|
||||
Expect(rep.Queued.Priority).To(Equal(model.ArtworkPriorityScan))
|
||||
Expect(rep.LastAttemptFailed()).To(Equal([]artwork.TraceStep{
|
||||
{Candidate: "external:lastfm", Outcome: artwork.OutcomeError, Detail: "429"},
|
||||
}))
|
||||
})
|
||||
|
||||
It("records nothing for a kind that keeps no state and has no walker", func() {
|
||||
Expect(ds.Album().Put(ctx, &model.Album{ID: "al-1", Name: "OK Computer"})).To(Succeed())
|
||||
|
||||
rep, err := artwork.Explain(ctx, ds, nil, model.KindDiscArtwork, "al-1:2", artwork.ExplainOptions{})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(rep.Stored).To(BeNil())
|
||||
Expect(rep.Steps).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("performs a fresh walk and reports its outcome, including a failed one, when a walker is supplied", func() {
|
||||
// GetAll erroring mid-walk is a deterministic way to force ResolveErr without a real library.
|
||||
ds.Album().(*tests.MockAlbumRepo).SetError(true)
|
||||
opts := artwork.ExplainOptions{Walk: func(t *artwork.ChainTrace) *artwork.TracingResolver {
|
||||
return artwork.NewTracingResolver(ds, nil, nil, t, false)
|
||||
}}
|
||||
|
||||
rep, err := artwork.Explain(ctx, ds, nil, model.KindArtistArtwork, "ar-1", opts)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(rep.Walked).To(BeTrue())
|
||||
Expect(rep.ResolveErr).To(HaveOccurred())
|
||||
})
|
||||
|
||||
It("still reports Walked for a kind with no chain to walk, when a walker is supplied", func() {
|
||||
Expect(ds.Playlist().Put(ctx, &model.Playlist{ID: "pl-1", Name: "Favorites"})).To(Succeed())
|
||||
opts := artwork.ExplainOptions{Walk: func(*artwork.ChainTrace) *artwork.TracingResolver {
|
||||
panic("a kind that cannot walk must never be handed to the walker")
|
||||
}}
|
||||
|
||||
rep, err := artwork.Explain(ctx, ds, nil, model.KindPlaylistArtwork, "pl-1", opts)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(rep.Walked).To(BeTrue())
|
||||
})
|
||||
})
|
||||
|
|
@ -25,6 +25,13 @@ var ReprocessKinds = []model.Kind{
|
|||
// artwork is read through on every request and cached by content key, so it has neither.
|
||||
func KeepsState(kind model.Kind) bool { return kind != model.KindDiscArtwork }
|
||||
|
||||
// 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,
|
||||
}
|
||||
|
||||
// RefreshableKinds is every kind Refresh can clear and re-queue, so it holds exactly the kinds
|
||||
// KeepsState admits. Media files are absent from ReprocessKinds but belong here: the worker
|
||||
// resolves them, it just never enumerates them in bulk.
|
||||
|
|
|
|||
|
|
@ -3,14 +3,12 @@ package lyrics
|
|||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
. "github.com/Masterminds/squirrel"
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/persistence"
|
||||
"github.com/navidrome/navidrome/utils/cache"
|
||||
)
|
||||
|
||||
// maxLegacyLyricsCandidates bounds the duplicate window scanned by the legacy
|
||||
|
|
@ -18,12 +16,6 @@ import (
|
|||
// matches without turning it into an unbounded table scan.
|
||||
const maxLegacyLyricsCandidates = 10
|
||||
|
||||
const (
|
||||
lyricsCacheSize = 1000
|
||||
lyricsCacheTTL = 5 * time.Minute
|
||||
lyricsLoadTimeout = time.Minute
|
||||
)
|
||||
|
||||
// Provider fetches lyrics for a single media file. It is the contract
|
||||
// implemented by individual lyrics sources, such as plugins.
|
||||
type Provider interface {
|
||||
|
|
@ -45,25 +37,12 @@ type PluginLoader interface {
|
|||
type lyricsService struct {
|
||||
ds model.DataStore
|
||||
pluginLoader PluginLoader
|
||||
pluginCache cache.SimpleCache[pluginKey, model.LyricList]
|
||||
}
|
||||
|
||||
type pluginKey struct {
|
||||
plugin string
|
||||
mediaFileID string
|
||||
}
|
||||
|
||||
// NewLyrics creates a new lyrics service. pluginLoader may be nil if no plugin
|
||||
// system is available.
|
||||
func NewLyrics(ds model.DataStore, pluginLoader PluginLoader) Lyrics {
|
||||
return &lyricsService{
|
||||
ds: ds,
|
||||
pluginLoader: pluginLoader,
|
||||
pluginCache: cache.NewSimpleCache[pluginKey, model.LyricList](cache.Options{
|
||||
SizeLimit: lyricsCacheSize,
|
||||
DefaultTTL: lyricsCacheTTL,
|
||||
}),
|
||||
}
|
||||
return &lyricsService{ds: ds, pluginLoader: pluginLoader}
|
||||
}
|
||||
|
||||
// GetLyrics returns lyrics for the given media file, trying sources in the
|
||||
|
|
|
|||
|
|
@ -365,77 +365,6 @@ var _ = Describe("Lyrics", func() {
|
|||
})
|
||||
})
|
||||
|
||||
Context("caching", func() {
|
||||
var mockLoader *mockPluginLoader
|
||||
var svc lyrics.Lyrics
|
||||
|
||||
BeforeEach(func() {
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = "test-lyrics-plugin" })
|
||||
mockLoader = &mockPluginLoader{}
|
||||
svc = lyrics.NewLyrics(nil, mockLoader)
|
||||
mf.ID = "mf-1"
|
||||
})
|
||||
|
||||
It("serves a repeated request for the same track from the cache", func() {
|
||||
mockLoader.lyrics = unsyncedLyrics
|
||||
_, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(unsyncedLyrics))
|
||||
Expect(mockLoader.calls).To(Equal(1))
|
||||
})
|
||||
|
||||
It("caches a miss, so a track without lyrics does not reach the plugin again", func() {
|
||||
for range 2 {
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(BeEmpty())
|
||||
}
|
||||
Expect(mockLoader.calls).To(Equal(1))
|
||||
})
|
||||
|
||||
It("caches a plugin error as a miss, since some plugins report no lyrics as an error", func() {
|
||||
mockLoader.err = fmt.Errorf("no lyrics found from any provider")
|
||||
for range 2 {
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(BeEmpty())
|
||||
}
|
||||
Expect(mockLoader.calls).To(Equal(1))
|
||||
})
|
||||
|
||||
It("looks up each track separately", func() {
|
||||
other := mf
|
||||
other.ID = "mf-2"
|
||||
_, _ = svc.GetLyrics(ctx, &mf)
|
||||
_, _ = svc.GetLyrics(ctx, &other)
|
||||
Expect(mockLoader.calls).To(Equal(2))
|
||||
})
|
||||
|
||||
It("finishes and caches the lookup when the caller's request is cancelled", func() {
|
||||
mockLoader.lyrics = unsyncedLyrics
|
||||
cancelled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
|
||||
list, err := svc.GetLyrics(cancelled, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(unsyncedLyrics))
|
||||
|
||||
list, err = svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(unsyncedLyrics))
|
||||
Expect(mockLoader.calls).To(Equal(1))
|
||||
})
|
||||
|
||||
It("bounds the lookup with a deadline", func() {
|
||||
_, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mockLoader.hadDeadline).To(BeTrue())
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("GetLyricsByArtistTitle", func() {
|
||||
var svc lyrics.Lyrics
|
||||
var repo *tests.MockMediaFileRepo
|
||||
|
|
@ -481,12 +410,10 @@ var _ = Describe("Lyrics", func() {
|
|||
})
|
||||
|
||||
type mockPluginLoader struct {
|
||||
lyrics model.LyricList
|
||||
err error
|
||||
notFound bool
|
||||
pluginName string // expected plugin name (exact match, like real manager)
|
||||
calls int
|
||||
hadDeadline bool
|
||||
lyrics model.LyricList
|
||||
err error
|
||||
notFound bool
|
||||
pluginName string // expected plugin name (exact match, like real manager)
|
||||
}
|
||||
|
||||
func (m *mockPluginLoader) PluginNames(_ string) []string {
|
||||
|
|
@ -504,18 +431,14 @@ func (m *mockPluginLoader) LoadLyricsProvider(name string) (lyrics.Provider, boo
|
|||
if m.pluginName != "" && name != m.pluginName {
|
||||
return nil, false
|
||||
}
|
||||
return &mockLyricsProvider{loader: m}, true
|
||||
return &mockLyricsProvider{lyrics: m.lyrics, err: m.err}, true
|
||||
}
|
||||
|
||||
type mockLyricsProvider struct {
|
||||
loader *mockPluginLoader
|
||||
lyrics model.LyricList
|
||||
err error
|
||||
}
|
||||
|
||||
func (m *mockLyricsProvider) GetLyrics(ctx context.Context, _ *model.MediaFile) (model.LyricList, error) {
|
||||
m.loader.calls++
|
||||
_, m.loader.hadDeadline = ctx.Deadline()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m.loader.lyrics, m.loader.err
|
||||
func (m *mockLyricsProvider) GetLyrics(_ context.Context, _ *model.MediaFile) (model.LyricList, error) {
|
||||
return m.lyrics, m.err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import (
|
|||
"io"
|
||||
"io/fs"
|
||||
"path"
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/core/storage"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
|
|
@ -69,8 +68,7 @@ func fromExternalFile(ctx context.Context, mf *model.MediaFile, suffix string) (
|
|||
return list, nil
|
||||
}
|
||||
|
||||
// fromPlugin attempts to load lyrics from a plugin with the given name. Results are cached,
|
||||
// misses included: clients ask for every track in a queue, and plugin lookups are slow.
|
||||
// fromPlugin attempts to load lyrics from a plugin with the given name.
|
||||
func (l *lyricsService) fromPlugin(ctx context.Context, mf *model.MediaFile, pluginName string) (model.LyricList, error) {
|
||||
if l.pluginLoader == nil {
|
||||
log.Debug(ctx, "Invalid lyric source", "source", pluginName)
|
||||
|
|
@ -83,20 +81,13 @@ func (l *lyricsService) fromPlugin(ctx context.Context, mf *model.MediaFile, plu
|
|||
return nil, nil
|
||||
}
|
||||
|
||||
key := pluginKey{plugin: pluginName, mediaFileID: mf.ID}
|
||||
return l.pluginCache.GetWithLoader(key, func(pluginKey) (model.LyricList, time.Duration, error) {
|
||||
// Concurrent callers share one load, so one cancelled request must not abort it for the others.
|
||||
loadCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), lyricsLoadTimeout)
|
||||
defer cancel()
|
||||
lyricsList, err := provider.GetLyrics(loadCtx, mf)
|
||||
if err != nil {
|
||||
// Cached as a miss: some plugins report "no lyrics" as an error.
|
||||
log.Error(ctx, "Error getting lyrics from plugin", "plugin", pluginName, err)
|
||||
return nil, 0, nil
|
||||
}
|
||||
if len(lyricsList) > 0 {
|
||||
log.Trace(ctx, "Retrieved lyrics from plugin", "plugin", pluginName, "count", len(lyricsList))
|
||||
}
|
||||
return lyricsList, 0, nil
|
||||
})
|
||||
lyricsList, err := provider.GetLyrics(ctx, mf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(lyricsList) > 0 {
|
||||
log.Trace(ctx, "Retrieved lyrics from plugin", "plugin", pluginName, "count", len(lyricsList))
|
||||
}
|
||||
return lyricsList, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -136,14 +136,10 @@ ON CONFLICT (user_id, library_id) DO NOTHING;`,
|
|||
// TODO Remove this method when we have a proper UI to add libraries
|
||||
// This is a temporary method to store the music folder path from the config in the DB
|
||||
func (r *libraryRepository) StoreMusicFolder(ctx context.Context) error {
|
||||
changed := And{Eq{"id": model.DefaultLibraryID}, NotEq{"path": conf.Server().MusicFolder}}
|
||||
// An UPDATE takes the write lock even when nothing matches, and a startup scan may be holding it
|
||||
if needsUpdate, err := r.exists(ctx, changed); err != nil || !needsUpdate {
|
||||
return err
|
||||
}
|
||||
sq := Update(r.tableName).Set("path", conf.Server().MusicFolder).
|
||||
Set("updated_at", time.Now()).
|
||||
Where(changed)
|
||||
Where(Eq{"id": model.DefaultLibraryID}).
|
||||
Where(NotEq{"path": conf.Server().MusicFolder})
|
||||
rowsAffected, err := r.executeSQL(ctx, sq)
|
||||
if err == nil && rowsAffected > 0 {
|
||||
libLock.Lock()
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import (
|
|||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/db"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/model/request"
|
||||
|
|
@ -169,18 +168,6 @@ var _ = Describe("LibraryRepository", func() {
|
|||
Expect(libAfter.UpdatedAt).To(Equal(libBefore.UpdatedAt))
|
||||
})
|
||||
|
||||
It("does not need the write lock when the configured path is unchanged", func() {
|
||||
conf.Update(func(c *conf.Options) { c.MusicFolder = libBefore.Path })
|
||||
lockConn, err := db.Db().Conn(ctx)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
DeferCleanup(lockConn.Close)
|
||||
_, err = lockConn.ExecContext(ctx, "BEGIN IMMEDIATE")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
DeferCleanup(func() { _, _ = lockConn.ExecContext(context.Background(), "ROLLBACK") })
|
||||
|
||||
Expect(repo.StoreMusicFolder(ctx)).To(Succeed())
|
||||
})
|
||||
|
||||
It("updates the default library only when the configured path changes", func() {
|
||||
conf.Update(func(c *conf.Options) { c.MusicFolder = libBefore.Path + "-updated" })
|
||||
Expect(repo.StoreMusicFolder(ctx)).To(Succeed())
|
||||
|
|
|
|||
|
|
@ -545,18 +545,7 @@ func (r *mediaFileRepository) FindRecentFilesByMBZTrackID(ctx context.Context, m
|
|||
// FindRecentFilesByProperties finds recently added files by intrinsic properties in other libraries
|
||||
// It uses a lightweight query without annotation/bookmark joins since those are not needed for matching
|
||||
func (r *mediaFileRepository) FindRecentFilesByProperties(ctx context.Context, missing model.MediaFile, since time.Time) (model.MediaFiles, error) {
|
||||
var res dbMediaFiles
|
||||
err := r.queryAll(ctx, recentFilesByPropertiesQuery(missing, since), &res)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res.toModels(), nil
|
||||
}
|
||||
|
||||
func recentFilesByPropertiesQuery(missing model.MediaFile, since time.Time) SelectBuilder {
|
||||
// Many files share mbz_release_track_id = '', so the planner's pick of that index scans them all
|
||||
return Select("media_file.*", "library.path as library_path", "library.name as library_name").
|
||||
From("media_file INDEXED BY media_file_title").
|
||||
sel := r.newSelect(ctx).Columns("media_file.*", "library.path as library_path", "library.name as library_name").
|
||||
LeftJoin("library on media_file.library_id = library.id").
|
||||
Where(And{
|
||||
NotEq{"media_file.library_id": missing.LibraryID},
|
||||
|
|
@ -570,6 +559,13 @@ func recentFilesByPropertiesQuery(missing model.MediaFile, since time.Time) Sele
|
|||
Gt{"media_file.created_at": since},
|
||||
Eq{"media_file.missing": false},
|
||||
}).OrderBy("media_file.created_at DESC")
|
||||
|
||||
var res dbMediaFiles
|
||||
err := r.queryAll(ctx, sel, &res)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res.toModels(), nil
|
||||
}
|
||||
|
||||
var mediaFileSearchConfig = searchConfig{
|
||||
|
|
|
|||
|
|
@ -1203,73 +1203,6 @@ var _ = Describe("MediaRepository", func() {
|
|||
})
|
||||
})
|
||||
|
||||
Describe("FindRecentFilesByProperties", func() {
|
||||
var adminCtx context.Context
|
||||
var otherLib model.Library
|
||||
var missing model.MediaFile
|
||||
var since time.Time
|
||||
|
||||
BeforeEach(func() {
|
||||
adminCtx, otherLib, _ = restrictedFixture("moved")
|
||||
since = time.Now().Add(-time.Hour)
|
||||
missing = model.MediaFile{
|
||||
LibraryID: 1, Title: "Moved Song", Album: "Moved Album", Size: 1234,
|
||||
Suffix: "flac", DiscNumber: 1, TrackNumber: 3,
|
||||
}
|
||||
})
|
||||
|
||||
candidate := func(id string, change func(*model.MediaFile)) {
|
||||
mf := missing
|
||||
mf.ID, mf.LibraryID, mf.Path, mf.CreatedAt = id, otherLib.ID, id+".flac", since.Add(time.Minute)
|
||||
if change != nil {
|
||||
change(&mf)
|
||||
}
|
||||
Expect(mr.Put(adminCtx, &mf)).To(Succeed())
|
||||
DeferCleanup(func() { _ = mr.Delete(adminCtx, mf.ID) })
|
||||
}
|
||||
|
||||
It("returns only recent, present, untagged copies from other libraries", func() {
|
||||
candidate("moved-match", nil)
|
||||
candidate("moved-same-lib", func(mf *model.MediaFile) { mf.LibraryID = 1 })
|
||||
candidate("moved-tagged", func(mf *model.MediaFile) { mf.MbzReleaseTrackID = "some-mbid" })
|
||||
candidate("moved-older", func(mf *model.MediaFile) { mf.CreatedAt = since.Add(-time.Minute) })
|
||||
candidate("moved-missing", func(mf *model.MediaFile) { mf.Missing = true })
|
||||
candidate("moved-other-title", func(mf *model.MediaFile) { mf.Title = "Another Song" })
|
||||
|
||||
results, err := mr.FindRecentFilesByProperties(adminCtx, missing, since)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(slice.Map(results, func(mf model.MediaFile) string { return mf.ID })).To(ConsistOf("moved-match"))
|
||||
Expect(results[0].LibraryPath).To(Equal(otherLib.Path))
|
||||
})
|
||||
|
||||
It("searches by title even when stats make the MBZ track ID index look more selective", func() {
|
||||
conn := GetDBXBuilder().DB()
|
||||
tx, err := conn.BeginTx(adminCtx, nil)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
// The schema, and so the loaded stats, are shared by every connection to the in-memory DB
|
||||
DeferCleanup(func() {
|
||||
Expect(tx.Rollback()).To(Succeed())
|
||||
_, err := conn.Exec("ANALYZE sqlite_schema")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
for _, stmt := range []string{
|
||||
"ANALYZE media_file_title",
|
||||
"DELETE FROM sqlite_stat1 WHERE tbl = 'media_file'",
|
||||
"INSERT INTO sqlite_stat1 VALUES ('media_file', 'media_file_title', '40000 2'), ('media_file', 'media_file_mbz_release_track_id', '40000 1'), ('media_file', 'media_file_created_at', '40000 1')",
|
||||
"ANALYZE sqlite_schema",
|
||||
} {
|
||||
_, err := tx.Exec(stmt)
|
||||
Expect(err).ToNot(HaveOccurred(), stmt)
|
||||
}
|
||||
|
||||
query, args, err := recentFilesByPropertiesQuery(missing, since).ToSql()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
plan, err := queryPlan(tx, query, args...)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(plan).To(ContainElement(ContainSubstring("USING INDEX media_file_title")))
|
||||
})
|
||||
})
|
||||
|
||||
Describe("dbMediaFile.String", func() {
|
||||
It("does not dereference a nil MediaFile", func() {
|
||||
Expect(fmt.Sprint(dbMediaFile{})).To(Equal("<nil>"))
|
||||
|
|
|
|||
|
|
@ -140,30 +140,24 @@ var _ = Describe("Sort index coverage", func() {
|
|||
// "USE TEMP B-TREE FOR LAST TERM OF ORDER BY" (or "LAST N TERMS") and are allowed.
|
||||
var fullTempBTreeSort = regexp.MustCompile(`USE TEMP B-TREE FOR ORDER BY`)
|
||||
|
||||
func queryPlan(conn interface {
|
||||
Query(string, ...any) (*sql.Rows, error)
|
||||
}, query string, args ...any) ([]string, error) {
|
||||
rows, err := conn.Query("explain query plan "+query, args...)
|
||||
func checkSortUsesIndex(conn *sql.DB, table, orderBy string) error {
|
||||
rows, err := conn.Query(fmt.Sprintf("explain query plan select * from %s order by %s limit 15", table, orderBy))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return fmt.Errorf("explain query plan failed for order by %q: %w", orderBy, err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var details []string
|
||||
for rows.Next() {
|
||||
var id, parent, notUsed int
|
||||
var detail string
|
||||
if err := rows.Scan(new(int), new(int), new(int), &detail); err != nil {
|
||||
return nil, err
|
||||
if err := rows.Scan(&id, &parent, ¬Used, &detail); err != nil {
|
||||
return err
|
||||
}
|
||||
details = append(details, detail)
|
||||
}
|
||||
return details, rows.Err()
|
||||
}
|
||||
|
||||
func checkSortUsesIndex(conn *sql.DB, table, orderBy string) error {
|
||||
details, err := queryPlan(conn, fmt.Sprintf("select * from %s order by %s limit 15", table, orderBy))
|
||||
if err != nil {
|
||||
return fmt.Errorf("explain query plan failed for order by %q: %w", orderBy, err)
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if slices.ContainsFunc(details, fullTempBTreeSort.MatchString) {
|
||||
return fmt.Errorf("no index satisfies ORDER BY %s - plan: %v", orderBy, details)
|
||||
|
|
|
|||
|
|
@ -38,8 +38,6 @@
|
|||
"missing": "Manquant",
|
||||
"libraryName": "Bibliothèque",
|
||||
"composer": "Compositeur·e",
|
||||
"albumGain": "Gain de l'album",
|
||||
"trackGain": "Gain du titre",
|
||||
"disc": "Disque %{discNumber}"
|
||||
},
|
||||
"actions": {
|
||||
|
|
@ -51,7 +49,7 @@
|
|||
"playNext": "Jouer ensuite",
|
||||
"info": "Plus d'informations",
|
||||
"showInPlaylist": "Montrer dans la playlist",
|
||||
"instantMix": "Mix instantané"
|
||||
"instantMix": "Mix instantanné"
|
||||
}
|
||||
},
|
||||
"album": {
|
||||
|
|
@ -83,8 +81,7 @@
|
|||
"mood": "Humeur",
|
||||
"date": "Date d'enregistrement",
|
||||
"missing": "Manquant",
|
||||
"libraryName": "Bibliothèque",
|
||||
"played": "Écouté"
|
||||
"libraryName": "Bibliothèque"
|
||||
},
|
||||
"actions": {
|
||||
"playAll": "Lire",
|
||||
|
|
@ -94,8 +91,7 @@
|
|||
"addToPlaylist": "Ajouter à la playlist",
|
||||
"download": "Télécharger",
|
||||
"info": "Plus d'informations",
|
||||
"share": "Partager",
|
||||
"refresh": "Actualiser les métadonnées"
|
||||
"share": "Partager"
|
||||
},
|
||||
"lists": {
|
||||
"all": "Tous",
|
||||
|
|
@ -157,13 +153,11 @@
|
|||
"newPassword": "Nouveau mot de passe",
|
||||
"token": "Token",
|
||||
"lastAccessAt": "Dernier accès",
|
||||
"libraries": "Bibliothèques",
|
||||
"scrobbleFilter": "Filtre de scrobble"
|
||||
"libraries": "Bibliothèques"
|
||||
},
|
||||
"helperTexts": {
|
||||
"name": "Les changements liés à votre nom ne seront reflétés qu'à la prochaine connexion",
|
||||
"libraries": "Sélectionner des bibliothèques pour cet utilisateur, ou laisser vide pour utiliser les bibliothèques par défaut",
|
||||
"scrobbleFilter": "Les titres correspondant à ces règles de playlist intelligente ne sont pas envoyés à Last.fm, à ListenBrainz ou aux extensions de scrobble. Ce filtre utilise la même syntaxe JSON et le même comportement que les playlists intelligentes. Exemple : {\"all\":[{\"lt\":{\"rating\":4}}]}. Laisser vide pour tout scrobbler. Les compteurs d'écoutes locaux ne sont pas modifiés."
|
||||
"libraries": "Sélectionner une bibliothèque pour cet utilisateur ou laisser vide pour utiliser la bibliothèque par défaut"
|
||||
},
|
||||
"notifications": {
|
||||
"created": "Utilisateur créé",
|
||||
|
|
@ -177,13 +171,11 @@
|
|||
"adminAutoLibraries": "Les utilisateurs admin ont automatiquement accès à l'ensemble des bibliothèques"
|
||||
},
|
||||
"validation": {
|
||||
"librariesRequired": "Au moins une bibliothèque doit être sélectionnée pour les utilisateurs non administrateurs",
|
||||
"invalidScrobbleFilter": "Le filtre doit contenir des règles de playlist intelligente valides. Les options limit et offset, ainsi que le délai d'actualisation, ne sont pas prises en charge."
|
||||
"librariesRequired": "Au moins une bibliothèque doit être sélectionnée pour les utilisateurs non administrateurs"
|
||||
}
|
||||
},
|
||||
"player": {
|
||||
"name": "Lecteur |||| Lecteurs",
|
||||
"menuName": "Lecteurs et clés API",
|
||||
"fields": {
|
||||
"name": "Nom",
|
||||
"transcodingId": "Transcodage",
|
||||
|
|
@ -192,29 +184,7 @@
|
|||
"userName": "Nom d'utilisateur",
|
||||
"lastSeen": "Vu pour la dernière fois",
|
||||
"reportRealPath": "Rapporter le chemin d'accès absolu",
|
||||
"scrobbleEnabled": "Scrobbler vers des services externes",
|
||||
"hasApiKey": "Clé API"
|
||||
},
|
||||
"actions": {
|
||||
"generateApiKey": "Générer une clé API",
|
||||
"regenerateApiKey": "Régénérer",
|
||||
"revokeApiKey": "Révoquer",
|
||||
"copyApiKey": "Copier"
|
||||
},
|
||||
"message": {
|
||||
"apiKeyActive": "Ce lecteur possède une clé API. Utilisez-la dans votre application comme clé API, ou comme mot de passe si l'application n'utilise pas l'authentification par token.",
|
||||
"apiKeyNone": "Aucune clé API. Générez-en une pour connecter une application à ce lecteur.",
|
||||
"apiKeyNoneOther": "Aucune clé API.",
|
||||
"apiKeyPending": "Copiez cette clé maintenant. Elle sera enregistrée lorsque vous cliquerez sur Enregistrer et ne sera plus affichée ensuite.",
|
||||
"apiKeyRevokePending": "La clé API sera supprimée lors de l'enregistrement.",
|
||||
"deleteWithKeyTitle": "Supprimer le lecteur",
|
||||
"deleteWithKeyContent": "Ce lecteur possède une clé API. Les applications qui l'utilisent cesseront de fonctionner."
|
||||
},
|
||||
"notifications": {
|
||||
"apiKeyCopied": "Clé API copiée dans le presse-papiers"
|
||||
},
|
||||
"validation": {
|
||||
"apiKeyFormat": "Format de clé API invalide"
|
||||
"scrobbleEnabled": "Scrobbler vers des services externes"
|
||||
}
|
||||
},
|
||||
"transcoding": {
|
||||
|
|
@ -224,9 +194,6 @@
|
|||
"targetFormat": "Format",
|
||||
"defaultBitRate": "Bitrate par défaut",
|
||||
"command": "Commande"
|
||||
},
|
||||
"choices": {
|
||||
"noDefaultBitRate": "Aucun"
|
||||
}
|
||||
},
|
||||
"playlist": {
|
||||
|
|
@ -241,8 +208,7 @@
|
|||
"songCount": "Morceaux",
|
||||
"comment": "Commentaire",
|
||||
"sync": "Import automatique",
|
||||
"path": "Importer depuis",
|
||||
"starred": "Favoris"
|
||||
"path": "Importer depuis"
|
||||
},
|
||||
"actions": {
|
||||
"selectPlaylist": "Sélectionner une playlist :",
|
||||
|
|
@ -290,9 +256,7 @@
|
|||
"updatedAt": "Mis à jour le",
|
||||
"createdAt": "Créé le",
|
||||
"downloadable": "Autoriser les téléchargements ?"
|
||||
},
|
||||
"notifications": {},
|
||||
"actions": {}
|
||||
}
|
||||
},
|
||||
"missing": {
|
||||
"name": "Fichier manquant|||| Fichiers manquants",
|
||||
|
|
@ -330,23 +294,12 @@
|
|||
"totalSize": "Taille totale",
|
||||
"totalDuration": "Durée",
|
||||
"defaultNewUsers": "Défaut pour les nouveaux utilisateurs",
|
||||
"createdAt": "Créée le",
|
||||
"updatedAt": "Mise à jour le",
|
||||
"pidAlbum": "Regroupement des albums",
|
||||
"pidTrack": "Identification des titres"
|
||||
"createdAt": "Crée",
|
||||
"updatedAt": "Mise à jour"
|
||||
},
|
||||
"sections": {
|
||||
"basic": "Informations",
|
||||
"statistics": "Statistiques",
|
||||
"pid": "Identifiants persistants"
|
||||
},
|
||||
"pid": {
|
||||
"global": "Utiliser le paramètre global (%{value})",
|
||||
"folder": "Dossier (un album par dossier)",
|
||||
"custom": "Personnalisé",
|
||||
"spec": "Spécification du PID",
|
||||
"help": "Étiquettes et attributs qui identifient un élément. Consultez la documentation pour connaître la syntaxe :",
|
||||
"docs": "Identifiants persistants"
|
||||
"statistics": "Statistiques"
|
||||
},
|
||||
"actions": {
|
||||
"scan": "Scanner la bibliothèque",
|
||||
|
|
@ -376,9 +329,7 @@
|
|||
"messages": {
|
||||
"deleteConfirm": "Êtes-vous sûr(e) de vouloir supprimer cette bibliothèque ? Cela supprimera toutes les données associées ainsi que les accès utilisateurs.",
|
||||
"scanInProgress": "Scan en cours...",
|
||||
"noLibrariesAssigned": "Aucune bibliothèque pour cet utilisateur",
|
||||
"pidChangeTitle": "Modifier les identifiants persistants ?",
|
||||
"pidChangeConfirm": "Cela regroupe à nouveau les albums et les titres de cette bibliothèque. Un scan complet de cette bibliothèque démarre maintenant. Les favoris, les notes et les nombres d'écoutes des titres sont conservés. Les favoris et les notes des albums sont reportés sur les nouveaux albums lorsqu'un ancien album correspond à un nouveau."
|
||||
"noLibrariesAssigned": "Aucune bibliothèque pour cet utilisateur"
|
||||
}
|
||||
},
|
||||
"plugin": {
|
||||
|
|
@ -388,7 +339,7 @@
|
|||
"name": "Nom",
|
||||
"description": "Description",
|
||||
"version": "Version",
|
||||
"author": "Auteur·rice",
|
||||
"author": "Auteur.e",
|
||||
"website": "Site web",
|
||||
"permissions": "Permissions",
|
||||
"enabled": "Activée",
|
||||
|
|
@ -398,10 +349,10 @@
|
|||
"hasError": "Erreur",
|
||||
"updatedAt": "Mise à jour",
|
||||
"createdAt": "Installée",
|
||||
"configKey": "Clé",
|
||||
"configKey": "Clef",
|
||||
"configValue": "Valeur",
|
||||
"allUsers": "Autoriser tous les utilisateur·rices",
|
||||
"selectedUsers": "Utilisateur·rices sélectionné·e·s",
|
||||
"selectedUsers": "Utilisateur·rices sélectionné.e.s",
|
||||
"allLibraries": "Autoriser toutes les bibliothèques",
|
||||
"selectedLibraries": "Bibliothèques sélectionnées",
|
||||
"allowWriteAccess": "Autoriser l'accès en écriture"
|
||||
|
|
@ -411,7 +362,7 @@
|
|||
"info": "Informations de l'extension",
|
||||
"configuration": "Configuration",
|
||||
"manifest": "Manifeste",
|
||||
"usersPermission": "Permissions utilisateur·rices",
|
||||
"usersPermission": "Permissions utilisateur·ices",
|
||||
"libraryPermission": "Permissions des bibliothèques"
|
||||
},
|
||||
"status": {
|
||||
|
|
@ -421,8 +372,8 @@
|
|||
"actions": {
|
||||
"enable": "Activer",
|
||||
"disable": "Désactiver",
|
||||
"disabledDueToError": "Corriger l'erreur avant d'activer l'extension",
|
||||
"disabledUsersRequired": "Sélectionner des utilisateur·rices avant d'activer l'extension",
|
||||
"disabledDueToError": "L'erreur doit être réglée avant de pouvoir activer la bibliothèque",
|
||||
"disabledUsersRequired": "Sélectionner des utilisateur·ices avant d'activer la bibliothèque",
|
||||
"disabledLibrariesRequired": "Sélectionner au moins une bibliothèque",
|
||||
"addConfig": "Ajouter une configuration",
|
||||
"rescan": "Rescanner"
|
||||
|
|
@ -437,24 +388,23 @@
|
|||
"invalidJson": "La configuration doit être un JSON valide"
|
||||
},
|
||||
"messages": {
|
||||
"idHelp": "L'identifiant de l'extension, dérivé du nom de son fichier. Utilisez-le pour faire référence à cette extension dans les options de configuration, comme Agents.",
|
||||
"configHelp": "Configurer l'extension à l'aide de paires clé/valeur. Laisser vide si l'extension ne requiert aucune configuration.",
|
||||
"configHelp": "Configurer l'extension en utilisant des paires clef/valeurs. Laisser vide si l'extension ne requiert aucune configuration.",
|
||||
"clickPermissions": "Cliquer sur une permission pour plus de détails",
|
||||
"noConfig": "Aucune configuration",
|
||||
"allUsersHelp": "Lorsque cette option est activée, l'extension aura accès à l'ensemble des utilisateur·rices, y compris celles et ceux créé·e·s à l'avenir.",
|
||||
"noUsers": "Aucun·e utilisateur·rice sélectionné·e",
|
||||
"allUsersHelp": "Quand sélectionnée, l'extension aura accès à l'ensemble des utilisateur·rices, y compris ceux créé.e.s dans le future.",
|
||||
"noUsers": "Aucun.e utilisateur·rice sélectionné.e",
|
||||
"permissionReason": "Raison",
|
||||
"usersRequired": "Cette extension nécessite un accès aux informations utilisateurs. Sélectionnez les utilisateur·rices autorisé·e·s ou cochez « Autoriser tous les utilisateur·rices ».",
|
||||
"allLibrariesHelp": "Lorsque cette option est activée, cette extension aura accès à l'ensemble des bibliothèques, y compris celles créées à l'avenir.",
|
||||
"usersRequired": "Cette extension nécessite un accès aux informations utilisateurs. Sélectionnez les utilisateur·rices autorisé.e.s ou sélectionnez 'Tout autoriser'.",
|
||||
"allLibrariesHelp": "Quand sélectionnée, cette extension aura accès à l'ensemble des bibliothèques, y compris celles créées dans le futur.",
|
||||
"noLibraries": "Aucune bibliothèque sélectionnée",
|
||||
"librariesRequired": "Cette extension nécessite l'accès aux informations des bibliothèques. Sélectionnez les bibliothèques auxquelles cette extension a accès, ou cochez « Autoriser toutes les bibliothèques ».",
|
||||
"librariesRequired": "Cette extension nécessite l'accès aux information de la bibliothèque. Sélectionnez à quelles bibliothèque cette extension a accès, ou sélectionnez 'Autoriser toutes les bibliothèques'.",
|
||||
"requiredHosts": "Hôtes requis",
|
||||
"configValidationError": "Erreur lors de la validation de la configuration",
|
||||
"schemaRenderError": "Impossible d'afficher le formulaire de configuration. Le schéma de l'extension n'est peut-être pas valide.",
|
||||
"allowWriteAccessHelp": "Lorsque cette option est activée, l'extension peut modifier les fichiers dans les répertoires de la bibliothèque. Par défaut, les extensions ont un accès en lecture seule."
|
||||
"schemaRenderError": "Impossible de processer la configuration. Le schéma de l'extension n'est peut-être pas valide.",
|
||||
"allowWriteAccessHelp": "Lorsque cette option est activée, le plugin peut modifier les fichiers dans les répertoires de la bibliothèque. Par défaut, les plugins ont un accès en lecture seule."
|
||||
},
|
||||
"placeholders": {
|
||||
"configKey": "clé",
|
||||
"configKey": "clef",
|
||||
"configValue": "valeur"
|
||||
}
|
||||
}
|
||||
|
|
@ -511,7 +461,7 @@
|
|||
"show": "Afficher",
|
||||
"sort": "Trier",
|
||||
"undo": "Annuler",
|
||||
"expand": "Développer",
|
||||
"expand": "Étendre",
|
||||
"close": "Fermer",
|
||||
"open_menu": "Ouvrir le menu",
|
||||
"close_menu": "Fermer le menu",
|
||||
|
|
@ -606,7 +556,7 @@
|
|||
},
|
||||
"message": {
|
||||
"note": "NOTE",
|
||||
"transcodingDisabled": "Le changement de paramètres depuis l'interface web est désactivé pour des raisons de sécurité. Pour modifier ou supprimer les options de transcodage, relancez le serveur avec l'option %{config} activée.",
|
||||
"transcodingDisabled": "Le changement de paramètres depuis l'interface web est désactivé pour des raisons de sécurité. Pour changer (éditer ou supprimer) les options de transcodage, relancer le serveur avec l'option %{config} activée.",
|
||||
"transcodingEnabled": "Navidrome fonctionne actuellement avec %{config}, rendant possible l’exécution de commandes arbitraires depuis l'interface web. Il est recommandé d'activer cette fonctionnalité uniquement lors de la configuration du transcodage.",
|
||||
"songsAddedToPlaylist": "1 titre a été ajouté à la playlist |||| %{smart_count} titres ont été ajoutés à la playlist",
|
||||
"noPlaylistsAvailable": "Aucune playlist",
|
||||
|
|
@ -638,7 +588,7 @@
|
|||
"remove_missing_title": "Supprimer les fichiers manquants",
|
||||
"remove_missing_content": "Êtes-vous sûr(e) de vouloir supprimer les fichiers manquants sélectionnés de la base de données ? Ceci supprimera définitivement toute référence à ceux-ci, y compris leurs nombres d'écoutes et leurs notations",
|
||||
"remove_all_missing_title": "Supprimer tous les fichiers manquants",
|
||||
"remove_all_missing_content": "Êtes-vous sûr(e) de vouloir supprimer tous les fichiers manquants de la base de données ? Cette action est permanente et supprimera leurs nombres d'écoutes, leurs notes et tout ce qui y fait référence.",
|
||||
"remove_all_missing_content": "Êtes-vous sûr(e) de vouloir supprimer tous les fichiers manquants de la base de données ? Cette action est permanente et supprimera leurs nombres d'écoutes, leur notations et tout ce qui y fait référence.",
|
||||
"noSimilarSongsFound": "Aucun titre similaire n'a été trouvé",
|
||||
"noTopSongsFound": "Aucun meilleur titre n'a été trouvé",
|
||||
"startingInstantMix": "Chargement du mix instantané...",
|
||||
|
|
@ -647,11 +597,7 @@
|
|||
"coverUploaded": "Pochette mise à jour",
|
||||
"coverRemoved": "Pochette supprimée",
|
||||
"coverUploadError": "Erreur lors du téléversement de la pochette",
|
||||
"coverRemoveError": "Erreur lors de la suppression de la pochette",
|
||||
"metadataRefreshStarted": "Actualisation des métadonnées en arrière-plan",
|
||||
"quickConnectApproved": "%{app} sur %{device} est maintenant connecté",
|
||||
"quickConnectInvalidCode": "Code invalide ou expiré",
|
||||
"quickConnectError": "Impossible de valider le code"
|
||||
"coverRemoveError": "Erreur lors de la suppression de la pochette"
|
||||
},
|
||||
"menu": {
|
||||
"library": "Bibliothèque",
|
||||
|
|
@ -663,11 +609,6 @@
|
|||
"options": {
|
||||
"theme": "Thème",
|
||||
"language": "Langue",
|
||||
"dateFormat": "Format de date",
|
||||
"dateFormats": {
|
||||
"language": "Selon la langue",
|
||||
"browser": "Selon le navigateur"
|
||||
},
|
||||
"defaultView": "Vue par défaut",
|
||||
"desktop_notifications": "Notifications de bureau",
|
||||
"lastfmScrobbling": "Scrobbler vers Last.fm",
|
||||
|
|
@ -679,7 +620,7 @@
|
|||
"album": "Utiliser le gain de l'album",
|
||||
"track": "Utiliser le gain des titres"
|
||||
},
|
||||
"lastfmNotConfigured": "La clé API de Last.fm n'est pas configurée"
|
||||
"lastfmNotConfigured": "La clef API de Last.fm n'est pas configurée"
|
||||
}
|
||||
},
|
||||
"albumList": "Albums",
|
||||
|
|
@ -691,16 +632,7 @@
|
|||
"multipleLibraries": "%{selected} bibliothèque(s) sélectionnée(s) sur %{total}",
|
||||
"selectLibraries": "Sélectionner les bibliothèques",
|
||||
"none": "Aucune"
|
||||
},
|
||||
"quickConnect": {
|
||||
"name": "Connexion rapide",
|
||||
"code": "Code",
|
||||
"help": "Saisissez le code affiché par une application Jellyfin pour la connecter à votre compte",
|
||||
"confirm": "Connecter %{app} %{version} sur %{device} à votre compte ?",
|
||||
"continue": "Continuer",
|
||||
"approve": "Approuver"
|
||||
},
|
||||
"onlyFavourites": "Afficher uniquement les favoris"
|
||||
}
|
||||
},
|
||||
"player": {
|
||||
"playListsText": "File de lecture",
|
||||
|
|
@ -731,8 +663,8 @@
|
|||
"links": {
|
||||
"homepage": "Page d'accueil",
|
||||
"source": "Code source",
|
||||
"featureRequests": "Demandes de fonctionnalités",
|
||||
"lastInsightsCollection": "Dernière collecte des données",
|
||||
"featureRequests": "Demande de fonctionnalités",
|
||||
"lastInsightsCollection": "Dernière collection des données",
|
||||
"insights": {
|
||||
"disabled": "Désactivée",
|
||||
"waiting": "En attente"
|
||||
|
|
@ -786,4 +718,4 @@
|
|||
"empty": "Aucun titre en cours de lecture",
|
||||
"minutesAgo": "Il y a %{smart_count} minute |||| Il y a %{smart_count} minutes"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -175,7 +175,7 @@ flowchart TD
|
|||
1. **Folder Traversal**
|
||||
- Uses `walkDirTree` to traverse the directory structure
|
||||
- Handles symbolic links and hidden files
|
||||
- Processes `.ndignore` files for exclusions, and skips folders containing a `.nomedia` file when `Scanner.RespectNoMedia` is enabled
|
||||
- Processes `.ndignore` files for exclusions
|
||||
- Maps files to appropriate types (audio, image, playlist)
|
||||
|
||||
2. **Metadata Extraction**
|
||||
|
|
|
|||
|
|
@ -7,14 +7,11 @@ import (
|
|||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
ignore "github.com/sabhiram/go-gitignore"
|
||||
)
|
||||
|
||||
const ignoreAllPattern = "**/*"
|
||||
|
||||
// IgnoreChecker manages .ndignore patterns using a stack-based approach.
|
||||
// Use Push() to add patterns when entering a folder, Pop() when leaving,
|
||||
// and ShouldIgnore() to check if a path should be ignored.
|
||||
|
|
@ -83,24 +80,6 @@ func (ic *IgnoreChecker) PushAllParents(ctx context.Context, targetPath string)
|
|||
return nil
|
||||
}
|
||||
|
||||
// PushParents pushes the patterns of each folder above target, from the root down. It returns true,
|
||||
// and stops, when target or a folder above it is ignored, as a full walk would never reach target.
|
||||
func (ic *IgnoreChecker) PushParents(ctx context.Context, target string) bool {
|
||||
target = path.Clean(target)
|
||||
if target == "." {
|
||||
return false
|
||||
}
|
||||
dir := "."
|
||||
for part := range strings.SplitSeq(target, "/") {
|
||||
_ = ic.Push(ctx, dir)
|
||||
dir = path.Join(dir, part)
|
||||
if ic.ShouldIgnore(ctx, dir) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ShouldIgnore checks if the given path should be ignored based on the current patterns.
|
||||
// Returns true if the path matches any ignore pattern, false otherwise.
|
||||
func (ic *IgnoreChecker) ShouldIgnore(ctx context.Context, relPath string) bool {
|
||||
|
|
@ -116,22 +95,15 @@ func (ic *IgnoreChecker) ShouldIgnore(ctx context.Context, relPath string) bool
|
|||
|
||||
matches := ic.matcher.MatchesPath(relPath)
|
||||
if matches {
|
||||
log.Trace(ctx, "Scanner: Ignoring entry matching ignore rules", "path", relPath)
|
||||
log.Trace(ctx, "Scanner: Ignoring entry matching .ndignore", "path", relPath)
|
||||
}
|
||||
return matches
|
||||
}
|
||||
|
||||
// loadPatternsFromFolder reads the .ndignore file in the specified folder and returns the patterns.
|
||||
// If the file doesn't exist, returns an empty slice.
|
||||
// If the file exists but is empty, or there is a .nomedia file with Scanner.RespectNoMedia, ignores everything.
|
||||
// If the file exists but is empty, returns a pattern to ignore everything ("**/*").
|
||||
func (ic *IgnoreChecker) loadPatternsFromFolder(ctx context.Context, folder string) []string {
|
||||
if conf.Server().Scanner.RespectNoMedia {
|
||||
if _, err := fs.Stat(ic.fsys, path.Join(folder, consts.NoMediaFile)); err == nil {
|
||||
log.Trace(ctx, "Scanner: .nomedia file found, ignoring everything", "path", folder)
|
||||
return []string{ignoreAllPattern}
|
||||
}
|
||||
}
|
||||
|
||||
ignoreFilePath := path.Join(folder, consts.ScanIgnoreFile)
|
||||
var patterns []string
|
||||
|
||||
|
|
@ -166,7 +138,7 @@ func (ic *IgnoreChecker) loadPatternsFromFolder(ctx context.Context, folder stri
|
|||
// If the .ndignore file is empty, ignore everything
|
||||
if len(patterns) == 0 {
|
||||
log.Trace(ctx, "Scanner: .ndignore file is empty, ignoring everything", "path", folder)
|
||||
patterns = []string{ignoreAllPattern}
|
||||
patterns = []string{"**/*"}
|
||||
}
|
||||
|
||||
return patterns
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import (
|
|||
"context"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
|
@ -38,26 +37,6 @@ var _ = Describe("IgnoreChecker", func() {
|
|||
})
|
||||
})
|
||||
|
||||
DescribeTable("when .nomedia file exists",
|
||||
func(respectNoMedia bool, files fstest.MapFS, expected []string) {
|
||||
conf.Update(func(c *conf.Options) { c.Scanner.RespectNoMedia = respectNoMedia })
|
||||
ic = newIgnoreChecker(files)
|
||||
patterns := ic.loadPatternsFromFolder(ctx, ".")
|
||||
Expect(patterns).To(Equal(expected))
|
||||
},
|
||||
Entry("empty", true, fstest.MapFS{".nomedia": &fstest.MapFile{}}, []string{"**/*"}),
|
||||
Entry("with content", true, fstest.MapFS{".nomedia": &fstest.MapFile{Data: []byte("*.txt")}}, []string{"**/*"}),
|
||||
Entry("alongside .ndignore", true, fstest.MapFS{
|
||||
".nomedia": &fstest.MapFile{},
|
||||
".ndignore": &fstest.MapFile{Data: []byte("*.txt")},
|
||||
}, []string{"**/*"}),
|
||||
Entry("disabled", false, fstest.MapFS{".nomedia": &fstest.MapFile{}}, []string(nil)),
|
||||
Entry("disabled, alongside .ndignore", false, fstest.MapFS{
|
||||
".nomedia": &fstest.MapFile{},
|
||||
".ndignore": &fstest.MapFile{Data: []byte("*.txt")},
|
||||
}, []string{"*.txt"}),
|
||||
)
|
||||
|
||||
DescribeTable("parsing .ndignore content",
|
||||
func(content string, expectedPatterns []string) {
|
||||
fsys := fstest.MapFS{
|
||||
|
|
|
|||
|
|
@ -44,8 +44,7 @@ var _ = Describe("runPhase", func() {
|
|||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
sum.Store(0)
|
||||
ctx = context.Background()
|
||||
phaseNum = 1
|
||||
phase = &mockPhase{
|
||||
num: 3,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ package scanner_test
|
|||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing/fstest"
|
||||
"time"
|
||||
|
|
@ -42,13 +41,9 @@ var _ = Describe("Scanner - Multi-Library", Ordered, func() {
|
|||
}
|
||||
|
||||
BeforeAll(func() {
|
||||
tests.SkipOnWindows("SQLite file lock blocks TempDir cleanup (#TBD-path-sep-scanner)")
|
||||
ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "123", IsAdmin: true})
|
||||
// db.Db() is a process-wide singleton, so this dir may hold the open DB until
|
||||
// the suite ends, and Windows can't delete an open file
|
||||
tmpDir, err := os.MkdirTemp("", "scanner-test")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
DeferCleanup(func() { _ = os.RemoveAll(tmpDir) })
|
||||
DeferCleanup(conf.SnapshotConfig())
|
||||
tmpDir := GinkgoT().TempDir()
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DbPath = filepath.Join(tmpDir, "test-scanner-multilibrary.db?_journal_mode=WAL")
|
||||
})
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ package scanner_test
|
|||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing/fstest"
|
||||
"time"
|
||||
|
|
@ -35,13 +34,9 @@ var _ = Describe("ScanFolders", Ordered, func() {
|
|||
var fsys storagetest.FakeFS
|
||||
|
||||
BeforeAll(func() {
|
||||
tests.SkipOnWindows("SQLite file lock blocks TempDir cleanup (#TBD-path-sep-scanner)")
|
||||
ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "123", IsAdmin: true})
|
||||
// db.Db() is a process-wide singleton, so this dir may hold the open DB until
|
||||
// the suite ends, and Windows can't delete an open file
|
||||
tmpDir, err := os.MkdirTemp("", "scanner-test")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
DeferCleanup(func() { _ = os.RemoveAll(tmpDir) })
|
||||
DeferCleanup(conf.SnapshotConfig())
|
||||
tmpDir := GinkgoT().TempDir()
|
||||
conf.Update(func(c *conf.Options) { c.DbPath = filepath.Join(tmpDir, "test-selective-scan.db?_journal_mode=WAL") })
|
||||
log.Warn("Using DB at " + conf.Server().DbPath)
|
||||
db.Db().SetMaxOpenConns(1)
|
||||
|
|
|
|||
|
|
@ -59,7 +59,6 @@ var _ = Describe("Scanner", Ordered, func() {
|
|||
tmpDir, err := os.MkdirTemp("", "scanner-test")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
DeferCleanup(func() { _ = os.RemoveAll(tmpDir) })
|
||||
DeferCleanup(conf.SnapshotConfig())
|
||||
conf.Update(func(c *conf.Options) { c.DbPath = filepath.Join(tmpDir, "test-scanner.db?_journal_mode=WAL") })
|
||||
log.Warn("Using DB at " + conf.Server().DbPath)
|
||||
//conf.Server.DbPath = ":memory:"
|
||||
|
|
|
|||
|
|
@ -50,10 +50,11 @@ func walkDirTree(ctx context.Context, job *scanJob, targetFolders ...string) (<-
|
|||
continue
|
||||
}
|
||||
|
||||
// walkFolder pushes the target folder's own patterns, so only its parents are pushed here
|
||||
// Create checker and push patterns from root to this folder
|
||||
checker := newIgnoreChecker(job.fs)
|
||||
if checker.PushParents(ctx, folderPath) {
|
||||
log.Debug(ctx, "Scanner: Skipping target folder ignored by its parents", "path", folderPath)
|
||||
err = checker.PushAllParents(ctx, folderPath)
|
||||
if err != nil {
|
||||
log.Error(ctx, "Scanner: Error pushing ignore patterns for target folder", "path", folderPath, err)
|
||||
continue
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -27,26 +27,8 @@ var _ = Describe("walk_dir_tree", func() {
|
|||
ctx context.Context
|
||||
)
|
||||
|
||||
// Helper function to call walkDirTree and collect folders from the results channel
|
||||
getFolders := func(targets ...string) map[string]*folderEntry {
|
||||
results, err := walkDirTree(ctx, job, targets...)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
folders := map[string]*folderEntry{}
|
||||
g := errgroup.Group{}
|
||||
g.Go(func() error {
|
||||
for folder := range results {
|
||||
folders[folder.path] = folder
|
||||
}
|
||||
return nil
|
||||
})
|
||||
_ = g.Wait()
|
||||
return folders
|
||||
}
|
||||
|
||||
Context("full library", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Update(func(c *conf.Options) { c.Scanner.RespectNoMedia = true })
|
||||
ctx = GinkgoT().Context()
|
||||
fsys = &mockMusicFS{
|
||||
FS: fstest.MapFS{
|
||||
|
|
@ -71,9 +53,6 @@ var _ = Describe("walk_dir_tree", func() {
|
|||
"root/h/.hidden.mp3": {},
|
||||
"root/i/.git/config": {},
|
||||
"root/i/.streams/stream.mp3": {},
|
||||
"root/j/.nomedia": {},
|
||||
"root/j/f1.mp3": {},
|
||||
"root/j/sub/f2.mp3": {},
|
||||
},
|
||||
}
|
||||
job = &scanJob{
|
||||
|
|
@ -82,6 +61,23 @@ var _ = Describe("walk_dir_tree", func() {
|
|||
}
|
||||
})
|
||||
|
||||
// Helper function to call walkDirTree and collect folders from the results channel
|
||||
getFolders := func() map[string]*folderEntry {
|
||||
results, err := walkDirTree(ctx, job)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
folders := map[string]*folderEntry{}
|
||||
g := errgroup.Group{}
|
||||
g.Go(func() error {
|
||||
for folder := range results {
|
||||
folders[folder.path] = folder
|
||||
}
|
||||
return nil
|
||||
})
|
||||
_ = g.Wait()
|
||||
return folders
|
||||
}
|
||||
|
||||
DescribeTable("symlink handling",
|
||||
func(followSymlinks bool, expectedFolderCount int) {
|
||||
conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = followSymlinks })
|
||||
|
|
@ -104,8 +100,6 @@ var _ = Describe("walk_dir_tree", func() {
|
|||
Expect(folders["root/c"].audioFiles).To(BeEmpty())
|
||||
Expect(folders["root/c"].imageFiles).To(BeEmpty())
|
||||
Expect(folders).ToNot(HaveKey("root/d"))
|
||||
Expect(folders["root/j"].audioFiles).To(BeEmpty())
|
||||
Expect(folders).ToNot(HaveKey("root/j/sub"))
|
||||
|
||||
// By default (Scanner.IgnoreDotFolders == true), dot-prefixed
|
||||
// folders are skipped, dot-prefixed files are not indexed, and
|
||||
|
|
@ -128,8 +122,8 @@ var _ = Describe("walk_dir_tree", func() {
|
|||
Expect(folders["root/f"].audioFiles).ToNot(HaveKey("evil.mp3"))
|
||||
}
|
||||
},
|
||||
Entry("with symlinks enabled", true, 12),
|
||||
Entry("with symlinks disabled", false, 11),
|
||||
Entry("with symlinks enabled", true, 11),
|
||||
Entry("with symlinks disabled", false, 10),
|
||||
)
|
||||
|
||||
DescribeTable("dot-prefixed folders with IgnoreDotFolders disabled",
|
||||
|
|
@ -156,37 +150,6 @@ var _ = Describe("walk_dir_tree", func() {
|
|||
Entry("with symlinks enabled", true),
|
||||
Entry("with symlinks disabled", false),
|
||||
)
|
||||
|
||||
It("scans folders containing a .nomedia file when RespectNoMedia is disabled", func() {
|
||||
conf.Update(func(c *conf.Options) { c.Scanner.RespectNoMedia = false })
|
||||
folders := getFolders()
|
||||
|
||||
Expect(folders["root/j"].audioFiles).To(HaveKey("f1.mp3"))
|
||||
Expect(folders["root/j/sub"].audioFiles).To(HaveKey("f2.mp3"))
|
||||
})
|
||||
})
|
||||
|
||||
Context("targeted scans", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Update(func(c *conf.Options) { c.Scanner.RespectNoMedia = true })
|
||||
ctx = GinkgoT().Context()
|
||||
})
|
||||
|
||||
DescribeTable("skips a folder ignored by its parent, even if it re-includes files",
|
||||
func(targets []string) {
|
||||
job = &scanJob{fs: &mockMusicFS{FS: fstest.MapFS{
|
||||
"a/.nomedia": {},
|
||||
"a/b/.ndignore": {Data: []byte("!song.mp3\n!c")},
|
||||
"a/b/song.mp3": {},
|
||||
"a/b/c/song.mp3": {},
|
||||
}}, lib: model.Library{Path: "/music"}}
|
||||
|
||||
Expect(getFolders(targets...)).ToNot(SatisfyAny(HaveKey("a/b"), HaveKey("a/b/c")))
|
||||
},
|
||||
Entry("full scan", nil),
|
||||
Entry("targeted scan", []string{"a/b"}),
|
||||
Entry("targeted scan of a deeper folder", []string{"a/b/c"}),
|
||||
)
|
||||
})
|
||||
|
||||
Context("with target folders", func() {
|
||||
|
|
|
|||
|
|
@ -432,18 +432,6 @@ var _ = Describe("Watcher", func() {
|
|||
})
|
||||
})
|
||||
|
||||
DescribeTable("with a .nomedia file in a parent folder",
|
||||
func(respectNoMedia bool, expected bool) {
|
||||
conf.Update(func(c *conf.Options) { c.Scanner.RespectNoMedia = respectNoMedia })
|
||||
fsys := &mockMusicFS{FS: fstest.MapFS{
|
||||
"rock/.nomedia": &fstest.MapFile{},
|
||||
"rock/album/song.mp3": &fstest.MapFile{},
|
||||
}}
|
||||
Expect(w.shouldIgnoreFolderPath(ctx, fsys, "rock/album")).To(Equal(expected))
|
||||
},
|
||||
Entry("ignores the folder when RespectNoMedia is enabled", true, true),
|
||||
Entry("scans the folder when RespectNoMedia is disabled", false, false),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -14,23 +14,31 @@ import (
|
|||
"github.com/navidrome/navidrome/model/id"
|
||||
)
|
||||
|
||||
// Keeps reads out of the transaction: SQLite fails a write that follows a read at once, without waiting for the lock
|
||||
func initialSetup(ctx context.Context, ds model.DataStore) error {
|
||||
if err := ds.Library().StoreMusicFolder(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := ds.Property().Get(ctx, consts.InitialSetupFlagKey); err == nil {
|
||||
return nil
|
||||
}
|
||||
return ds.WithTxRetry(ctx, func(ctx context.Context, tx model.DataStore) error {
|
||||
func initialSetup(ds model.DataStore) {
|
||||
ctx := context.TODO()
|
||||
err := ds.WithTx(func(tx model.DataStore) error {
|
||||
if err := tx.Library().StoreMusicFolder(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
properties := tx.Property()
|
||||
_, err := properties.Get(ctx, consts.InitialSetupFlagKey)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
log.Info("Running initial setup")
|
||||
if conf.Server().DevAutoCreateAdminPassword != "" {
|
||||
if err := createInitialAdminUser(ctx, tx, conf.Server().DevAutoCreateAdminPassword); err != nil {
|
||||
if err = createInitialAdminUser(ctx, tx, conf.Server().DevAutoCreateAdminPassword); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Property().Put(ctx, consts.InitialSetupFlagKey, time.Now().String())
|
||||
|
||||
err = properties.Put(ctx, consts.InitialSetupFlagKey, time.Now().String())
|
||||
return err
|
||||
}, "initial setup")
|
||||
if err != nil {
|
||||
log.Fatal("Error running initial setup", err)
|
||||
}
|
||||
}
|
||||
|
||||
// If the Dev Admin user is not present, create it
|
||||
|
|
|
|||
|
|
@ -3,14 +3,8 @@ package server
|
|||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/db"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/persistence"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
|
|
@ -65,61 +59,3 @@ var _ = Describe("initial_setup", func() {
|
|||
})
|
||||
})
|
||||
})
|
||||
|
||||
// db.Db() is a process-wide singleton that the BeforeAll cleanup closes; keep these the only real-DB specs in this package.
|
||||
var _ = Describe("initialSetup with a real database", Ordered, func() {
|
||||
var ctx context.Context
|
||||
var ds model.DataStore
|
||||
|
||||
holdWriteLock := func(releaseAfter time.Duration) {
|
||||
conn, err := db.Db().Conn(ctx)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = conn.ExecContext(ctx, "BEGIN IMMEDIATE")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
released := make(chan struct{})
|
||||
go func() {
|
||||
defer close(released)
|
||||
time.Sleep(releaseAfter)
|
||||
_, _ = conn.ExecContext(context.Background(), "ROLLBACK")
|
||||
_ = conn.Close()
|
||||
}()
|
||||
DeferCleanup(func() { <-released })
|
||||
}
|
||||
|
||||
BeforeAll(func() {
|
||||
DeferCleanup(conf.SnapshotConfig())
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DbPath = filepath.Join(GinkgoT().TempDir(), "initial-setup.db") + "?_journal_mode=WAL&_busy_timeout=1000"
|
||||
})
|
||||
DeferCleanup(db.Init(GinkgoT().Context()))
|
||||
ds = persistence.New(db.Db())
|
||||
})
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
})
|
||||
|
||||
It("completes the first-run setup when the write lock is held briefly", func() {
|
||||
holdWriteLock(300 * time.Millisecond)
|
||||
|
||||
Expect(initialSetup(ctx, ds)).To(Succeed())
|
||||
Expect(ds.Property().Get(ctx, consts.InitialSetupFlagKey)).ToNot(BeEmpty())
|
||||
})
|
||||
|
||||
It("does not need the write lock when setup already ran and the music folder is unchanged", func() {
|
||||
holdWriteLock(1500 * time.Millisecond)
|
||||
|
||||
Expect(initialSetup(ctx, ds)).To(Succeed())
|
||||
})
|
||||
|
||||
It("stores a changed music folder when the write lock is held briefly", func() {
|
||||
newFolder := conf.Server().MusicFolder + "-moved"
|
||||
conf.Update(func(c *conf.Options) { c.MusicFolder = newFolder })
|
||||
holdWriteLock(300 * time.Millisecond)
|
||||
|
||||
Expect(initialSetup(ctx, ds)).To(Succeed())
|
||||
lib, err := ds.Library().Get(ctx, model.DefaultLibraryID)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(lib.Path).To(Equal(newFolder))
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -278,13 +278,14 @@ The stream endpoints reuse the same transcode-decision pipeline as the Subsonic
|
|||
word-level `Cues` when present), resolved through the full `core/lyrics` pipeline (embedded, `.lrc`
|
||||
sidecars, plugins per `LyricsPriority`). No lyrics returns `404`, never an empty `200`.
|
||||
|
||||
`core/lyrics` caches plugin results, misses included, for 5 minutes: Jellify fetches lyrics for every played
|
||||
track and Feishin on every song change, so lyric-less tracks are the hot path.
|
||||
Results, misses included, are cached for 5 minutes: Jellify fetches lyrics for every played track and
|
||||
Feishin on every song change, so lyric-less tracks are the hot path. Concurrent misses on the same
|
||||
track share one pipeline run. That run is detached from the request, so a cancelled request doesn't
|
||||
fail it for other waiters, and its context has a one-minute deadline.
|
||||
|
||||
Finamp opens its lyrics view only when the track has a `Lyric` `MediaStream` (`HasLyrics` is just a
|
||||
list badge). Browse lists set both from embedded lyrics only. `PlaybackInfo` runs the full pipeline
|
||||
per track with a short timeout bound, so sidecar and cached/fast plugin lyrics show up there without
|
||||
stalling playback start on a slow cold plugin lookup. Feishin also requires server version ≥ 10.9
|
||||
per track, so sidecar and plugin lyrics show up there. Feishin also requires server version ≥ 10.9
|
||||
(we advertise 12.1.0).
|
||||
|
||||
## AudioMuse-AI compatible endpoints
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package jellyfin
|
|||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
|
@ -22,6 +23,7 @@ import (
|
|||
"github.com/navidrome/navidrome/server"
|
||||
"github.com/navidrome/navidrome/server/events"
|
||||
"github.com/navidrome/navidrome/server/jellyfin/dto"
|
||||
"github.com/navidrome/navidrome/utils/cache"
|
||||
)
|
||||
|
||||
type Router struct {
|
||||
|
|
@ -37,6 +39,7 @@ type Router struct {
|
|||
sonic sonic.Engine
|
||||
lyrics lyrics.Lyrics
|
||||
broker events.Broker
|
||||
lyricsCache cache.SimpleCache[string, model.LyricList]
|
||||
similarFlight singleflight.Group
|
||||
quickConnect quickconnect.QuickConnect
|
||||
serverIDVal string
|
||||
|
|
@ -50,6 +53,10 @@ func New(ds model.DataStore, artwork artwork.Artwork, streamer stream.MediaStrea
|
|||
ds: ds, artwork: artwork, streamer: streamer, transcodeDecider: transcodeDecider,
|
||||
players: players, scrobbler: scrobbler, playlists: playlists, provider: provider,
|
||||
sonic: sonicSvc, lyrics: lyricsSvc, broker: broker, quickConnect: quickConnect,
|
||||
lyricsCache: cache.NewSimpleCache[string, model.LyricList](cache.Options{
|
||||
SizeLimit: 1000,
|
||||
DefaultTTL: 5 * time.Minute,
|
||||
}),
|
||||
}
|
||||
r.Handler = r.routes()
|
||||
return r
|
||||
|
|
|
|||
|
|
@ -10,35 +10,20 @@ import (
|
|||
"github.com/navidrome/navidrome/server/jellyfin/dto"
|
||||
)
|
||||
|
||||
// playbackInfoLyricsTimeout bounds how long getPlaybackInfo waits for lyrics before
|
||||
// returning without the Lyric MediaStream; slow plugin lookups finish warming the cache in core/lyrics.
|
||||
var playbackInfoLyricsTimeout = 100 * time.Millisecond
|
||||
const lyricsLoadTimeout = time.Minute
|
||||
|
||||
// playbackLyrics resolves lyrics for getPlaybackInfo within playbackInfoLyricsTimeout.
|
||||
func (api *Router) playbackLyrics(ctx context.Context, mf *model.MediaFile) model.LyricList {
|
||||
resCh := make(chan model.LyricList, 1)
|
||||
go func() {
|
||||
defer close(resCh)
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Error(ctx, "Panic recovered in playback lyrics lookup", "id", mf.ID, "err", r)
|
||||
}
|
||||
}()
|
||||
resCh <- api.lyricsFor(ctx, mf)
|
||||
}()
|
||||
select {
|
||||
case list := <-resCh:
|
||||
return list
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-time.After(playbackInfoLyricsTimeout):
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// lyricsFor resolves lyrics through the full source pipeline (embedded, sidecar, plugins).
|
||||
func (api *Router) lyricsFor(ctx context.Context, mf *model.MediaFile) model.LyricList {
|
||||
list, err := api.lyrics.GetLyrics(ctx, mf)
|
||||
// cachedLyrics resolves lyrics through the full source pipeline (embedded, sidecar, plugins),
|
||||
// caching results — including empty: clients poll per played track, so misses are the hot path.
|
||||
func (api *Router) cachedLyrics(ctx context.Context, mf *model.MediaFile) model.LyricList {
|
||||
// The load is shared across requests (singleflight) and cached, so don't let one
|
||||
// cancelled request abort it for everybody — detach it from the request's lifetime,
|
||||
// keeping a bound so a hung plugin can't pin the fetch (and its plugin slot) forever.
|
||||
loadCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), lyricsLoadTimeout)
|
||||
defer cancel()
|
||||
list, err := api.lyricsCache.GetWithLoader(mf.ID, func(string) (model.LyricList, time.Duration, error) {
|
||||
l, err := api.lyrics.GetLyrics(loadCtx, mf)
|
||||
return l, 0, err // 0 → cache DefaultTTL
|
||||
})
|
||||
if err != nil {
|
||||
log.Error(ctx, "Error getting lyrics", "id", mf.ID, "title", mf.Title, err)
|
||||
return nil
|
||||
|
|
@ -53,7 +38,7 @@ func (api *Router) getLyrics(w http.ResponseWriter, r *http.Request) {
|
|||
if !ok {
|
||||
return
|
||||
}
|
||||
main, found := servableLyric(api.lyricsFor(r.Context(), mf))
|
||||
main, found := servableLyric(api.cachedLyrics(r.Context(), mf))
|
||||
if !found {
|
||||
http.Error(w, "Not Found", http.StatusNotFound)
|
||||
return
|
||||
|
|
|
|||
|
|
@ -10,32 +10,24 @@ import (
|
|||
"github.com/navidrome/navidrome/model/request"
|
||||
"github.com/navidrome/navidrome/server/jellyfin/dto"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
"github.com/navidrome/navidrome/utils/cache"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
// fakeLyricsService returns canned lyrics per media-file ID.
|
||||
// fakeLyricsService returns canned lyrics per media-file ID and counts calls.
|
||||
type fakeLyricsService struct {
|
||||
lyrics map[string]model.LyricList
|
||||
err error
|
||||
panicVal any
|
||||
blockCh <-chan struct{}
|
||||
doneCh chan<- struct{}
|
||||
lyrics map[string]model.LyricList
|
||||
err error
|
||||
calls int
|
||||
hadDeadline bool
|
||||
}
|
||||
|
||||
func (f *fakeLyricsService) GetLyrics(ctx context.Context, mf *model.MediaFile) (model.LyricList, error) {
|
||||
if f.doneCh != nil {
|
||||
defer close(f.doneCh)
|
||||
}
|
||||
if f.blockCh != nil {
|
||||
select {
|
||||
case <-f.blockCh:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
if f.panicVal != nil {
|
||||
panic(f.panicVal)
|
||||
f.calls++
|
||||
_, f.hadDeadline = ctx.Deadline()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
|
|
@ -49,6 +41,10 @@ func (f *fakeLyricsService) GetLyricsByArtistTitle(context.Context, string, stri
|
|||
|
||||
func p(ms int64) *int64 { return &ms }
|
||||
|
||||
func newTestLyricsCache() cache.SimpleCache[string, model.LyricList] {
|
||||
return cache.NewSimpleCache[string, model.LyricList](cache.Options{SizeLimit: 1000})
|
||||
}
|
||||
|
||||
var _ = Describe("getLyrics", func() {
|
||||
var api *Router
|
||||
var ds *tests.MockDataStore
|
||||
|
|
@ -62,8 +58,9 @@ var _ = Describe("getLyrics", func() {
|
|||
})
|
||||
fake = &fakeLyricsService{lyrics: map[string]model.LyricList{}}
|
||||
api = &Router{
|
||||
ds: ds,
|
||||
lyrics: fake,
|
||||
ds: ds,
|
||||
lyrics: fake,
|
||||
lyricsCache: newTestLyricsCache(),
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -122,4 +119,37 @@ var _ = Describe("getLyrics", func() {
|
|||
w := doRequest("unknown")
|
||||
Expect(w.Code).To(Equal(http.StatusNotFound))
|
||||
})
|
||||
|
||||
It("caches results so a second request doesn't re-invoke the service", func() {
|
||||
fake.lyrics[testID("s1")] = model.LyricList{
|
||||
{Kind: "main", Synced: true, Line: []model.Line{{Start: p(1000), Value: "hello"}}},
|
||||
}
|
||||
Expect(doRequest(testID("s1")).Code).To(Equal(http.StatusOK))
|
||||
Expect(doRequest(testID("s1")).Code).To(Equal(http.StatusOK))
|
||||
Expect(fake.calls).To(Equal(1))
|
||||
})
|
||||
|
||||
It("caches empty results too", func() {
|
||||
Expect(doRequest(testID("s2")).Code).To(Equal(http.StatusNotFound))
|
||||
Expect(doRequest(testID("s2")).Code).To(Equal(http.StatusNotFound))
|
||||
Expect(fake.calls).To(Equal(1))
|
||||
})
|
||||
|
||||
It("completes and caches the fetch even when the request context is cancelled", func() {
|
||||
fake.lyrics[testID("s1")] = model.LyricList{
|
||||
{Kind: "main", Synced: true, Line: []model.Line{{Start: p(1000), Value: "hello"}}},
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
list := api.cachedLyrics(ctx, &model.MediaFile{ID: testID("s1")})
|
||||
Expect(list).ToNot(BeEmpty())
|
||||
Expect(doRequest(testID("s1")).Code).To(Equal(http.StatusOK))
|
||||
Expect(fake.calls).To(Equal(1))
|
||||
})
|
||||
|
||||
It("bounds the detached fetch with a timeout", func() {
|
||||
Expect(doRequest(testID("s2")).Code).To(Equal(http.StatusNotFound))
|
||||
Expect(fake.hadDeadline).To(BeTrue())
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package jellyfin
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
|
|
@ -204,7 +205,7 @@ func (api *Router) withPlayer(next http.Handler) http.Handler {
|
|||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
ip := middleware.GetClientIP(r.Context())
|
||||
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
|
||||
player, trc, err := api.players.Register(ctx, a.DeviceId, a.Client, a.Device, ip)
|
||||
if err != nil {
|
||||
// Fail open, like Subsonic's getPlayer: proceed without a player; reporting handlers
|
||||
|
|
|
|||
|
|
@ -50,10 +50,10 @@ func (api *Router) getPlaybackInfo(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
src := dto.MediaSourceFromMediaFile(*mf)
|
||||
// The mapper only sees embedded lyrics; also check external sources (sidecars, plugins)
|
||||
// within playbackInfoLyricsTimeout so Finamp's Lyric-stream gate reflects them when ready.
|
||||
// The mapper only sees embedded lyrics; per-track we can afford the full pipeline
|
||||
// (sidecars, plugins) so Finamp's Lyric-stream gate reflects every source.
|
||||
if !slices.ContainsFunc(src.MediaStreams, func(s dto.MediaStream) bool { return s.Type == "Lyric" }) {
|
||||
if _, found := servableLyric(api.playbackLyrics(r.Context(), mf)); found {
|
||||
if _, found := servableLyric(api.cachedLyrics(r.Context(), mf)); found {
|
||||
src.MediaStreams = append(src.MediaStreams, dto.MediaStream{
|
||||
Type: "Lyric", Index: len(src.MediaStreams), IsExternal: true,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ import (
|
|||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/core/stream"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
|
|
@ -36,7 +35,8 @@ var _ = Describe("Stream", func() {
|
|||
decider = &fakeTranscodeDecider{}
|
||||
api = &Router{
|
||||
ds: ds, streamer: streamer, transcodeDecider: decider,
|
||||
lyrics: &fakeLyricsService{lyrics: map[string]model.LyricList{}},
|
||||
lyrics: &fakeLyricsService{lyrics: map[string]model.LyricList{}},
|
||||
lyricsCache: newTestLyricsCache(),
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -162,55 +162,6 @@ var _ = Describe("Stream", func() {
|
|||
Expect(res.MediaSources[0].Id).To(Equal(dto.EncodeID(testID("s-err"))))
|
||||
Expect(lyricStreams(res)).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("does not block playback info when lyrics lookup is slow", func() {
|
||||
origTimeout := playbackInfoLyricsTimeout
|
||||
playbackInfoLyricsTimeout = 20 * time.Millisecond
|
||||
DeferCleanup(func() { playbackInfoLyricsTimeout = origTimeout })
|
||||
|
||||
blockCh := make(chan struct{})
|
||||
doneCh := make(chan struct{})
|
||||
DeferCleanup(func() {
|
||||
close(blockCh)
|
||||
Eventually(doneCh).Should(BeClosed())
|
||||
})
|
||||
|
||||
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
|
||||
{ID: testID("s1"), Title: "Slow Song", Suffix: "mp3", Duration: 100, Size: 1000, LibraryID: 1},
|
||||
})
|
||||
api.lyrics = &fakeLyricsService{
|
||||
lyrics: map[string]model.LyricList{
|
||||
testID("s1"): {{Kind: "main", Synced: true, Line: []model.Line{{Value: "delayed"}}}},
|
||||
},
|
||||
blockCh: blockCh,
|
||||
doneCh: doneCh,
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
res := playbackInfo()
|
||||
duration := time.Since(start)
|
||||
Expect(duration).To(BeNumerically("<", 150*time.Millisecond))
|
||||
Expect(res.MediaSources).To(HaveLen(1))
|
||||
Expect(lyricStreams(res)).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("recovers panics in detached lyrics lookup and returns 200 without Lyric stream", func() {
|
||||
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
|
||||
{ID: testID("s-panic"), Title: "Panic Song", Suffix: "mp3", Duration: 100, Size: 1000, LibraryID: 1},
|
||||
})
|
||||
api.lyrics = &fakeLyricsService{panicVal: "lyrics plugin crash"}
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
r := httptest.NewRequest("POST", "/Items/"+dto.EncodeID(testID("s-panic"))+"/PlaybackInfo", nil).WithContext(ctxUser())
|
||||
r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s-panic")))
|
||||
api.getPlaybackInfo(w, r)
|
||||
|
||||
Expect(w.Code).To(Equal(http.StatusOK))
|
||||
var res dto.PlaybackInfoResponse
|
||||
Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed())
|
||||
Expect(res.MediaSources).To(HaveLen(1))
|
||||
Expect(lyricStreams(res)).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
|
||||
Describe("streamAudio", func() {
|
||||
|
|
|
|||
133
server/nativeapi/artwork_explain.go
Normal file
133
server/nativeapi/artwork_explain.go
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
package nativeapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/navidrome/navidrome/core/artwork"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
)
|
||||
|
||||
type traceStepDTO struct {
|
||||
Candidate string `json:"candidate"`
|
||||
Outcome string `json:"outcome"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
type storedDTO struct {
|
||||
Source string `json:"source"`
|
||||
SourcePath string `json:"sourcePath,omitempty"`
|
||||
AttemptedAt string `json:"attemptedAt,omitempty"`
|
||||
}
|
||||
|
||||
type queuedDTO struct {
|
||||
PriorityName string `json:"priorityName"`
|
||||
Attempts int `json:"attempts"`
|
||||
RetryAt string `json:"retryAt,omitempty"`
|
||||
}
|
||||
|
||||
type configDTO struct {
|
||||
Setting string `json:"setting"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
type explainDTO struct {
|
||||
Name string `json:"name"`
|
||||
Result string `json:"result"`
|
||||
Steps []traceStepDTO `json:"steps"`
|
||||
Stored *storedDTO `json:"stored,omitempty"`
|
||||
Queued *queuedDTO `json:"queued,omitempty"`
|
||||
LastAttemptFailed []traceStepDTO `json:"lastAttemptFailed,omitempty"`
|
||||
GaveUpAfter []traceStepDTO `json:"gaveUpAfter,omitempty"`
|
||||
Config *configDTO `json:"config,omitempty"`
|
||||
Agents string `json:"agents,omitempty"`
|
||||
AgentsIncomplete bool `json:"agentsIncomplete,omitempty"`
|
||||
}
|
||||
|
||||
func (api *Router) addArtworkExplainRoute(r chi.Router) {
|
||||
r.Get("/artwork/explain", api.explainArtwork())
|
||||
}
|
||||
|
||||
func (api *Router) explainArtwork() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
kind, ok := model.ParseKind(r.URL.Query().Get("kind"))
|
||||
if !ok || !slices.Contains(artwork.ExplainKinds, kind) {
|
||||
http.Error(w, "invalid artwork kind", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
id := r.URL.Query().Get("id")
|
||||
|
||||
// No Walk: the endpoint reports history only, so it can never reach the network.
|
||||
rep, err := artwork.Explain(ctx, api.ds, api.agents, kind, id, artwork.ExplainOptions{})
|
||||
if err != nil {
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
log.Error(ctx, "Error explaining artwork", "kind", kind, "id", id, err)
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(toExplainDTO(rep)); err != nil {
|
||||
log.Error(ctx, "Error encoding artwork explain response", "kind", kind, "id", id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func rfc3339(t time.Time) string {
|
||||
if t.IsZero() {
|
||||
return ""
|
||||
}
|
||||
return t.Format(time.RFC3339)
|
||||
}
|
||||
|
||||
func toStepDTOs(steps []artwork.TraceStep) []traceStepDTO {
|
||||
// Never nil: the UI maps over this unconditionally.
|
||||
out := make([]traceStepDTO, 0, len(steps))
|
||||
for _, s := range steps {
|
||||
out = append(out, traceStepDTO{Candidate: s.Candidate, Outcome: string(s.Outcome), Detail: s.Detail})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func toExplainDTO(rep artwork.ExplainReport) explainDTO {
|
||||
dto := explainDTO{
|
||||
Name: rep.Name,
|
||||
Result: rep.Result(),
|
||||
Steps: toStepDTOs(rep.Steps),
|
||||
Agents: rep.Agents,
|
||||
AgentsIncomplete: rep.AgentsIncomplete,
|
||||
}
|
||||
if rep.Stored != nil {
|
||||
dto.Stored = &storedDTO{
|
||||
Source: rep.Stored.Source,
|
||||
SourcePath: rep.Stored.SourcePath,
|
||||
AttemptedAt: rfc3339(rep.Stored.AttemptedAt),
|
||||
}
|
||||
}
|
||||
if rep.Queued != nil {
|
||||
dto.Queued = &queuedDTO{
|
||||
PriorityName: artwork.PriorityName(rep.Queued.Priority),
|
||||
Attempts: rep.Queued.Attempts,
|
||||
RetryAt: rfc3339(rep.Queued.RetryAt),
|
||||
}
|
||||
}
|
||||
if steps := rep.LastAttemptFailed(); len(steps) > 0 {
|
||||
dto.LastAttemptFailed = toStepDTOs(steps)
|
||||
}
|
||||
if steps := rep.GaveUpAfter(); len(steps) > 0 {
|
||||
dto.GaveUpAfter = toStepDTOs(steps)
|
||||
}
|
||||
if setting, value := artwork.ConfigFor(rep.Kind); setting != "" {
|
||||
dto.Config = &configDTO{Setting: setting, Value: value}
|
||||
}
|
||||
return dto
|
||||
}
|
||||
155
server/nativeapi/artwork_explain_test.go
Normal file
155
server/nativeapi/artwork_explain_test.go
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
package nativeapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/core/auth"
|
||||
"github.com/navidrome/navidrome/core/playlists"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/server"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("GET /artwork/explain", func() {
|
||||
var router http.Handler
|
||||
var ds *tests.MockDataStore
|
||||
var artRepo *tests.MockArtworkRepo
|
||||
var queueRepo *tests.MockArtworkQueueRepo
|
||||
var adminToken, userToken string
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.EnableSharing = false
|
||||
c.ArtistArtPriority = "external"
|
||||
})
|
||||
artRepo = tests.CreateMockArtworkRepo()
|
||||
queueRepo = tests.CreateMockArtworkQueueRepo()
|
||||
ds = &tests.MockDataStore{MockedArtwork: artRepo, MockedArtworkQueue: queueRepo}
|
||||
Expect(ds.Artist().Put(ctx, &model.Artist{ID: "ar-1", Name: "Radiohead"})).To(Succeed())
|
||||
auth.Init(ds)
|
||||
|
||||
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil, nil)
|
||||
router = server.JWTVerifier(nativeRouter)
|
||||
|
||||
adminUser := model.User{ID: "admin-1", UserName: "admin", IsAdmin: true, NewPassword: "adminpass"}
|
||||
regularUser := model.User{ID: "user-1", UserName: "regular", IsAdmin: false, NewPassword: "userpass"}
|
||||
Expect(ds.User().Put(ctx, &adminUser)).To(Succeed())
|
||||
Expect(ds.User().Put(ctx, ®ularUser)).To(Succeed())
|
||||
|
||||
var err error
|
||||
adminToken, err = auth.CreateToken(&adminUser)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
userToken, err = auth.CreateToken(®ularUser)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("returns 403 for a non-admin", func() {
|
||||
req := createAuthenticatedRequest("GET", "/artwork/explain?kind=ar&id=ar-1", nil, userToken)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
Expect(w.Code).To(Equal(http.StatusForbidden))
|
||||
})
|
||||
|
||||
It("returns 400 for an unknown kind", func() {
|
||||
req := createAuthenticatedRequest("GET", "/artwork/explain?kind=zz&id=ar-1", nil, adminToken)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
Expect(w.Code).To(Equal(http.StatusBadRequest))
|
||||
})
|
||||
|
||||
It("returns 404 for an unknown id", func() {
|
||||
req := createAuthenticatedRequest("GET", "/artwork/explain?kind=ar&id=missing", nil, adminToken)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
Expect(w.Code).To(Equal(http.StatusNotFound))
|
||||
})
|
||||
|
||||
It("returns the report for an admin", func() {
|
||||
// Storage shape from core/artwork/trace.go's storedStep: single-letter keys, "d" optional.
|
||||
trace := `[{"c":"external:deezer","o":"hit","d":"https://cdn/x.jpg"}]`
|
||||
gaveUpTrace := `[{"c":"external:deezer","o":"error","d":"connection reset"}]`
|
||||
attemptedAt := time.Date(2026, 9, 1, 10, 0, 0, 0, time.UTC)
|
||||
Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{
|
||||
ItemKind: model.KindArtistArtwork.Prefix(), ItemID: "ar-1", ImageType: model.ImageTypePrimary,
|
||||
Hash: "abc", Source: "external:deezer", SourcePath: "/music/Radiohead/folder.jpg", Trace: trace,
|
||||
LastFailure: gaveUpTrace, AttemptedAt: attemptedAt,
|
||||
})).To(Succeed())
|
||||
|
||||
req := createAuthenticatedRequest("GET", "/artwork/explain?kind=ar&id=ar-1", nil, adminToken)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
Expect(w.Code).To(Equal(http.StatusOK))
|
||||
|
||||
var got map[string]any
|
||||
Expect(json.Unmarshal(w.Body.Bytes(), &got)).To(Succeed())
|
||||
Expect(got["name"]).To(Equal("Radiohead"))
|
||||
Expect(got["result"]).To(Equal("resolved from external:deezer"))
|
||||
Expect(got["config"]).To(HaveKeyWithValue("setting", "ArtistArtPriority"))
|
||||
|
||||
Expect(got["stored"]).To(Equal(map[string]any{
|
||||
"source": "external:deezer",
|
||||
"sourcePath": "/music/Radiohead/folder.jpg",
|
||||
"attemptedAt": attemptedAt.Format(time.RFC3339),
|
||||
}))
|
||||
Expect(got["steps"]).To(Equal([]any{
|
||||
map[string]any{"candidate": "external:deezer", "outcome": "hit", "detail": "https://cdn/x.jpg"},
|
||||
}))
|
||||
Expect(got["gaveUpAfter"]).To(Equal([]any{
|
||||
map[string]any{"candidate": "external:deezer", "outcome": "error", "detail": "connection reset"},
|
||||
}))
|
||||
})
|
||||
|
||||
It("returns the queue state and the last-attempt trace", func() {
|
||||
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
|
||||
ItemKind: model.KindArtistArtwork.Prefix(), ItemID: "ar-1", ImageType: model.ImageTypePrimary,
|
||||
Priority: model.ArtworkPriorityScan,
|
||||
})).To(Succeed())
|
||||
seen, err := queueRepo.Get(ctx, model.KindArtistArtwork, "ar-1", model.ImageTypePrimary)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
retryAt := time.Date(2026, 9, 2, 8, 0, 0, 0, time.UTC)
|
||||
failTrace := `[{"c":"external:deezer","o":"error","d":"timeout"}]`
|
||||
Expect(queueRepo.MarkFailedIfUnchanged(ctx, model.KindArtistArtwork.Prefix(), "ar-1", model.ImageTypePrimary,
|
||||
seen.RetryAt, retryAt, failTrace)).To(Succeed())
|
||||
|
||||
req := createAuthenticatedRequest("GET", "/artwork/explain?kind=ar&id=ar-1", nil, adminToken)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
Expect(w.Code).To(Equal(http.StatusOK))
|
||||
|
||||
var got map[string]any
|
||||
Expect(json.Unmarshal(w.Body.Bytes(), &got)).To(Succeed())
|
||||
Expect(got["queued"]).To(Equal(map[string]any{
|
||||
"priorityName": "scan",
|
||||
"attempts": float64(1),
|
||||
"retryAt": retryAt.Format(time.RFC3339),
|
||||
}))
|
||||
Expect(got["lastAttemptFailed"]).To(Equal([]any{
|
||||
map[string]any{"candidate": "external:deezer", "outcome": "error", "detail": "timeout"},
|
||||
}))
|
||||
})
|
||||
|
||||
It("omits empty sections", func() {
|
||||
req := createAuthenticatedRequest("GET", "/artwork/explain?kind=ar&id=ar-1", nil, adminToken)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
Expect(w.Code).To(Equal(http.StatusOK))
|
||||
|
||||
var got map[string]any
|
||||
Expect(json.Unmarshal(w.Body.Bytes(), &got)).To(Succeed())
|
||||
Expect(got).ToNot(HaveKey("stored"))
|
||||
Expect(got).ToNot(HaveKey("queued"))
|
||||
Expect(got).ToNot(HaveKey("lastAttemptFailed"))
|
||||
Expect(got).ToNot(HaveKey("gaveUpAfter"))
|
||||
Expect(got).ToNot(HaveKey("chainOrigin"))
|
||||
})
|
||||
})
|
||||
|
|
@ -32,7 +32,7 @@ var _ = Describe("Config API", func() {
|
|||
}) // Enable config endpoint for tests
|
||||
ds = &tests.MockDataStore{}
|
||||
auth.Init(ds)
|
||||
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil)
|
||||
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil, nil)
|
||||
router = server.JWTVerifier(nativeRouter)
|
||||
|
||||
// Create test users
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ var _ = Describe("Library API", func() {
|
|||
conf.Update(func(c *conf.Options) { c.EnableSharing = false })
|
||||
ds = &tests.MockDataStore{}
|
||||
auth.Init(ds)
|
||||
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil)
|
||||
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil, nil)
|
||||
router = server.JWTVerifier(nativeRouter)
|
||||
|
||||
// Create test users
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ var _ = Describe("Metadata API", func() {
|
|||
}
|
||||
auth.Init(ds)
|
||||
provider = &fakeProvider{}
|
||||
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, provider, nil)
|
||||
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, provider, nil, nil)
|
||||
router = server.JWTVerifier(nativeRouter)
|
||||
|
||||
adminUser := model.User{ID: "admin-1", UserName: "admin", IsAdmin: true, NewPassword: "adminpass"}
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ var _ = Describe("Missing Files Endpoint", func() {
|
|||
token, err = auth.CreateToken(&user)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
router = server.JWTVerifier(New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil))
|
||||
router = server.JWTVerifier(New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil, nil))
|
||||
})
|
||||
|
||||
DescribeTable("GET /missing/{id}",
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import (
|
|||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/core"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/core/artwork"
|
||||
"github.com/navidrome/navidrome/core/external"
|
||||
"github.com/navidrome/navidrome/core/metrics"
|
||||
|
|
@ -48,10 +49,11 @@ type Router struct {
|
|||
imgUpload artwork.Uploader
|
||||
provider external.Provider
|
||||
quickConnect quickconnect.QuickConnect
|
||||
agents *agents.Agents
|
||||
}
|
||||
|
||||
func New(ds model.DataStore, share core.Share, playlists playlistsvc.Playlists, insights metrics.Insights, libraryService core.Library, userService core.User, maintenance core.Maintenance, pluginManager PluginManager, imgUpload artwork.Uploader, provider external.Provider, quickConnect quickconnect.QuickConnect) *Router {
|
||||
r := &Router{ds: ds, share: share, playlists: playlists, insights: insights, libs: libraryService, users: userService, maintenance: maintenance, pluginManager: pluginManager, imgUpload: imgUpload, provider: provider, quickConnect: quickConnect}
|
||||
func New(ds model.DataStore, share core.Share, playlists playlistsvc.Playlists, insights metrics.Insights, libraryService core.Library, userService core.User, maintenance core.Maintenance, pluginManager PluginManager, imgUpload artwork.Uploader, provider external.Provider, quickConnect quickconnect.QuickConnect, ag *agents.Agents) *Router {
|
||||
r := &Router{ds: ds, share: share, playlists: playlists, insights: insights, libs: libraryService, users: userService, maintenance: maintenance, pluginManager: pluginManager, imgUpload: imgUpload, provider: provider, quickConnect: quickConnect, agents: ag}
|
||||
r.Handler = r.routes()
|
||||
return r
|
||||
}
|
||||
|
|
@ -96,6 +98,7 @@ func (api *Router) routes() http.Handler {
|
|||
api.addUserLibraryRoute(r)
|
||||
api.addPluginRoute(r)
|
||||
api.addMetadataRoute(r)
|
||||
api.addArtworkExplainRoute(r)
|
||||
rx(r, "/library", api.libs.Repository(), true)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -99,7 +99,7 @@ var _ = Describe("Song Endpoints", func() {
|
|||
mfRepo.SetData(testSongs)
|
||||
|
||||
// Create the native API router and wrap it with the JWTVerifier middleware
|
||||
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil)
|
||||
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil, nil)
|
||||
router = server.JWTVerifier(nativeRouter)
|
||||
w = httptest.NewRecorder()
|
||||
})
|
||||
|
|
|
|||
|
|
@ -97,7 +97,7 @@ var _ = Describe("Playlist Tracks Endpoint", func() {
|
|||
err := userRepo.Put(GinkgoT().Context(), &testUser)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
nativeRouter := New(ds, nil, plsSvc, nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil)
|
||||
nativeRouter := New(ds, nil, plsSvc, nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil, nil)
|
||||
router = server.JWTVerifier(nativeRouter)
|
||||
w = httptest.NewRecorder()
|
||||
})
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ var _ = Describe("Plugin API", func() {
|
|||
ds = &tests.MockDataStore{}
|
||||
mockManager = &tests.MockPluginManager{}
|
||||
auth.Init(ds)
|
||||
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, mockManager, nil, nil, nil)
|
||||
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, mockManager, nil, nil, nil, nil)
|
||||
router = server.JWTVerifier(nativeRouter)
|
||||
|
||||
// Create test users
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ var _ = Describe("PUT /user/{id}: token refresh on self password change", func()
|
|||
auth.Init(ds)
|
||||
|
||||
userService := core.NewUser(ds, noopPluginUnloader{})
|
||||
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), userService, nil, nil, nil, nil, nil)
|
||||
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), userService, nil, nil, nil, nil, nil, nil)
|
||||
router = server.JWTVerifier(nativeRouter)
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -37,9 +37,7 @@ type Server struct {
|
|||
|
||||
func New(ds model.DataStore, broker events.Broker, insights metrics.Insights) *Server {
|
||||
s := &Server{ds: ds, broker: broker, insights: insights}
|
||||
if err := initialSetup(context.TODO(), ds); err != nil {
|
||||
log.Fatal("Error running initial setup", err)
|
||||
}
|
||||
initialSetup(ds)
|
||||
auth.Init(s.ds)
|
||||
s.initRoutes()
|
||||
s.mountAuthenticationRoutes()
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import (
|
|||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
|
@ -293,7 +294,7 @@ func getPlayer(players core.Players) func(next http.Handler) http.Handler {
|
|||
ctx := r.Context()
|
||||
userName, _ := request.UsernameFrom(ctx)
|
||||
client, _ := request.ClientFrom(ctx)
|
||||
ip := middleware.GetClientIP(r.Context())
|
||||
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
|
||||
userAgent := canonicalUserAgent(r)
|
||||
|
||||
var player *model.Player
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ import (
|
|||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/core"
|
||||
|
|
@ -665,40 +664,6 @@ var _ = Describe("Middlewares", func() {
|
|||
Expect(cookieStr).To(ContainSubstring(playerIDCookieName("someone")))
|
||||
})
|
||||
|
||||
It("registers the player with the client IP from RemoteAddr", func() {
|
||||
r.RemoteAddr = "192.0.2.10:54321"
|
||||
gp := middleware.ClientIPFromRemoteAddr(getPlayer(mockedPlayers)(next))
|
||||
gp.ServeHTTP(w, r)
|
||||
|
||||
Expect(mockedPlayers.ip).To(Equal("192.0.2.10"))
|
||||
})
|
||||
|
||||
It("keeps the client IP when RemoteAddr has no port, as set behind a trusted proxy", func() {
|
||||
r.RemoteAddr = "192.0.2.10"
|
||||
gp := middleware.ClientIPFromRemoteAddr(getPlayer(mockedPlayers)(next))
|
||||
gp.ServeHTTP(w, r)
|
||||
|
||||
Expect(mockedPlayers.ip).To(Equal("192.0.2.10"))
|
||||
})
|
||||
|
||||
It("takes the client IP resolved into the context, not the peer address", func() {
|
||||
// realIPMiddleware resolves forwarding headers from a trusted proxy the same way
|
||||
r.RemoteAddr = "10.0.0.1:1234"
|
||||
r.Header.Set("X-Real-IP", "203.0.113.6")
|
||||
gp := middleware.ClientIPFromHeader("X-Real-IP")(getPlayer(mockedPlayers)(next))
|
||||
gp.ServeHTTP(w, r)
|
||||
|
||||
Expect(mockedPlayers.ip).To(Equal("203.0.113.6"))
|
||||
})
|
||||
|
||||
It("does not take a unix socket peer for an IP", func() {
|
||||
r.RemoteAddr = "@"
|
||||
gp := middleware.ClientIPFromRemoteAddr(getPlayer(mockedPlayers)(next))
|
||||
gp.ServeHTTP(w, r)
|
||||
|
||||
Expect(mockedPlayers.ip).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("does not add the cookie if there was an error", func() {
|
||||
ctx := request.WithClient(r.Context(), "error")
|
||||
r = r.WithContext(ctx)
|
||||
|
|
@ -907,12 +872,10 @@ type mockPlayers struct {
|
|||
core.Players
|
||||
transcoding *model.Transcoding
|
||||
touched bool
|
||||
ip string
|
||||
}
|
||||
|
||||
func (mp *mockPlayers) Touch(_ context.Context, plr model.Player, _, _, ip string) (*model.Player, *model.Transcoding, error) {
|
||||
func (mp *mockPlayers) Touch(_ context.Context, plr model.Player, _, _, _ string) (*model.Player, *model.Transcoding, error) {
|
||||
mp.touched = true
|
||||
mp.ip = ip
|
||||
return &plr, mp.transcoding, nil
|
||||
}
|
||||
|
||||
|
|
@ -921,7 +884,6 @@ func (mp *mockPlayers) Get(ctx context.Context, playerId string) (*model.Player,
|
|||
}
|
||||
|
||||
func (mp *mockPlayers) Register(ctx context.Context, id, client, typ, ip string) (*model.Player, *model.Transcoding, error) {
|
||||
mp.ip = ip
|
||||
if client == "error" {
|
||||
return nil, nil, errors.New(client)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,6 +40,18 @@ func (m *MockArtworkQueueRepo) Get(_ context.Context, kind model.Kind, id, image
|
|||
return &it, nil
|
||||
}
|
||||
|
||||
// SetTrace stores a queue row's trace directly, bypassing the retry-token check
|
||||
// MarkFailedIfUnchanged enforces; tests use it to seed a failure trace outright.
|
||||
func (m *MockArtworkQueueRepo) SetTrace(kind model.Kind, id, imageType, trace string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
k := iaKey(kind.Prefix(), id, imageType)
|
||||
if it, ok := m.Data[k]; ok {
|
||||
it.Trace = trace
|
||||
m.Data[k] = it
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MockArtworkQueueRepo) Enqueue(_ context.Context, items ...model.ArtworkQueueItem) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
|
|
|||
|
|
@ -60,10 +60,11 @@ export const closeDuplicateSongDialog = () => ({
|
|||
type: DUPLICATE_SONG_WARNING_CLOSE,
|
||||
})
|
||||
|
||||
export const openExtendedInfoDialog = (record) => {
|
||||
export const openExtendedInfoDialog = (record, resource) => {
|
||||
return {
|
||||
type: EXTENDED_INFO_OPEN,
|
||||
record,
|
||||
resource,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import { makeStyles } from '@material-ui/core/styles'
|
|||
import {
|
||||
DateField,
|
||||
ArtistLinkField,
|
||||
ArtworkInfo,
|
||||
MultiLineTextField,
|
||||
ParticipantsInfo,
|
||||
RangeField,
|
||||
|
|
@ -139,6 +140,7 @@ const AlbumInfo = (props) => {
|
|||
)
|
||||
})}
|
||||
<ParticipantsInfo record={record} classes={classes} />
|
||||
<ArtworkInfo resource="album" id={record.id} />
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
|
|
|
|||
82
ui/src/artist/ArtistInfo.jsx
Normal file
82
ui/src/artist/ArtistInfo.jsx
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import Table from '@material-ui/core/Table'
|
||||
import TableBody from '@material-ui/core/TableBody'
|
||||
import { humanize, underscore } from 'inflection'
|
||||
import TableCell from '@material-ui/core/TableCell'
|
||||
import TableContainer from '@material-ui/core/TableContainer'
|
||||
import TableRow from '@material-ui/core/TableRow'
|
||||
import {
|
||||
DateField,
|
||||
TextField,
|
||||
useRecordContext,
|
||||
useTranslate,
|
||||
} from 'react-admin'
|
||||
import { makeStyles } from '@material-ui/core/styles'
|
||||
import { ArtworkInfo, SizeField } from '../common'
|
||||
|
||||
const useStyles = makeStyles({
|
||||
tableCell: {
|
||||
width: '17.5%',
|
||||
},
|
||||
value: {
|
||||
whiteSpace: 'pre-line',
|
||||
},
|
||||
})
|
||||
|
||||
const ArtistInfo = (props) => {
|
||||
const classes = useStyles()
|
||||
const translate = useTranslate()
|
||||
const record = useRecordContext(props)
|
||||
const data = {
|
||||
name: <TextField source={'name'} />,
|
||||
sortArtistName: <TextField source={'sortArtistName'} />,
|
||||
mbzArtistId: <TextField source={'mbzArtistId'} />,
|
||||
albumCount: <TextField source={'albumCount'} />,
|
||||
songCount: <TextField source={'songCount'} />,
|
||||
size: <SizeField source={'size'} />,
|
||||
playCount: <TextField source={'playCount'} />,
|
||||
externalInfoUpdatedAt: (
|
||||
<DateField source={'externalInfoUpdatedAt'} showTime />
|
||||
),
|
||||
updatedAt: <DateField source={'updatedAt'} showTime />,
|
||||
}
|
||||
|
||||
const optionalFields = [
|
||||
'sortArtistName',
|
||||
'mbzArtistId',
|
||||
'externalInfoUpdatedAt',
|
||||
]
|
||||
optionalFields.forEach((field) => {
|
||||
!record[field] && delete data[field]
|
||||
})
|
||||
|
||||
return (
|
||||
<TableContainer>
|
||||
<Table aria-label="artist details" size="small">
|
||||
<TableBody>
|
||||
{Object.keys(data).map((key) => {
|
||||
return (
|
||||
<TableRow key={`${record.id}-${key}`}>
|
||||
<TableCell
|
||||
component="th"
|
||||
scope="row"
|
||||
className={classes.tableCell}
|
||||
>
|
||||
{translate(`resources.artist.fields.${key}`, {
|
||||
_: humanize(underscore(key)),
|
||||
})}
|
||||
:
|
||||
</TableCell>
|
||||
<TableCell align="left" className={classes.value}>
|
||||
{data[key]}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
<ArtworkInfo resource="artist" id={record.id} />
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
)
|
||||
}
|
||||
|
||||
export default ArtistInfo
|
||||
39
ui/src/artist/ArtistInfo.test.jsx
Normal file
39
ui/src/artist/ArtistInfo.test.jsx
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import React from 'react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { RecordContextProvider } from 'react-admin'
|
||||
import ArtistInfo from './ArtistInfo'
|
||||
|
||||
vi.mock('../common', async (importOriginal) => ({
|
||||
...(await importOriginal()),
|
||||
ArtworkInfo: () => (
|
||||
<tr>
|
||||
<td>artwork-section</td>
|
||||
</tr>
|
||||
),
|
||||
}))
|
||||
|
||||
const renderWith = (record) =>
|
||||
render(
|
||||
<RecordContextProvider value={record}>
|
||||
<ArtistInfo />
|
||||
</RecordContextProvider>,
|
||||
)
|
||||
|
||||
describe('<ArtistInfo />', () => {
|
||||
it('renders the artist fields', () => {
|
||||
renderWith({ id: 'ar-1', name: 'Radiohead', albumCount: 9, songCount: 120 })
|
||||
expect(screen.getByText('Radiohead')).toBeInTheDocument()
|
||||
expect(screen.getByText('9')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('drops optional fields that are empty', () => {
|
||||
renderWith({ id: 'ar-1', name: 'Radiohead' })
|
||||
expect(screen.queryByText(/MusicBrainz/i)).toBeNull()
|
||||
})
|
||||
|
||||
it('renders the artwork section', () => {
|
||||
renderWith({ id: 'ar-1', name: 'Radiohead' })
|
||||
expect(screen.getByText('artwork-section')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
|
@ -35,6 +35,8 @@ import ArtistSimpleList from './ArtistSimpleList'
|
|||
import { DraggableTypes } from '../consts'
|
||||
import en from '../i18n/en.json'
|
||||
import { formatBytes } from '../utils/index.js'
|
||||
import ArtistInfo from './ArtistInfo'
|
||||
import ExpandInfoDialog from '../dialogs/ExpandInfoDialog'
|
||||
|
||||
const useStyles = makeStyles({
|
||||
contextHeader: {
|
||||
|
|
@ -219,6 +221,7 @@ const ArtistList = (props) => {
|
|||
>
|
||||
<ArtistListView {...props} />
|
||||
</List>
|
||||
<ExpandInfoDialog content={<ArtistInfo />} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import { LoveButton, RatingField, ImageUploadOverlay } from '../common'
|
|||
import Lightbox from 'react-image-lightbox'
|
||||
import ExpandInfoDialog from '../dialogs/ExpandInfoDialog'
|
||||
import AlbumInfo from '../album/AlbumInfo'
|
||||
import ArtistInfo from './ArtistInfo'
|
||||
import subsonic from '../subsonic'
|
||||
import { SafeHTML } from '../common/SafeHTML'
|
||||
import { Artwork } from '../common/Artwork'
|
||||
|
|
@ -160,7 +161,8 @@ const DesktopArtistDetails = ({ artistInfo, record, biography }) => {
|
|||
/>
|
||||
)}
|
||||
</Card>
|
||||
<ExpandInfoDialog content={<AlbumInfo />} />
|
||||
<ExpandInfoDialog resource="album" content={<AlbumInfo />} />
|
||||
<ExpandInfoDialog resource="artist" content={<ArtistInfo />} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
183
ui/src/common/ArtworkInfo.jsx
Normal file
183
ui/src/common/ArtworkInfo.jsx
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
import React, { useEffect, useState } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
import { Chip, Link, TableCell, TableRow } from '@material-ui/core'
|
||||
import { makeStyles } from '@material-ui/core/styles'
|
||||
import clsx from 'clsx'
|
||||
import { useDataProvider, usePermissions, useTranslate } from 'react-admin'
|
||||
import { DateField } from './DateField'
|
||||
|
||||
const useStyles = makeStyles((theme) => ({
|
||||
chip: { color: theme.palette.common.white, height: 20 },
|
||||
hit: { backgroundColor: theme.palette.success.main },
|
||||
error: { backgroundColor: theme.palette.error.main },
|
||||
neutral: { backgroundColor: theme.palette.grey[500] },
|
||||
toggle: { cursor: 'pointer' },
|
||||
}))
|
||||
|
||||
const OUTCOME_CLASS = { hit: 'hit', error: 'error', unreadable: 'error' }
|
||||
|
||||
const OutcomeChip = ({ outcome }) => {
|
||||
const classes = useStyles()
|
||||
return (
|
||||
<Chip
|
||||
size="small"
|
||||
label={outcome}
|
||||
className={clsx(
|
||||
classes.chip,
|
||||
classes[OUTCOME_CLASS[outcome] || 'neutral'],
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
OutcomeChip.propTypes = {
|
||||
outcome: PropTypes.string.isRequired,
|
||||
}
|
||||
|
||||
const StepTable = ({ title, steps }) => {
|
||||
if (!steps?.length) return null
|
||||
return (
|
||||
<>
|
||||
<TableRow>
|
||||
<TableCell colSpan={2}>
|
||||
<strong>{title}</strong>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{steps.map((s, i) => (
|
||||
<TableRow key={`${s.candidate}-${i}`}>
|
||||
<TableCell>{s.candidate}</TableCell>
|
||||
<TableCell>
|
||||
<OutcomeChip outcome={s.outcome} /> {s.detail}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
StepTable.propTypes = {
|
||||
title: PropTypes.string.isRequired,
|
||||
steps: PropTypes.array,
|
||||
}
|
||||
|
||||
const Row = ({ label, children }) => (
|
||||
<TableRow>
|
||||
<TableCell component="th" scope="row">
|
||||
{label}:
|
||||
</TableCell>
|
||||
<TableCell align="left">{children}</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
|
||||
Row.propTypes = {
|
||||
label: PropTypes.node.isRequired,
|
||||
children: PropTypes.node,
|
||||
}
|
||||
|
||||
export const ArtworkInfo = ({ resource, id }) => {
|
||||
const classes = useStyles()
|
||||
const translate = useTranslate()
|
||||
const dataProvider = useDataProvider()
|
||||
const { permissions } = usePermissions()
|
||||
const [report, setReport] = useState(null)
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const isAdmin = permissions === 'admin'
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAdmin) return undefined
|
||||
let live = true
|
||||
dataProvider
|
||||
.explainArtwork(resource, id)
|
||||
.then(({ data }) => live && setReport(data))
|
||||
.catch(() => live && setReport(null))
|
||||
return () => {
|
||||
live = false
|
||||
}
|
||||
}, [dataProvider, resource, id, isAdmin])
|
||||
|
||||
if (!isAdmin || !report) return null
|
||||
|
||||
const recorded = !!report.stored
|
||||
return (
|
||||
<>
|
||||
<TableRow>
|
||||
<TableCell colSpan={2}>
|
||||
<strong>{translate('artwork.title')}</strong>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<Row label={translate('artwork.result')}>{report.result}</Row>
|
||||
{recorded ? (
|
||||
<>
|
||||
<Row label={translate('artwork.source')}>{report.stored?.source}</Row>
|
||||
<Row label={translate('artwork.attemptedAt')}>
|
||||
<DateField record={report.stored} source="attemptedAt" showTime />
|
||||
</Row>
|
||||
</>
|
||||
) : (
|
||||
<Row label={translate('artwork.source')}>
|
||||
{translate('artwork.notRecorded')}
|
||||
</Row>
|
||||
)}
|
||||
<TableRow>
|
||||
<TableCell colSpan={2}>
|
||||
<Link
|
||||
component="button"
|
||||
className={classes.toggle}
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
>
|
||||
{translate(
|
||||
expanded ? 'artwork.hideDetails' : 'artwork.showDetails',
|
||||
)}
|
||||
</Link>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{expanded && (
|
||||
<>
|
||||
<StepTable title={translate('artwork.chain')} steps={report.steps} />
|
||||
<StepTable
|
||||
title={translate('artwork.lastAttemptFailed')}
|
||||
steps={report.lastAttemptFailed}
|
||||
/>
|
||||
<StepTable
|
||||
title={translate('artwork.gaveUpAfter')}
|
||||
steps={report.gaveUpAfter}
|
||||
/>
|
||||
{report.stored?.sourcePath && (
|
||||
<Row label={translate('artwork.sourcePath')}>
|
||||
{report.stored.sourcePath}
|
||||
</Row>
|
||||
)}
|
||||
{report.queued && (
|
||||
<>
|
||||
<Row label={translate('artwork.priority')}>
|
||||
{report.queued.priorityName}
|
||||
</Row>
|
||||
<Row label={translate('artwork.attempts')}>
|
||||
{report.queued.attempts}
|
||||
</Row>
|
||||
<Row label={translate('artwork.retryAt')}>
|
||||
<DateField record={report.queued} source="retryAt" showTime />
|
||||
</Row>
|
||||
</>
|
||||
)}
|
||||
{report.config && (
|
||||
<Row label={report.config.setting}>{report.config.value}</Row>
|
||||
)}
|
||||
{report.agents && (
|
||||
<Row label={translate('artwork.agents')}>
|
||||
{report.agents}
|
||||
{report.agentsIncomplete && (
|
||||
<div>{translate('artwork.agentsIncomplete')}</div>
|
||||
)}
|
||||
</Row>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
ArtworkInfo.propTypes = {
|
||||
resource: PropTypes.oneOf(['album', 'artist']).isRequired,
|
||||
id: PropTypes.string.isRequired,
|
||||
}
|
||||
108
ui/src/common/ArtworkInfo.test.jsx
Normal file
108
ui/src/common/ArtworkInfo.test.jsx
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
import React from 'react'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ArtworkInfo } from './ArtworkInfo'
|
||||
|
||||
const explainArtwork = vi.fn()
|
||||
const { mockPermissions } = vi.hoisted(() => ({
|
||||
mockPermissions: { value: 'admin' },
|
||||
}))
|
||||
|
||||
vi.mock('react-admin', async (importOriginal) => {
|
||||
const actual = await importOriginal()
|
||||
return {
|
||||
...actual,
|
||||
useDataProvider: () => ({ explainArtwork }),
|
||||
usePermissions: () => ({ permissions: mockPermissions.value }),
|
||||
useTranslate: () => (key) => key,
|
||||
}
|
||||
})
|
||||
|
||||
const report = {
|
||||
result: 'resolved from external:deezer',
|
||||
chainOrigin: 'recorded 2026-09-01T10:00:00Z',
|
||||
stored: {
|
||||
source: 'external:deezer',
|
||||
sourcePath: '/music/Radiohead/folder.jpg',
|
||||
attemptedAt: '2026-09-01T10:00:00Z',
|
||||
},
|
||||
steps: [
|
||||
{ candidate: 'cover.*', outcome: 'miss' },
|
||||
{
|
||||
candidate: 'external:deezer',
|
||||
outcome: 'hit',
|
||||
detail: 'https://cdn/x.jpg',
|
||||
},
|
||||
],
|
||||
queued: { priority: 20, priorityName: 'scan', attempts: 1, retryAt: '' },
|
||||
config: { setting: 'ArtistArtPriority', value: 'external' },
|
||||
}
|
||||
|
||||
// ArtworkInfo renders bare TableRows to slot into the caller's TableBody, so it needs a
|
||||
// table/tbody ancestor or React logs DOM-nesting warnings.
|
||||
const renderInTable = (ui) =>
|
||||
render(
|
||||
<table>
|
||||
<tbody>{ui}</tbody>
|
||||
</table>,
|
||||
)
|
||||
|
||||
describe('<ArtworkInfo />', () => {
|
||||
beforeEach(() => {
|
||||
mockPermissions.value = 'admin'
|
||||
explainArtwork.mockReset()
|
||||
explainArtwork.mockResolvedValue({ data: report })
|
||||
})
|
||||
|
||||
it('renders nothing for a non-admin', () => {
|
||||
mockPermissions.value = 'regular'
|
||||
const { container } = renderInTable(
|
||||
<ArtworkInfo resource="artist" id="ar-1" />,
|
||||
)
|
||||
expect(container.querySelector('tbody')).toBeEmptyDOMElement()
|
||||
expect(explainArtwork).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows the summary for an admin', async () => {
|
||||
renderInTable(<ArtworkInfo resource="artist" id="ar-1" />)
|
||||
expect(
|
||||
await screen.findByText('resolved from external:deezer'),
|
||||
).toBeInTheDocument()
|
||||
expect(screen.queryByText('external:deezer')).not.toBeNull()
|
||||
expect(screen.queryByText('cover.*')).toBeNull()
|
||||
})
|
||||
|
||||
it('reveals the step table when details are expanded', async () => {
|
||||
renderInTable(<ArtworkInfo resource="artist" id="ar-1" />)
|
||||
await screen.findByText('resolved from external:deezer')
|
||||
await userEvent.click(screen.getByText('artwork.showDetails'))
|
||||
expect(screen.getByText('cover.*')).toBeInTheDocument()
|
||||
expect(screen.getByText('ArtistArtPriority:')).toBeInTheDocument()
|
||||
expect(screen.getByText('/music/Radiohead/folder.jpg')).toBeInTheDocument()
|
||||
expect(screen.getByText('scan')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the not-recorded state', async () => {
|
||||
explainArtwork.mockResolvedValue({
|
||||
data: { result: 'not resolved', chainOrigin: 'not recorded', steps: [] },
|
||||
})
|
||||
renderInTable(<ArtworkInfo resource="artist" id="ar-1" />)
|
||||
expect(await screen.findByText('artwork.notRecorded')).toBeInTheDocument()
|
||||
|
||||
// stored/queued/config/agents are all omitted by the endpoint here, so the optional
|
||||
// blocks' guards must not throw when expanded.
|
||||
await userEvent.click(screen.getByText('artwork.showDetails'))
|
||||
expect(screen.queryByText('artwork.priority')).toBeNull()
|
||||
expect(screen.queryByText('artwork.agents')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders nothing when the fetch fails', async () => {
|
||||
explainArtwork.mockRejectedValue(new Error('boom'))
|
||||
const { container } = renderInTable(
|
||||
<ArtworkInfo resource="artist" id="ar-1" />,
|
||||
)
|
||||
await waitFor(() => expect(explainArtwork).toHaveBeenCalled())
|
||||
expect(container.querySelector('tbody')).toBeEmptyDOMElement()
|
||||
})
|
||||
})
|
||||
|
|
@ -146,9 +146,9 @@ const ContextMenu = ({
|
|||
...(!hideInfo && {
|
||||
info: {
|
||||
enabled: true,
|
||||
needData: true,
|
||||
needData: false,
|
||||
label: translate('resources.album.actions.info'),
|
||||
action: () => dispatch(openExtendedInfoDialog(record)),
|
||||
action: (record) => dispatch(openExtendedInfoDialog(record, resource)),
|
||||
},
|
||||
}),
|
||||
}
|
||||
|
|
@ -272,7 +272,6 @@ export const ArtistContextMenu = (props) =>
|
|||
props.record ? (
|
||||
<ContextMenu
|
||||
{...props}
|
||||
hideInfo={true}
|
||||
resource={'artist'}
|
||||
songQueryParams={{
|
||||
pagination: { page: 1, perPage: 200 },
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { TestContext } from 'ra-test'
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ThemeProvider, createTheme } from '@material-ui/core/styles'
|
||||
import { AlbumContextMenu, ArtistContextMenu } from './ContextMenus'
|
||||
import { EXTENDED_INFO_OPEN } from '../actions'
|
||||
|
||||
const mockDispatch = vi.fn()
|
||||
vi.mock('react-redux', () => ({ useDispatch: () => mockDispatch }))
|
||||
|
|
@ -130,4 +131,28 @@ describe('ContextMenus', () => {
|
|||
expect(mockRefreshMetadata).toHaveBeenCalledWith('album', 'al1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('info dialog', () => {
|
||||
it('dispatches the record and resource when opening the info dialog', () => {
|
||||
const record = { id: 'al1', name: 'Album', songCount: 1 }
|
||||
renderMenu(AlbumContextMenu, record)
|
||||
fireEvent.click(screen.getByText('resources.album.actions.info'))
|
||||
expect(mockDispatch).toHaveBeenCalledWith({
|
||||
type: EXTENDED_INFO_OPEN,
|
||||
record,
|
||||
resource: 'album',
|
||||
})
|
||||
})
|
||||
|
||||
it('dispatches the record and resource when opening the artist info dialog', () => {
|
||||
const record = { id: 'ar1', name: 'Artist', stats: {} }
|
||||
renderMenu(ArtistContextMenu, record)
|
||||
fireEvent.click(screen.getByText('resources.album.actions.info'))
|
||||
expect(mockDispatch).toHaveBeenCalledWith({
|
||||
type: EXTENDED_INFO_OPEN,
|
||||
record,
|
||||
resource: 'artist',
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -165,7 +165,7 @@ export const SongContextMenu = ({
|
|||
}
|
||||
}
|
||||
|
||||
dispatch(openExtendedInfoDialog(fullRecord))
|
||||
dispatch(openExtendedInfoDialog(fullRecord, 'song'))
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { TestContext } from 'ra-test'
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { SongContextMenu } from './SongContextMenu'
|
||||
import subsonic from '../subsonic'
|
||||
import { EXTENDED_INFO_OPEN } from '../actions'
|
||||
|
||||
vi.mock('../dataProvider', () => ({
|
||||
httpClient: vi.fn(),
|
||||
|
|
@ -130,6 +131,26 @@ describe('SongContextMenu', () => {
|
|||
expect(mockOnClick).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('dispatches the record and resource when opening the info dialog', async () => {
|
||||
const record = { id: 'song1', size: 1 }
|
||||
render(
|
||||
<TestContext>
|
||||
<SongContextMenu record={record} resource="song" />
|
||||
</TestContext>,
|
||||
)
|
||||
fireEvent.click(screen.getAllByRole('button')[1])
|
||||
await waitFor(() => screen.getByText(/resources\.song\.actions\.info/))
|
||||
fireEvent.click(screen.getByText(/resources\.song\.actions\.info/))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mockDispatch).toHaveBeenCalledWith({
|
||||
type: EXTENDED_INFO_OPEN,
|
||||
record,
|
||||
resource: 'song',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
describe('Instant Mix action', () => {
|
||||
it('calls getSimilarSongs2 with song id and shows loading notification', async () => {
|
||||
render(
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
export * from './AddToPlaylistButton'
|
||||
export * from './artist'
|
||||
export * from './ArtistLinkField'
|
||||
export * from './ArtworkInfo'
|
||||
export * from './BatchPlayButton'
|
||||
export * from './BitrateField'
|
||||
export * from './CollapsibleComment'
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { REST_URL } from '../consts'
|
|||
|
||||
const dataProvider = jsonServerProvider(REST_URL, httpClient)
|
||||
|
||||
const REFRESH_KIND = { album: 'al', artist: 'ar' }
|
||||
const ARTWORK_KIND = { album: 'al', artist: 'ar' }
|
||||
|
||||
const isAdmin = () => {
|
||||
const role = localStorage.getItem('role')
|
||||
|
|
@ -244,9 +244,13 @@ const wrapperDataProvider = {
|
|||
// The endpoint answers 204 with no body, but react-admin rejects any response without a
|
||||
// `data` key, so the id stands in for one.
|
||||
refreshMetadata: (resource, id) =>
|
||||
httpClient(`${REST_URL}/metadata/${REFRESH_KIND[resource]}/${id}/refresh`, {
|
||||
httpClient(`${REST_URL}/metadata/${ARTWORK_KIND[resource]}/${id}/refresh`, {
|
||||
method: 'POST',
|
||||
}).then(() => ({ data: { id } })),
|
||||
explainArtwork: (resource, id) =>
|
||||
httpClient(
|
||||
`${REST_URL}/artwork/explain?kind=${ARTWORK_KIND[resource]}&id=${encodeURIComponent(id)}`,
|
||||
).then(({ json }) => ({ data: json })),
|
||||
}
|
||||
|
||||
export default wrapperDataProvider
|
||||
|
|
|
|||
|
|
@ -135,4 +135,23 @@ describe('wrapperDataProvider', () => {
|
|||
).resolves.toEqual({ data: { id: 'al-1' } })
|
||||
})
|
||||
})
|
||||
|
||||
describe('explainArtwork', () => {
|
||||
it('requests the artist kind prefix', async () => {
|
||||
mockHttpClient.mockResolvedValue({ json: { name: 'Radiohead' } })
|
||||
const result = await wrapperDataProvider.explainArtwork('artist', 'ar-1')
|
||||
expect(mockHttpClient).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/artwork/explain?kind=ar&id=ar-1'),
|
||||
)
|
||||
expect(result).toEqual({ data: { name: 'Radiohead' } })
|
||||
})
|
||||
|
||||
it('requests the album kind prefix', async () => {
|
||||
mockHttpClient.mockResolvedValue({ json: {} })
|
||||
await wrapperDataProvider.explainArtwork('album', 'al-1')
|
||||
expect(mockHttpClient).toHaveBeenCalledWith(
|
||||
expect.stringContaining('kind=al&id=al-1'),
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -11,10 +11,16 @@ import {
|
|||
} from '@material-ui/core'
|
||||
import { closeExtendedInfoDialog } from '../actions'
|
||||
|
||||
const ExpandInfoDialog = ({ title, content }) => {
|
||||
const { open, record } = useSelector((state) => state.expandInfoDialog)
|
||||
const ExpandInfoDialog = ({ title, content, resource }) => {
|
||||
const {
|
||||
open,
|
||||
record,
|
||||
resource: openFor,
|
||||
} = useSelector((state) => state.expandInfoDialog)
|
||||
const dispatch = useDispatch()
|
||||
const translate = useTranslate()
|
||||
// One page may mount several of these; each claims the resource it was given.
|
||||
const mine = !resource || resource === openFor
|
||||
|
||||
const handleClose = (e) => {
|
||||
dispatch(closeExtendedInfoDialog())
|
||||
|
|
@ -23,7 +29,7 @@ const ExpandInfoDialog = ({ title, content }) => {
|
|||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
open={open && mine}
|
||||
onClose={handleClose}
|
||||
aria-labelledby="info-dialog-album"
|
||||
fullWidth={true}
|
||||
|
|
@ -33,7 +39,7 @@ const ExpandInfoDialog = ({ title, content }) => {
|
|||
{translate(title || 'resources.song.actions.info')}
|
||||
</DialogTitle>
|
||||
<DialogContent>
|
||||
{record && (
|
||||
{record && mine && (
|
||||
<RecordContextProvider value={record}>
|
||||
{content}
|
||||
</RecordContextProvider>
|
||||
|
|
@ -50,7 +56,8 @@ const ExpandInfoDialog = ({ title, content }) => {
|
|||
|
||||
ExpandInfoDialog.propTypes = {
|
||||
title: PropTypes.string,
|
||||
content: PropTypes.object.isRequired,
|
||||
content: PropTypes.element.isRequired,
|
||||
resource: PropTypes.string,
|
||||
}
|
||||
|
||||
export default ExpandInfoDialog
|
||||
|
|
|
|||
54
ui/src/dialogs/ExpandInfoDialog.test.jsx
Normal file
54
ui/src/dialogs/ExpandInfoDialog.test.jsx
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import * as React from 'react'
|
||||
import { TestContext } from 'ra-test'
|
||||
import { render, screen, cleanup } from '@testing-library/react'
|
||||
import { describe, afterEach, it, expect } from 'vitest'
|
||||
import ExpandInfoDialog from './ExpandInfoDialog'
|
||||
|
||||
const renderDialogs = (openFor, dialogs) =>
|
||||
render(
|
||||
<TestContext
|
||||
initialState={{
|
||||
expandInfoDialog: {
|
||||
open: true,
|
||||
record: { id: 'r1', name: 'Record' },
|
||||
resource: openFor,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{dialogs}
|
||||
</TestContext>,
|
||||
)
|
||||
|
||||
describe('ExpandInfoDialog', () => {
|
||||
afterEach(cleanup)
|
||||
|
||||
it('renders an unclaimed dialog for any resource', () => {
|
||||
renderDialogs('song', <ExpandInfoDialog content={<div>Song Info</div>} />)
|
||||
expect(screen.getByText('Song Info')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
// Guards the artist detail page, which mounts both dialogs: an album card's Get Info
|
||||
// must open AlbumInfo, and the page's own ArtistInfo must stay shut.
|
||||
it.each([
|
||||
['artist', 'Artist Info', 'Album Info'],
|
||||
['album', 'Album Info', 'Artist Info'],
|
||||
])('opens only the %s dialog', (openFor, shown, hidden) => {
|
||||
renderDialogs(
|
||||
openFor,
|
||||
<>
|
||||
<ExpandInfoDialog resource="album" content={<div>Album Info</div>} />
|
||||
<ExpandInfoDialog resource="artist" content={<div>Artist Info</div>} />
|
||||
</>,
|
||||
)
|
||||
expect(screen.getByText(shown)).toBeInTheDocument()
|
||||
expect(screen.queryByText(hidden)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('stays shut when no mounted dialog claims the resource', () => {
|
||||
renderDialogs(
|
||||
'artist',
|
||||
<ExpandInfoDialog resource="album" content={<div>Album Info</div>} />,
|
||||
)
|
||||
expect(screen.queryByText('Album Info')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
|
@ -111,10 +111,14 @@
|
|||
"name": "Artist |||| Artists",
|
||||
"fields": {
|
||||
"name": "Name",
|
||||
"sortArtistName": "Sort Name",
|
||||
"mbzArtistId": "MusicBrainz Artist Id",
|
||||
"albumCount": "Album Count",
|
||||
"songCount": "Song Count",
|
||||
"size": "Size",
|
||||
"playCount": "Plays",
|
||||
"externalInfoUpdatedAt": "External Info Updated At",
|
||||
"updatedAt": "Updated At",
|
||||
"rating": "Rating",
|
||||
"genre": "Genre",
|
||||
"role": "Role",
|
||||
|
|
@ -702,6 +706,24 @@
|
|||
"sharedPlaylists": "Shared Playlists",
|
||||
"about": "About"
|
||||
},
|
||||
"artwork": {
|
||||
"title": "Artwork",
|
||||
"chain": "Chain",
|
||||
"result": "Result",
|
||||
"source": "Source",
|
||||
"attemptedAt": "Attempted at",
|
||||
"sourcePath": "Source path",
|
||||
"showDetails": "Show details",
|
||||
"hideDetails": "Hide details",
|
||||
"priority": "Priority",
|
||||
"attempts": "Attempts",
|
||||
"retryAt": "Retry at",
|
||||
"lastAttemptFailed": "Last attempt failed",
|
||||
"gaveUpAfter": "Gave up after",
|
||||
"agents": "Agents",
|
||||
"agentsIncomplete": "* This agent is configured but cannot supply images",
|
||||
"notRecorded": "No resolution recorded yet"
|
||||
},
|
||||
"player": {
|
||||
"playListsText": "Play Queue",
|
||||
"openText": "Open",
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
import React, { useState, useCallback, useEffect } from 'react'
|
||||
import React, { useState, useCallback } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
import { Field, Form } from 'react-final-form'
|
||||
import { useDispatch } from 'react-redux'
|
||||
import { useHistory } from 'react-router-dom'
|
||||
import Button from '@material-ui/core/Button'
|
||||
import Card from '@material-ui/core/Card'
|
||||
import CardActions from '@material-ui/core/CardActions'
|
||||
|
|
@ -12,7 +11,6 @@ import TextField from '@material-ui/core/TextField'
|
|||
import { ThemeProvider, makeStyles } from '@material-ui/core/styles'
|
||||
import {
|
||||
createMuiTheme,
|
||||
useCheckAuth,
|
||||
useLogin,
|
||||
useNotify,
|
||||
useTranslate,
|
||||
|
|
@ -324,16 +322,6 @@ const Login = ({ location }) => {
|
|||
const notify = useNotify()
|
||||
const login = useLogin()
|
||||
const dispatch = useDispatch()
|
||||
const checkAuth = useCheckAuth()
|
||||
const history = useHistory()
|
||||
|
||||
// Signed-in users opening #/login go straight to the app;
|
||||
// replace keeps Back from bouncing.
|
||||
useEffect(() => {
|
||||
checkAuth({}, false)
|
||||
.then(() => history.replace('/'))
|
||||
.catch(() => {})
|
||||
}, [checkAuth, history])
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
(auth) => {
|
||||
|
|
|
|||
|
|
@ -1,70 +0,0 @@
|
|||
import React from 'react'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import { describe, it, beforeEach, vi } from 'vitest'
|
||||
import { Provider } from 'react-redux'
|
||||
import { createStore } from 'redux'
|
||||
import { createMuiTheme } from '@material-ui/core/styles'
|
||||
import Login from './Login'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
checkAuth: vi.fn(),
|
||||
push: vi.fn(),
|
||||
replace: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('react-admin', () => ({
|
||||
createMuiTheme: (theme) => theme,
|
||||
useCheckAuth: () => mocks.checkAuth,
|
||||
useLogin: () => vi.fn(() => Promise.resolve()),
|
||||
useNotify: () => vi.fn(),
|
||||
useTranslate: () => (x) => x,
|
||||
useVersion: () => 1,
|
||||
}))
|
||||
|
||||
vi.mock('react-router-dom', () => ({
|
||||
useHistory: () => ({ push: mocks.push, replace: mocks.replace }),
|
||||
}))
|
||||
|
||||
vi.mock('../themes/useCurrentTheme', () => ({
|
||||
default: () => createMuiTheme({}),
|
||||
}))
|
||||
|
||||
vi.mock('./Notification', () => ({
|
||||
default: () => <div />,
|
||||
}))
|
||||
|
||||
const renderLogin = () =>
|
||||
render(
|
||||
<Provider store={createStore(() => ({}))}>
|
||||
<Login location={{}} />
|
||||
</Provider>,
|
||||
)
|
||||
|
||||
describe('<Login />', () => {
|
||||
beforeEach(() => {
|
||||
mocks.checkAuth.mockReset()
|
||||
mocks.push.mockReset()
|
||||
mocks.replace.mockReset()
|
||||
})
|
||||
|
||||
it('replaces the login page with the home page when already signed in', async () => {
|
||||
mocks.checkAuth.mockResolvedValue()
|
||||
|
||||
renderLogin()
|
||||
|
||||
await waitFor(() => expect(mocks.replace).toHaveBeenCalledWith('/'))
|
||||
expect(mocks.checkAuth).toHaveBeenCalledWith({}, false)
|
||||
expect(mocks.push).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows the login form when the user is not signed in', async () => {
|
||||
mocks.checkAuth.mockRejectedValue()
|
||||
|
||||
renderLogin()
|
||||
|
||||
await waitFor(() => expect(mocks.checkAuth).toHaveBeenCalledWith({}, false))
|
||||
expect(screen.getByText('ra.auth.sign_in')).toBeInTheDocument()
|
||||
expect(mocks.replace).not.toHaveBeenCalled()
|
||||
expect(mocks.push).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
|
@ -127,6 +127,7 @@ export const expandInfoDialogReducer = (
|
|||
previousState = {
|
||||
open: false,
|
||||
record: undefined,
|
||||
resource: undefined,
|
||||
},
|
||||
payload,
|
||||
) => {
|
||||
|
|
@ -137,12 +138,14 @@ export const expandInfoDialogReducer = (
|
|||
...previousState,
|
||||
open: true,
|
||||
record: payload.record,
|
||||
resource: payload.resource,
|
||||
}
|
||||
case EXTENDED_INFO_CLOSE:
|
||||
return {
|
||||
...previousState,
|
||||
open: false,
|
||||
record: undefined,
|
||||
resource: undefined,
|
||||
}
|
||||
default:
|
||||
return previousState
|
||||
|
|
|
|||
45
ui/src/reducers/dialogReducer.test.js
Normal file
45
ui/src/reducers/dialogReducer.test.js
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { describe, it, expect } from 'vitest'
|
||||
import { expandInfoDialogReducer } from './dialogReducer'
|
||||
import { EXTENDED_INFO_OPEN, EXTENDED_INFO_CLOSE } from '../actions'
|
||||
|
||||
describe('expandInfoDialogReducer', () => {
|
||||
it('stores the record and resource on EXTENDED_INFO_OPEN', () => {
|
||||
const record = { id: 'al1', name: 'Album' }
|
||||
const result = expandInfoDialogReducer(
|
||||
{ open: false, record: undefined, resource: undefined },
|
||||
{ type: EXTENDED_INFO_OPEN, record, resource: 'album' },
|
||||
)
|
||||
|
||||
expect(result).toEqual({ open: true, record, resource: 'album' })
|
||||
})
|
||||
|
||||
it('clears the record and resource on EXTENDED_INFO_CLOSE', () => {
|
||||
const previousState = {
|
||||
open: true,
|
||||
record: { id: 'al1', name: 'Album' },
|
||||
resource: 'album',
|
||||
}
|
||||
const result = expandInfoDialogReducer(previousState, {
|
||||
type: EXTENDED_INFO_CLOSE,
|
||||
})
|
||||
|
||||
expect(result).toEqual({
|
||||
open: false,
|
||||
record: undefined,
|
||||
resource: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns previous state for unknown action', () => {
|
||||
const previousState = {
|
||||
open: false,
|
||||
record: undefined,
|
||||
resource: undefined,
|
||||
}
|
||||
const result = expandInfoDialogReducer(previousState, {
|
||||
type: 'UNKNOWN_ACTION',
|
||||
})
|
||||
|
||||
expect(result).toBe(previousState)
|
||||
})
|
||||
})
|
||||
|
|
@ -5,12 +5,9 @@ export const formatBytes = (bytes, decimals = 2) => {
|
|||
const dm = decimals < 0 ? 0 : decimals
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
|
||||
|
||||
const scaled = (n) => parseFloat((bytes / Math.pow(k, n)).toFixed(dm))
|
||||
let i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
// rounding can carry the value up to k, e.g. 1048575 -> "1024 KB"
|
||||
if (scaled(i) >= k && i < sizes.length - 1) i++
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
|
||||
return scaled(i) + ' ' + sizes[i]
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
export const formatDuration = (d) => {
|
||||
|
|
|
|||
|
|
@ -16,12 +16,6 @@ describe('formatBytes', () => {
|
|||
expect(formatBytes(1024 * 1024 * 1024)).toEqual('1 GB')
|
||||
expect(formatBytes(1024 * 1024 * 1024 * 1024)).toEqual('1 TB')
|
||||
})
|
||||
|
||||
it('moves to the next unit when the value rounds up to 1024', () => {
|
||||
expect(formatBytes(1024 * 1024 - 1)).toEqual('1 MB')
|
||||
expect(formatBytes(1024 * 1024 * 1024 - 1)).toEqual('1 GB')
|
||||
expect(formatBytes(1024 * 1024 - 6)).toEqual('1023.99 KB')
|
||||
})
|
||||
})
|
||||
|
||||
const day = 86400
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue