mirror of
https://github.com/navidrome/navidrome.git
synced 2026-11-19 15:23:36 +00:00
Merge branch 'master' into apiv1-auth
This commit is contained in:
commit
0e02bced57
2
.github/workflows/pipeline.yml
vendored
2
.github/workflows/pipeline.yml
vendored
@ -79,7 +79,7 @@ jobs:
|
||||
with:
|
||||
version: ${{ steps.golangci-version.outputs.version }}
|
||||
problem-matchers: true
|
||||
args: --timeout 2m
|
||||
args: --timeout 3m
|
||||
|
||||
- name: Run go goimports
|
||||
run: go run golang.org/x/tools/cmd/goimports@latest -w `find . -name '*.go' | grep -v '_gen.go$' | grep -v '.pb.go$'`
|
||||
|
||||
@ -34,7 +34,7 @@ type deezerAgent struct {
|
||||
func deezerConstructor(dataStore model.DataStore) agents.Interface {
|
||||
agent := &deezerAgent{
|
||||
dataStore: dataStore,
|
||||
languages: conf.Server.Deezer.Languages,
|
||||
languages: conf.Server().Deezer.Languages,
|
||||
}
|
||||
httpClient := httpclient.New(consts.DefaultHttpClientTimeOut)
|
||||
cachedHttpClient := cache.NewHTTPClient(httpClient, consts.DefaultHttpClientTimeOut)
|
||||
@ -192,7 +192,7 @@ func (s *deezerAgent) GetArtistBiography(ctx context.Context, _, name, _ string)
|
||||
|
||||
func init() {
|
||||
conf.AddHook(func() {
|
||||
if conf.Server.Deezer.Enabled {
|
||||
if conf.Server().Deezer.Enabled {
|
||||
agents.Register(deezerAgentName, deezerConstructor)
|
||||
}
|
||||
})
|
||||
|
||||
@ -3,6 +3,7 @@ package deezer
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -15,3 +16,5 @@ func TestDeezer(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Deezer Test Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
@ -11,7 +11,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -23,13 +22,12 @@ var _ = Describe("deezerAgent", func() {
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.Deezer.Enabled = true
|
||||
conf.Update(func(c *conf.Options) { c.Deezer.Enabled = true })
|
||||
})
|
||||
|
||||
Describe("deezerConstructor", func() {
|
||||
It("uses configured languages", func() {
|
||||
conf.Server.Deezer.Languages = []string{"pt", "en"}
|
||||
conf.Update(func(c *conf.Options) { c.Deezer.Languages = []string{"pt", "en"} })
|
||||
agent := deezerConstructor(&tests.MockDataStore{}).(*deezerAgent)
|
||||
Expect(agent.languages).To(Equal([]string{"pt", "en"}))
|
||||
})
|
||||
@ -179,7 +177,7 @@ var _ = Describe("deezerAgent", func() {
|
||||
})
|
||||
|
||||
setupAgent := func(languages []string) {
|
||||
conf.Server.Deezer.Languages = languages
|
||||
conf.Update(func(c *conf.Options) { c.Deezer.Languages = languages })
|
||||
agent = &deezerAgent{
|
||||
dataStore: &tests.MockDataStore{},
|
||||
client: newClient(httpClient),
|
||||
|
||||
@ -50,14 +50,14 @@ type lastfmAgent struct {
|
||||
}
|
||||
|
||||
func lastFMConstructor(ds model.DataStore) *lastfmAgent {
|
||||
if !conf.Server.LastFM.Enabled || conf.Server.LastFM.ApiKey == "" || conf.Server.LastFM.Secret == "" {
|
||||
if !conf.Server().LastFM.Enabled || conf.Server().LastFM.ApiKey == "" || conf.Server().LastFM.Secret == "" {
|
||||
return nil
|
||||
}
|
||||
l := &lastfmAgent{
|
||||
ds: ds,
|
||||
languages: conf.Server.LastFM.Languages,
|
||||
apiKey: conf.Server.LastFM.ApiKey,
|
||||
secret: conf.Server.LastFM.Secret,
|
||||
languages: conf.Server().LastFM.Languages,
|
||||
apiKey: conf.Server().LastFM.ApiKey,
|
||||
secret: conf.Server().LastFM.Secret,
|
||||
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
|
||||
}
|
||||
hc := httpclient.New(consts.DefaultHttpClientTimeOut)
|
||||
@ -354,7 +354,7 @@ func (l *lastfmAgent) callTrackGetSimilar(ctx context.Context, name, artist stri
|
||||
}
|
||||
|
||||
func (l *lastfmAgent) getArtistForScrobble(track *model.MediaFile, role model.Role, displayName string) string {
|
||||
if conf.Server.LastFM.ScrobbleFirstArtistOnly && len(track.Participants[role]) > 0 {
|
||||
if conf.Server().LastFM.ScrobbleFirstArtistOnly && len(track.Participants[role]) > 0 {
|
||||
return track.Participants[role][0].Name
|
||||
}
|
||||
return displayName
|
||||
|
||||
@ -12,7 +12,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/core/scrobbler"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
@ -32,15 +31,16 @@ var _ = Describe("lastfmAgent", func() {
|
||||
BeforeEach(func() {
|
||||
ds = &tests.MockDataStore{}
|
||||
ctx = context.Background()
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.LastFM.Enabled = true
|
||||
conf.Server.LastFM.ApiKey = "123"
|
||||
conf.Server.LastFM.Secret = "secret"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.LastFM.Enabled = true
|
||||
c.LastFM.ApiKey = "123"
|
||||
c.LastFM.Secret = "secret"
|
||||
})
|
||||
})
|
||||
Describe("lastFMConstructor", func() {
|
||||
When("Agent is properly configured", func() {
|
||||
It("uses configured api key and languages", func() {
|
||||
conf.Server.LastFM.Languages = []string{"pt", "en"}
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"pt", "en"} })
|
||||
agent := lastFMConstructor(ds)
|
||||
Expect(agent.apiKey).To(Equal("123"))
|
||||
Expect(agent.secret).To(Equal("secret"))
|
||||
@ -49,19 +49,19 @@ var _ = Describe("lastfmAgent", func() {
|
||||
})
|
||||
When("Agent is disabled", func() {
|
||||
It("returns nil", func() {
|
||||
conf.Server.LastFM.Enabled = false
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.Enabled = false })
|
||||
Expect(lastFMConstructor(ds)).To(BeNil())
|
||||
})
|
||||
})
|
||||
When("ApiKey is empty", func() {
|
||||
It("returns nil", func() {
|
||||
conf.Server.LastFM.ApiKey = ""
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.ApiKey = "" })
|
||||
Expect(lastFMConstructor(ds)).To(BeNil())
|
||||
})
|
||||
})
|
||||
When("Secret is empty", func() {
|
||||
It("returns nil", func() {
|
||||
conf.Server.LastFM.Secret = ""
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.Secret = "" })
|
||||
Expect(lastFMConstructor(ds)).To(BeNil())
|
||||
})
|
||||
})
|
||||
@ -121,7 +121,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||
})
|
||||
|
||||
It("returns content in first language when available (1 API call)", func() {
|
||||
conf.Server.LastFM.Languages = []string{"pt", "en"}
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"pt", "en"} })
|
||||
agent = lastFMConstructor(ds)
|
||||
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
||||
|
||||
@ -138,7 +138,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||
})
|
||||
|
||||
It("falls back to second language when first returns empty (2 API calls)", func() {
|
||||
conf.Server.LastFM.Languages = []string{"ja", "en"}
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "en"} })
|
||||
agent = lastFMConstructor(ds)
|
||||
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
||||
|
||||
@ -159,7 +159,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||
})
|
||||
|
||||
It("returns ErrNotFound when all languages return empty", func() {
|
||||
conf.Server.LastFM.Languages = []string{"ja", "xx"}
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "xx"} })
|
||||
agent = lastFMConstructor(ds)
|
||||
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
||||
|
||||
@ -186,7 +186,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||
})
|
||||
|
||||
It("falls back to second language when first returns empty description (2 API calls)", func() {
|
||||
conf.Server.LastFM.Languages = []string{"ja", "en"}
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "en"} })
|
||||
agent = lastFMConstructor(ds)
|
||||
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
||||
|
||||
@ -208,7 +208,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||
})
|
||||
|
||||
It("returns album without description when all languages return empty", func() {
|
||||
conf.Server.LastFM.Languages = []string{"ja", "xx"}
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "xx"} })
|
||||
agent = lastFMConstructor(ds)
|
||||
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
||||
|
||||
@ -412,7 +412,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||
|
||||
When("ScrobbleFirstArtistOnly is true", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.LastFM.ScrobbleFirstArtistOnly = true
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.ScrobbleFirstArtistOnly = true })
|
||||
})
|
||||
|
||||
It("uses only the first artist", func() {
|
||||
@ -454,7 +454,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||
|
||||
When("ScrobbleFirstArtistOnly is true", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.LastFM.ScrobbleFirstArtistOnly = true
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.ScrobbleFirstArtistOnly = true })
|
||||
})
|
||||
|
||||
It("uses only the first artist", func() {
|
||||
|
||||
@ -37,8 +37,8 @@ type Router struct {
|
||||
func NewRouter(ds model.DataStore) *Router {
|
||||
r := &Router{
|
||||
ds: ds,
|
||||
apiKey: conf.Server.LastFM.ApiKey,
|
||||
secret: conf.Server.LastFM.Secret,
|
||||
apiKey: conf.Server().LastFM.ApiKey,
|
||||
secret: conf.Server().LastFM.Secret,
|
||||
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
|
||||
}
|
||||
r.Handler = r.routes()
|
||||
|
||||
@ -3,6 +3,7 @@ package lastfm
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -15,3 +16,5 @@ func TestLastFM(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "LastFM Test Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
@ -31,7 +31,7 @@ func listenBrainzConstructor(ds model.DataStore) *listenBrainzAgent {
|
||||
l := &listenBrainzAgent{
|
||||
ds: ds,
|
||||
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
|
||||
baseURL: conf.Server.ListenBrainz.BaseURL,
|
||||
baseURL: conf.Server().ListenBrainz.BaseURL,
|
||||
}
|
||||
hc := httpclient.New(consts.DefaultHttpClientTimeOut)
|
||||
chc := cache.NewHTTPClient(hc, consts.DefaultHttpClientTimeOut)
|
||||
@ -229,7 +229,7 @@ func (l *listenBrainzAgent) PlaybackReport(context.Context, scrobbler.PlaybackSe
|
||||
|
||||
func init() {
|
||||
conf.AddHook(func() {
|
||||
if conf.Server.ListenBrainz.Enabled {
|
||||
if conf.Server().ListenBrainz.Enabled {
|
||||
scrobbler.Register(listenBrainzAgentName, func(ds model.DataStore) scrobbler.Scrobbler {
|
||||
// This is a workaround for the fact that a (Interface)(nil) is not the same as a (*listenBrainzAgent)(nil)
|
||||
// See https://go.dev/doc/faq#nil_error
|
||||
|
||||
@ -39,7 +39,7 @@ func NewRouter(ds model.DataStore) *Router {
|
||||
}
|
||||
r.Handler = r.routes()
|
||||
hc := httpclient.New(consts.DefaultHttpClientTimeOut)
|
||||
r.client = newClient(conf.Server.ListenBrainz.BaseURL, hc)
|
||||
r.client = newClient(conf.Server().ListenBrainz.BaseURL, hc)
|
||||
return r
|
||||
}
|
||||
|
||||
|
||||
@ -315,7 +315,7 @@ func (c *client) getSimilarArtists(ctx context.Context, mbid string, limit int)
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-artists/json", nil)
|
||||
req.Header.Add("Content-Type", "application/json; charset=UTF-8")
|
||||
req.URL.RawQuery = url.Values{
|
||||
"artist_mbids": []string{mbid}, "algorithm": []string{conf.Server.ListenBrainz.ArtistAlgorithm},
|
||||
"artist_mbids": []string{mbid}, "algorithm": []string{conf.Server().ListenBrainz.ArtistAlgorithm},
|
||||
}.Encode()
|
||||
|
||||
log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL)
|
||||
@ -354,7 +354,7 @@ func (c *client) getSimilarRecordings(ctx context.Context, mbid string, limit in
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-recordings/json", nil)
|
||||
req.Header.Add("Content-Type", "application/json; charset=UTF-8")
|
||||
req.URL.RawQuery = url.Values{
|
||||
"recording_mbids": []string{mbid}, "algorithm": []string{conf.Server.ListenBrainz.TrackAlgorithm},
|
||||
"recording_mbids": []string{mbid}, "algorithm": []string{conf.Server().ListenBrainz.TrackAlgorithm},
|
||||
}.Encode()
|
||||
|
||||
log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL)
|
||||
|
||||
@ -13,7 +13,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -257,7 +256,6 @@ var _ = Describe("client", func() {
|
||||
|
||||
BeforeEach(func() {
|
||||
algorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30"
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
})
|
||||
|
||||
getUrl := func(mbid string) string {
|
||||
@ -307,7 +305,7 @@ var _ = Describe("client", func() {
|
||||
|
||||
It("fetches a different endpoint when algorithm changes", func() {
|
||||
algorithm = "session_based_days_1825_session_300_contribution_3_threshold_10_limit_100_filter_True_skip_30"
|
||||
conf.Server.ListenBrainz.ArtistAlgorithm = algorithm
|
||||
conf.Update(func(c *conf.Options) { c.ListenBrainz.ArtistAlgorithm = algorithm })
|
||||
|
||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
@ -328,7 +326,6 @@ var _ = Describe("client", func() {
|
||||
|
||||
BeforeEach(func() {
|
||||
algorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30"
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
})
|
||||
|
||||
getUrl := func(mbid string) string {
|
||||
@ -444,7 +441,7 @@ var _ = Describe("client", func() {
|
||||
|
||||
It("uses a different algorithm when configured", func() {
|
||||
algorithm = "session_based_days_180_session_300_contribution_5_threshold_15_limit_50_skip_30"
|
||||
conf.Server.ListenBrainz.TrackAlgorithm = algorithm
|
||||
conf.Update(func(c *conf.Options) { c.ListenBrainz.TrackAlgorithm = algorithm })
|
||||
|
||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
|
||||
@ -3,6 +3,7 @@ package listenbrainz
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -15,3 +16,5 @@ func TestListenBrainz(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "ListenBrainz Test Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
@ -416,7 +416,7 @@ func needsImageAgents(kinds []model.Kind) bool {
|
||||
// configuredAgents names the agents in priority order; one absent from it can never supply an image.
|
||||
func configuredAgents() []string {
|
||||
var names []string
|
||||
for name := range strings.SplitSeq(conf.Server.Agents, ",") {
|
||||
for name := range strings.SplitSeq(conf.Server().Agents, ",") {
|
||||
if name = strings.TrimSpace(name); name != "" {
|
||||
names = append(names, name)
|
||||
}
|
||||
@ -811,13 +811,13 @@ func explainResult(source string, steps []artwork.TraceStep) string {
|
||||
func explainConfig(kind model.Kind) (name, value string) {
|
||||
switch kind {
|
||||
case model.KindArtistArtwork:
|
||||
return "ArtistArtPriority", conf.Server.ArtistArtPriority
|
||||
return "ArtistArtPriority", conf.Server().ArtistArtPriority
|
||||
case model.KindAlbumArtwork:
|
||||
return "CoverArtPriority", conf.Server.CoverArtPriority
|
||||
return "CoverArtPriority", conf.Server().CoverArtPriority
|
||||
case model.KindDiscArtwork:
|
||||
return "DiscArtPriority", conf.Server.DiscArtPriority
|
||||
return "DiscArtPriority", conf.Server().DiscArtPriority
|
||||
case model.KindMediaFileArtwork:
|
||||
return "EnableMediaFileCoverArt", strconv.FormatBool(conf.Server.EnableMediaFileCoverArt)
|
||||
return "EnableMediaFileCoverArt", strconv.FormatBool(conf.Server().EnableMediaFileCoverArt)
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
@ -1002,7 +1002,7 @@ func runExplain(ctx context.Context, args []string) {
|
||||
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))
|
||||
rep.agents = explainAgents(conf.Server().Agents, availableImageAgents(ds, mgr, kind))
|
||||
}
|
||||
switch {
|
||||
case rep.walked:
|
||||
|
||||
@ -8,7 +8,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/core/artwork"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
@ -226,8 +225,7 @@ var _ = Describe("formatExplain", func() {
|
||||
var rep explainReport
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.ArtistArtPriority = "external, artist.*"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external, artist.*" })
|
||||
rep = explainReport{
|
||||
kind: model.KindArtistArtwork,
|
||||
id: "ar-1",
|
||||
@ -289,7 +287,7 @@ var _ = Describe("formatExplain", func() {
|
||||
})
|
||||
|
||||
It("says a kind that does not walk a chain has no chain, without an empty table", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*, embedded"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*, embedded" })
|
||||
rep.kind = model.KindPlaylistArtwork
|
||||
rep.steps = nil
|
||||
rep.agents = ""
|
||||
@ -305,7 +303,7 @@ var _ = Describe("formatExplain", func() {
|
||||
})
|
||||
|
||||
It("says disc artwork keeps no state instead of reporting it as unresolved state", func() {
|
||||
conf.Server.DiscArtPriority = "cover.jpg, embedded"
|
||||
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"}},
|
||||
@ -387,7 +385,7 @@ var _ = Describe("formatExplain", func() {
|
||||
})
|
||||
|
||||
It("reports the setting that governs media file artwork", func() {
|
||||
conf.Server.EnableMediaFileCoverArt = false
|
||||
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false })
|
||||
rep = explainReport{
|
||||
kind: model.KindMediaFileArtwork, id: "mf-1", name: "Airbag",
|
||||
walked: true,
|
||||
@ -406,9 +404,10 @@ var _ = Describe("formatExplain", func() {
|
||||
|
||||
var _ = Describe("explainConfig", func() {
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.DiscArtPriority = "cover.jpg"
|
||||
conf.Server.EnableMediaFileCoverArt = true
|
||||
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",
|
||||
@ -578,10 +577,11 @@ var _ = Describe("reprocessArtwork", func() {
|
||||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.CoverArtPriority = "cover.*, external"
|
||||
conf.Server.ArtistArtPriority = "artist.*, external"
|
||||
conf.Server.EnableM3UExternalAlbumArt = false
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "cover.*, external"
|
||||
c.ArtistArtPriority = "artist.*, external"
|
||||
c.EnableM3UExternalAlbumArt = false
|
||||
})
|
||||
imageAgents = artwork.ImageAgentCount{Artist: 1, Album: 1}
|
||||
ds = &tests.MockDataStore{}
|
||||
art = ds.Artwork().(*tests.MockArtworkRepo)
|
||||
@ -714,7 +714,7 @@ var _ = Describe("reprocessArtwork", func() {
|
||||
})
|
||||
|
||||
It("says so when the selection needs no external lookup", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*" })
|
||||
put(model.KindPlaylistArtwork, "pl-1", "playlist")
|
||||
|
||||
Expect(reprocessArtwork(ctx, ds, []model.Kind{model.KindPlaylistArtwork}, nil, imageAgents, true, accept, &out)).To(Succeed())
|
||||
@ -723,8 +723,10 @@ var _ = Describe("reprocessArtwork", func() {
|
||||
})
|
||||
|
||||
It("counts playlists as external cost when the m3u image fetch is enabled", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*"
|
||||
conf.Server.EnableM3UExternalAlbumArt = true
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "cover.*"
|
||||
c.EnableM3UExternalAlbumArt = true
|
||||
})
|
||||
put(model.KindPlaylistArtwork, "pl-1", "playlist")
|
||||
var external int64
|
||||
capture := func(_ io.Writer, _, e int64) bool { external = e; return false }
|
||||
@ -1012,10 +1014,11 @@ var _ = Describe("refreshItems", func() {
|
||||
|
||||
var _ = Describe("needsImageAgents", func() {
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.CoverArtPriority = "cover.*, external"
|
||||
conf.Server.ArtistArtPriority = "artist.*, external"
|
||||
conf.Server.EnableM3UExternalAlbumArt = false
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "cover.*, external"
|
||||
c.ArtistArtPriority = "artist.*, external"
|
||||
c.EnableM3UExternalAlbumArt = false
|
||||
})
|
||||
})
|
||||
|
||||
It("is false for a selection no agent can serve", func() {
|
||||
@ -1033,24 +1036,25 @@ var _ = Describe("needsImageAgents", func() {
|
||||
})
|
||||
|
||||
It("is false once the chains no longer reach an agent", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*"
|
||||
conf.Server.ArtistArtPriority = "artist.*"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "cover.*"
|
||||
c.ArtistArtPriority = "artist.*"
|
||||
})
|
||||
Expect(needsImageAgents(artwork.ReprocessKinds)).To(BeFalse())
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("configuredAgents", func() {
|
||||
BeforeEach(func() { DeferCleanup(configtest.SetupConfig()) })
|
||||
|
||||
It("splits and trims the configured list", func() {
|
||||
conf.Server.Agents = "lastfm, spotify ,deezer"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "lastfm, spotify ,deezer" })
|
||||
Expect(configuredAgents()).To(Equal([]string{"lastfm", "spotify", "deezer"}))
|
||||
})
|
||||
|
||||
// An empty name would match no plugin, but it also must not make the list look non-empty:
|
||||
// LoadPlugins treats an empty list as "load nothing".
|
||||
It("drops empty entries rather than passing a name nothing can match", func() {
|
||||
conf.Server.Agents = " , ,"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = " , ," })
|
||||
Expect(configuredAgents()).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
|
||||
@ -75,7 +75,7 @@ var (
|
||||
|
||||
func runBackup(ctx context.Context) {
|
||||
if backupDir != "" {
|
||||
conf.Server.Backup.Path = conf.NewDir(backupDir)
|
||||
conf.Update(func(c *conf.Options) { c.Backup.Path = conf.NewDir(backupDir) })
|
||||
}
|
||||
|
||||
requireExistingDB()
|
||||
@ -83,7 +83,7 @@ func runBackup(ctx context.Context) {
|
||||
start := time.Now()
|
||||
path, err := db.Backup(ctx)
|
||||
if err != nil {
|
||||
log.Fatal("Error backing up database", "backupPath", conf.Server.Backup.Path, err)
|
||||
log.Fatal("Error backing up database", "backupPath", conf.Server().Backup.Path, err)
|
||||
}
|
||||
|
||||
elapsed := time.Since(start)
|
||||
@ -91,15 +91,16 @@ func runBackup(ctx context.Context) {
|
||||
}
|
||||
|
||||
func runPrune(ctx context.Context) {
|
||||
if backupDir != "" {
|
||||
conf.Server.Backup.Path = conf.NewDir(backupDir)
|
||||
}
|
||||
conf.Update(func(c *conf.Options) {
|
||||
if backupDir != "" {
|
||||
c.Backup.Path = conf.NewDir(backupDir)
|
||||
}
|
||||
if backupCount != -1 {
|
||||
c.Backup.Count = backupCount
|
||||
}
|
||||
})
|
||||
|
||||
if backupCount != -1 {
|
||||
conf.Server.Backup.Count = backupCount
|
||||
}
|
||||
|
||||
if conf.Server.Backup.Count == 0 && !force && !confirmYES("Warning: pruning ALL backups") {
|
||||
if conf.Server().Backup.Count == 0 && !force && !confirmYES("Warning: pruning ALL backups") {
|
||||
log.Warn("Prune cancelled")
|
||||
return
|
||||
}
|
||||
@ -109,7 +110,7 @@ func runPrune(ctx context.Context) {
|
||||
start := time.Now()
|
||||
count, err := db.Prune(ctx)
|
||||
if err != nil {
|
||||
log.Fatal("Error pruning database", "backupPath", conf.Server.Backup.Path, err)
|
||||
log.Fatal("Error pruning database", "backupPath", conf.Server().Backup.Path, err)
|
||||
}
|
||||
|
||||
elapsed := time.Since(start)
|
||||
@ -124,9 +125,9 @@ func runRestore(ctx context.Context) {
|
||||
// `backup create` writes to. Without this, the value was treated as relative
|
||||
// to the working directory, where the file does not exist.
|
||||
if !filepath.IsAbs(restorePath) {
|
||||
backupPath, err := conf.Server.Backup.Path.Path()
|
||||
backupPath, err := conf.Server().Backup.Path.Path()
|
||||
if err != nil {
|
||||
log.Fatal("Backup directory not available", "backupPath", conf.Server.Backup.Path, err)
|
||||
log.Fatal("Backup directory not available", "backupPath", conf.Server().Backup.Path, err)
|
||||
return
|
||||
}
|
||||
restorePath = filepath.Join(backupPath, restorePath)
|
||||
|
||||
@ -3,6 +3,7 @@ package cmd
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -15,3 +16,5 @@ func TestCmd(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Cmd Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
@ -5,7 +5,6 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
@ -46,13 +45,10 @@ var _ = Describe("inspect", func() {
|
||||
})
|
||||
|
||||
Describe("loadLibraries", func() {
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
})
|
||||
|
||||
It("does not create a database when there is none", func() {
|
||||
dbFile := filepath.Join(GinkgoT().TempDir(), "navidrome.db")
|
||||
conf.Server.DbPath = dbFile + "?_journal_mode=WAL"
|
||||
conf.Update(func(c *conf.Options) { c.DbPath = dbFile + "?_journal_mode=WAL" })
|
||||
|
||||
Expect(loadLibraries(GinkgoT().Context())).To(BeNil())
|
||||
Expect(dbFile).ToNot(BeAnExistingFile())
|
||||
|
||||
@ -343,7 +343,7 @@ func runPluginList(ctx context.Context) {
|
||||
// requirePluginsEnabled gates DB/manager-backed commands; off-disk .ndp
|
||||
// inspection deliberately skips this so it works without a configured server.
|
||||
func requirePluginsEnabled(ctx context.Context) {
|
||||
if !conf.Server.Plugins.Enabled {
|
||||
if !conf.Server().Plugins.Enabled {
|
||||
log.Fatal(ctx, "Plugin system is disabled (set Plugins.Enabled to use this command)")
|
||||
}
|
||||
}
|
||||
|
||||
44
cmd/root.go
44
cmd/root.go
@ -97,7 +97,7 @@ func runNavidrome(parentCtx context.Context) error {
|
||||
g.Go(startArtworkWorker(ctx, artworkWorker))
|
||||
g.Go(scheduleArtworkHousekeeping(ctx, artworkWorker))
|
||||
g.Go(runInitialScan(ctx))
|
||||
if conf.Server.Scanner.Enabled {
|
||||
if conf.Server().Scanner.Enabled {
|
||||
g.Go(startScanWatcher(ctx))
|
||||
g.Go(schedulePeriodicScan(ctx))
|
||||
} else {
|
||||
@ -128,31 +128,31 @@ func startServer(ctx context.Context) func() error {
|
||||
a.MountRouter("Native API", consts.URLPathNativeAPI, CreateNativeAPIRouter(ctx))
|
||||
a.MountRouter("Subsonic API", consts.URLPathSubsonicAPI, CreateSubsonicAPIRouter(ctx))
|
||||
a.MountRouter("Public Endpoints", consts.URLPathPublic, CreatePublicRouter())
|
||||
if conf.Server.LastFM.Enabled {
|
||||
if conf.Server().LastFM.Enabled {
|
||||
a.MountRouter("LastFM Auth", consts.URLPathNativeAPI+"/lastfm", CreateLastFMRouter())
|
||||
}
|
||||
if conf.Server.ListenBrainz.Enabled {
|
||||
if conf.Server().ListenBrainz.Enabled {
|
||||
a.MountRouter("ListenBrainz Auth", consts.URLPathNativeAPI+"/listenbrainz", CreateListenBrainzRouter())
|
||||
}
|
||||
if conf.Server.Jellyfin.Enabled {
|
||||
if conf.Server().Jellyfin.Enabled {
|
||||
a.MountRouter("Jellyfin API", consts.URLPathJellyfinAPI, CreateJellyfinAPIRouter(ctx))
|
||||
}
|
||||
if conf.Server.DevAPIv1 {
|
||||
if conf.Server().DevAPIv1 {
|
||||
a.MountRouter("API v1", consts.URLPathAPIv1, CreateAPIv1Router(ctx))
|
||||
}
|
||||
if conf.Server.Prometheus.Enabled {
|
||||
if conf.Server().Prometheus.Enabled {
|
||||
p := CreatePrometheus()
|
||||
// blocking call because takes <100ms but useful if fails
|
||||
p.WriteInitialMetrics(ctx)
|
||||
a.MountRouter("Prometheus metrics", conf.Server.Prometheus.MetricsPath, p.GetHandler())
|
||||
a.MountRouter("Prometheus metrics", conf.Server().Prometheus.MetricsPath, p.GetHandler())
|
||||
}
|
||||
if conf.Server.DevEnableProfiler {
|
||||
if conf.Server().DevEnableProfiler {
|
||||
a.MountRouter("Profiling", "/debug", profilerHandler())
|
||||
}
|
||||
if strings.HasPrefix(conf.Server.UILoginBackgroundURL, "/") {
|
||||
a.MountRouter("Background images", conf.Server.UILoginBackgroundURL, backgrounds.NewHandler())
|
||||
if strings.HasPrefix(conf.Server().UILoginBackgroundURL, "/") {
|
||||
a.MountRouter("Background images", conf.Server().UILoginBackgroundURL, backgrounds.NewHandler())
|
||||
}
|
||||
return a.Run(ctx, conf.Server.Address, conf.Server.Port, conf.Server.TLSCert, conf.Server.TLSKey)
|
||||
return a.Run(ctx, conf.Server().Address, conf.Server().Port, conf.Server().TLSCert, conf.Server().TLSKey)
|
||||
}
|
||||
}
|
||||
|
||||
@ -160,14 +160,14 @@ func startServer(ctx context.Context) func() error {
|
||||
// name from the raw request path, so the BasePath has to come off first.
|
||||
func profilerHandler() http.Handler {
|
||||
// A trailing or root slash would make StripPrefix drop the leading slash chi needs.
|
||||
basePath := strings.TrimRight(conf.Server.BasePath, "/")
|
||||
basePath := strings.TrimRight(conf.Server().BasePath, "/")
|
||||
return http.StripPrefix(basePath, middleware.Profiler())
|
||||
}
|
||||
|
||||
// schedulePeriodicScan schedules a periodic scan of the music library, if configured.
|
||||
func schedulePeriodicScan(ctx context.Context) func() error {
|
||||
return func() error {
|
||||
schedule := conf.Server.Scanner.Schedule
|
||||
schedule := conf.Server().Scanner.Schedule
|
||||
if schedule == "" {
|
||||
log.Info(ctx, "Periodic scan is DISABLED")
|
||||
return nil
|
||||
@ -222,7 +222,7 @@ func runInitialScan(ctx context.Context) func() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
scanOnStartup := conf.Server.Scanner.Enabled && conf.Server.Scanner.ScanOnStartup
|
||||
scanOnStartup := conf.Server().Scanner.Enabled && conf.Server().Scanner.ScanOnStartup
|
||||
scanNeeded := scanOnStartup || inProgress || fullScanRequired == "1" || len(pidChangedLibs) > 0
|
||||
time.Sleep(2 * time.Second) // Wait 2 seconds before the initial scan
|
||||
if scanNeeded {
|
||||
@ -255,7 +255,7 @@ func runInitialScan(ctx context.Context) func() error {
|
||||
|
||||
func startScanWatcher(ctx context.Context) func() error {
|
||||
return func() error {
|
||||
if conf.Server.Scanner.WatcherWait == 0 {
|
||||
if conf.Server().Scanner.WatcherWait == 0 {
|
||||
log.Debug("Folder watcher is DISABLED")
|
||||
return nil
|
||||
}
|
||||
@ -270,7 +270,7 @@ func startScanWatcher(ctx context.Context) func() error {
|
||||
|
||||
func schedulePeriodicBackup(ctx context.Context) func() error {
|
||||
return func() error {
|
||||
schedule := conf.Server.Backup.Schedule
|
||||
schedule := conf.Server().Backup.Schedule
|
||||
if schedule == "" {
|
||||
log.Info(ctx, "Periodic backup is DISABLED")
|
||||
return nil
|
||||
@ -305,7 +305,7 @@ func schedulePeriodicBackup(ctx context.Context) func() error {
|
||||
|
||||
func scheduleDBAnalyzer(ctx context.Context) func() error {
|
||||
return func() error {
|
||||
if !conf.Server.EnableScheduledDBAnalyze {
|
||||
if !conf.Server().EnableScheduledDBAnalyze {
|
||||
log.Info(ctx, "Scheduled DB analysis is DISABLED")
|
||||
return nil
|
||||
}
|
||||
@ -339,13 +339,13 @@ func startScheduler(ctx context.Context) func() error {
|
||||
// startInsightsCollector starts the Navidrome Insight Collector, if configured.
|
||||
func startInsightsCollector(ctx context.Context) func() error {
|
||||
return func() error {
|
||||
if !conf.Server.EnableInsightsCollector {
|
||||
if !conf.Server().EnableInsightsCollector {
|
||||
log.Info(ctx, "Insight Collector is DISABLED")
|
||||
return nil
|
||||
}
|
||||
log.Info(ctx, "Starting Insight Collector")
|
||||
select {
|
||||
case <-time.After(conf.Server.DevInsightsInitialDelay):
|
||||
case <-time.After(conf.Server().DevInsightsInitialDelay):
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
}
|
||||
@ -358,7 +358,7 @@ func startInsightsCollector(ctx context.Context) func() error {
|
||||
// startJellyfinDiscovery never returns an error: a discovery failure must not stop the server.
|
||||
func startJellyfinDiscovery(ctx context.Context) func() error {
|
||||
return func() error {
|
||||
if !conf.Server.Jellyfin.Enabled || !conf.Server.Jellyfin.AutoDiscovery {
|
||||
if !conf.Server().Jellyfin.Enabled || !conf.Server().Jellyfin.AutoDiscovery {
|
||||
log.Debug("Jellyfin auto-discovery is DISABLED")
|
||||
return nil
|
||||
}
|
||||
@ -371,7 +371,7 @@ func startJellyfinDiscovery(ctx context.Context) func() error {
|
||||
// It is responsible for the Jukebox functionality
|
||||
func startPlaybackServer(ctx context.Context) func() error {
|
||||
return func() error {
|
||||
if !conf.Server.Jukebox.Enabled {
|
||||
if !conf.Server().Jukebox.Enabled {
|
||||
log.Debug("Jukebox is DISABLED")
|
||||
return nil
|
||||
}
|
||||
@ -439,7 +439,7 @@ func scheduleArtworkHousekeeping(ctx context.Context, worker *artwork.Worker) fu
|
||||
func startPluginManager(ctx context.Context) func() error {
|
||||
return func() error {
|
||||
manager := GetPluginManager(ctx)
|
||||
if !conf.Server.Plugins.Enabled {
|
||||
if !conf.Server().Plugins.Enabled {
|
||||
log.Debug("Plugin system is DISABLED")
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -22,17 +21,13 @@ var _ = Describe("profilerHandler", func() {
|
||||
// Mirrors how server.MountRouter mounts the handler.
|
||||
mount := func() http.Handler {
|
||||
router := chi.NewRouter()
|
||||
router.Mount(path.Join(conf.Server.BasePath, "/debug"), profilerHandler())
|
||||
router.Mount(path.Join(conf.Server().BasePath, "/debug"), profilerHandler())
|
||||
return router
|
||||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
})
|
||||
|
||||
DescribeTable("serves a named profile",
|
||||
func(basePath string) {
|
||||
conf.Server.BasePath = basePath
|
||||
conf.Update(func(c *conf.Options) { c.BasePath = basePath })
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
target := path.Join(basePath, "/debug/pprof/nd-profiler-test") + "?debug=1"
|
||||
@ -53,7 +48,6 @@ var _ = Describe("librariesWithChangedPID", func() {
|
||||
var libs *tests.MockLibraryRepo
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
libs = &tests.MockLibraryRepo{}
|
||||
ds = &tests.MockDataStore{MockedLibrary: libs}
|
||||
})
|
||||
|
||||
26
cmd/svc.go
26
cmd/svc.go
@ -81,13 +81,13 @@ var svcInstance = sync.OnceValue(func() service.Service {
|
||||
options["Restart"] = "on-failure"
|
||||
options["SuccessExitStatus"] = "SIGKILL"
|
||||
options["UserService"] = false
|
||||
options["LogDirectory"] = conf.Server.DataFolder.String()
|
||||
options["LogDirectory"] = conf.Server().DataFolder.String()
|
||||
options["SystemdScript"] = systemdScript
|
||||
if conf.Server.LogFile != "" {
|
||||
if conf.Server().LogFile != "" {
|
||||
options["LogOutput"] = false
|
||||
} else {
|
||||
options["LogOutput"] = true
|
||||
options["LogDirectory"] = conf.Server.DataFolder.String()
|
||||
options["LogDirectory"] = conf.Server().DataFolder.String()
|
||||
}
|
||||
svcConfig := &service.Config{
|
||||
UserName: installUser,
|
||||
@ -101,8 +101,8 @@ var svcInstance = sync.OnceValue(func() service.Service {
|
||||
Option: options,
|
||||
}
|
||||
arguments := []string{"service", "execute"}
|
||||
if conf.Server.ConfigFile != "" {
|
||||
arguments = append(arguments, "-c", conf.Server.ConfigFile)
|
||||
if conf.Server().ConfigFile != "" {
|
||||
arguments = append(arguments, "-c", conf.Server().ConfigFile)
|
||||
}
|
||||
svcConfig.Arguments = arguments
|
||||
|
||||
@ -135,19 +135,21 @@ func buildInstallCmd() *cobra.Command {
|
||||
var err error
|
||||
println("Installing service with:")
|
||||
println(" working directory: " + executablePath())
|
||||
println(" music folder: " + conf.Server.MusicFolder)
|
||||
println(" data folder: " + conf.Server.DataFolder.String())
|
||||
if conf.Server.LogFile != "" {
|
||||
println(" log file: " + conf.Server.LogFile)
|
||||
println(" music folder: " + conf.Server().MusicFolder)
|
||||
println(" data folder: " + conf.Server().DataFolder.String())
|
||||
if conf.Server().LogFile != "" {
|
||||
println(" log file: " + conf.Server().LogFile)
|
||||
} else {
|
||||
println(" logs folder: " + conf.Server.DataFolder.String())
|
||||
println(" logs folder: " + conf.Server().DataFolder.String())
|
||||
}
|
||||
if cfgFile != "" {
|
||||
conf.Server.ConfigFile, err = filepath.Abs(cfgFile)
|
||||
var absPath string
|
||||
absPath, err = filepath.Abs(cfgFile)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
println(" config file: " + conf.Server.ConfigFile)
|
||||
conf.Update(func(c *conf.Options) { c.ConfigFile = absPath })
|
||||
println(" config file: " + absPath)
|
||||
}
|
||||
err = svcInstance().Install()
|
||||
if err != nil {
|
||||
|
||||
@ -20,7 +20,7 @@ import (
|
||||
|
||||
// existingDBFile returns the database file (DbPath minus DSN params), and whether it exists.
|
||||
func existingDBFile() (string, bool) {
|
||||
path, _, _ := strings.Cut(conf.Server.DbPath, "?")
|
||||
path, _, _ := strings.Cut(conf.Server().DbPath, "?")
|
||||
_, err := os.Stat(path)
|
||||
return path, err == nil
|
||||
}
|
||||
|
||||
@ -1,8 +1,16 @@
|
||||
package configtest
|
||||
|
||||
import "github.com/navidrome/navidrome/conf"
|
||||
import (
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/onsi/ginkgo/v2"
|
||||
)
|
||||
|
||||
// TODO Remove this redirection and call SnapshotConfig directly from tests
|
||||
func SetupConfig() func() {
|
||||
return conf.SnapshotConfig()
|
||||
// RestoreAfterEachSpec restores the config after every spec. Call it at the top level of a suite.
|
||||
// Ordered specs are skipped so a BeforeAll can set config for its whole container.
|
||||
func RestoreAfterEachSpec() bool {
|
||||
return ginkgo.BeforeEach(func() {
|
||||
if !ginkgo.CurrentSpecReport().IsInOrderedContainer {
|
||||
ginkgo.DeferCleanup(conf.SnapshotConfig())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
16
conf/configtest/configtest_suite_test.go
Normal file
16
conf/configtest/configtest_suite_test.go
Normal file
@ -0,0 +1,16 @@
|
||||
package configtest_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestConfigtest(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Configtest Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
35
conf/configtest/configtest_test.go
Normal file
35
conf/configtest/configtest_test.go
Normal file
@ -0,0 +1,35 @@
|
||||
package configtest_test
|
||||
|
||||
import (
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("RestoreAfterEachSpec", func() {
|
||||
// Either spec can run first: the second one sees the first one's change if it leaks.
|
||||
It("starts with the original value (A)", func() {
|
||||
Expect(conf.Server().UIWelcomeMessage).To(BeEmpty())
|
||||
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "A" })
|
||||
})
|
||||
|
||||
It("starts with the original value (B)", func() {
|
||||
Expect(conf.Server().UIWelcomeMessage).To(BeEmpty())
|
||||
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "B" })
|
||||
})
|
||||
|
||||
Describe("in an Ordered container", Ordered, func() {
|
||||
BeforeAll(func() {
|
||||
DeferCleanup(conf.SnapshotConfig())
|
||||
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "ordered" })
|
||||
})
|
||||
|
||||
It("sees the BeforeAll change in the first spec", func() {
|
||||
Expect(conf.Server().UIWelcomeMessage).To(Equal("ordered"))
|
||||
})
|
||||
|
||||
It("still sees the BeforeAll change in later specs", func() {
|
||||
Expect(conf.Server().UIWelcomeMessage).To(Equal("ordered"))
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -3,7 +3,6 @@ package conf
|
||||
import (
|
||||
"cmp"
|
||||
"encoding"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/url"
|
||||
@ -30,7 +29,7 @@ import (
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type configOptions struct {
|
||||
type Options struct {
|
||||
ConfigFile string `conf:"-"`
|
||||
Address string
|
||||
Port int
|
||||
@ -161,6 +160,7 @@ type configOptions struct {
|
||||
DevExternalArtistFetchMultiplier float64
|
||||
DevPreserveUnicodeInExternalCalls bool
|
||||
DevEnableMediaFileProbe bool
|
||||
DevMatchEstimatedContentLength bool
|
||||
DevAPIv1 bool
|
||||
}
|
||||
|
||||
@ -320,30 +320,11 @@ var currentGOOS = func() string {
|
||||
|
||||
// TLSEnabled reports whether the server serves HTTPS. Both halves are required,
|
||||
// so callers cannot infer it from the certificate alone.
|
||||
func (c *configOptions) TLSEnabled() bool {
|
||||
func (c Options) TLSEnabled() bool {
|
||||
return c.TLSCert != "" && c.TLSKey != ""
|
||||
}
|
||||
|
||||
var (
|
||||
Server = &configOptions{}
|
||||
hooks []func()
|
||||
)
|
||||
|
||||
// SnapshotConfig returns a function that restores Server to its current state.
|
||||
// Uses JSON round-tripping so Dir fields get fresh sync.Once values.
|
||||
func SnapshotConfig() func() {
|
||||
snapshot, err := json.Marshal(Server)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("SnapshotConfig: marshal failed: %v", err))
|
||||
}
|
||||
return func() {
|
||||
var restored configOptions
|
||||
if err := json.Unmarshal(snapshot, &restored); err != nil {
|
||||
panic(fmt.Sprintf("SnapshotConfig: unmarshal failed: %v", err))
|
||||
}
|
||||
Server = &restored
|
||||
}
|
||||
}
|
||||
var hooks []func()
|
||||
|
||||
func LoadFromFile(confFile string) {
|
||||
viper.SetConfigFile(confFile)
|
||||
@ -372,7 +353,8 @@ func Load(noConfigDump bool) {
|
||||
}
|
||||
}
|
||||
|
||||
err := viper.Unmarshal(&Server, viper.DecodeHook(
|
||||
s := clone(current.Load())
|
||||
err := viper.Unmarshal(s, viper.DecodeHook(
|
||||
mapstructure.ComposeDecodeHookFunc(
|
||||
mapstructure.TextUnmarshallerHookFunc(),
|
||||
mapstructure.StringToTimeDurationHookFunc(),
|
||||
@ -384,35 +366,35 @@ func Load(noConfigDump bool) {
|
||||
}
|
||||
|
||||
// Validate non-root user early, before any filesystem operations
|
||||
if err := validateEnforceNonRootUser(); err != nil {
|
||||
if err := s.validateEnforceNonRootUser(); err != nil {
|
||||
logFatal(err)
|
||||
}
|
||||
|
||||
if Server.CacheFolder.String() == "" {
|
||||
Server.CacheFolder = NewDir(filepath.Join(Server.DataFolder.String(), "cache"))
|
||||
if s.CacheFolder.String() == "" {
|
||||
s.CacheFolder = NewDir(filepath.Join(s.DataFolder.String(), "cache"))
|
||||
}
|
||||
|
||||
if Server.Plugins.Enabled {
|
||||
if Server.Plugins.Folder.String() == "" {
|
||||
Server.Plugins.Folder = NewDirWithPerm(filepath.Join(Server.DataFolder.String(), "plugins"), 0700)
|
||||
if s.Plugins.Enabled {
|
||||
if s.Plugins.Folder.String() == "" {
|
||||
s.Plugins.Folder = NewDirWithPerm(filepath.Join(s.DataFolder.String(), "plugins"), 0700)
|
||||
} else {
|
||||
Server.Plugins.Folder = NewDirWithPerm(Server.Plugins.Folder.String(), 0700)
|
||||
s.Plugins.Folder = NewDirWithPerm(s.Plugins.Folder.String(), 0700)
|
||||
}
|
||||
}
|
||||
|
||||
Server.ConfigFile = viper.GetViper().ConfigFileUsed()
|
||||
if Server.DbPath == "" {
|
||||
Server.DbPath = filepath.Join(Server.DataFolder.String(), consts.DefaultDbPath)
|
||||
s.ConfigFile = viper.GetViper().ConfigFileUsed()
|
||||
if s.DbPath == "" {
|
||||
s.DbPath = filepath.Join(s.DataFolder.String(), consts.DefaultDbPath)
|
||||
}
|
||||
|
||||
out := os.Stderr
|
||||
if Server.LogFile != "" {
|
||||
if mkErr := os.MkdirAll(filepath.Dir(Server.LogFile), os.ModePerm); mkErr != nil {
|
||||
if s.LogFile != "" {
|
||||
if mkErr := os.MkdirAll(filepath.Dir(s.LogFile), os.ModePerm); mkErr != nil {
|
||||
logFatal(fmt.Sprintf("Error creating log file directory: %s", mkErr.Error()))
|
||||
}
|
||||
out, err = os.OpenFile(Server.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
|
||||
out, err = os.OpenFile(s.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
logFatal(fmt.Sprintf("Error opening log file %s: %s", Server.LogFile, err.Error()))
|
||||
logFatal(fmt.Sprintf("Error opening log file %s: %s", s.LogFile, err.Error()))
|
||||
}
|
||||
log.SetOutput(out)
|
||||
} else if os.Getenv("ND_SYSTEMD_PRIORITY_LOGGING") != "" && os.Getenv("JOURNAL_STREAM") != "" {
|
||||
@ -423,24 +405,24 @@ func Load(noConfigDump bool) {
|
||||
log.EnableJournalFormat()
|
||||
}
|
||||
|
||||
log.SetLevelString(Server.LogLevel)
|
||||
log.SetLogLevels(Server.DevLogLevels)
|
||||
log.SetLogSourceLine(Server.DevLogSourceLine)
|
||||
log.SetRedacting(Server.EnableLogRedacting)
|
||||
log.SetLevelString(s.LogLevel)
|
||||
log.SetLogLevels(s.DevLogLevels)
|
||||
log.SetLogSourceLine(s.DevLogSourceLine)
|
||||
log.SetRedacting(s.EnableLogRedacting)
|
||||
|
||||
durationNonNegativeOrDefault(&Server.SessionTimeout, consts.DefaultSessionTimeout)
|
||||
durationNonNegativeOrDefault(&Server.SmartPlaylistRefreshDelay, consts.DefaultSmartRefresh)
|
||||
durationNonNegativeOrDefault(&Server.DefaultShareExpiration, consts.DefaultShareExpiration)
|
||||
durationNonNegativeOrDefault(&Server.UIPlaybackReportInterval, consts.DefaultUIPlaybackReportInterval)
|
||||
durationNonNegativeOrDefault(&Server.AuthWindowLength, consts.DefaultAuthWindowLength)
|
||||
durationNonNegativeOrDefault(&Server.Scanner.WatcherWait, consts.DefaultWatcherWait)
|
||||
durationNonNegativeOrDefault(&s.SessionTimeout, consts.DefaultSessionTimeout)
|
||||
durationNonNegativeOrDefault(&s.SmartPlaylistRefreshDelay, consts.DefaultSmartRefresh)
|
||||
durationNonNegativeOrDefault(&s.DefaultShareExpiration, consts.DefaultShareExpiration)
|
||||
durationNonNegativeOrDefault(&s.UIPlaybackReportInterval, consts.DefaultUIPlaybackReportInterval)
|
||||
durationNonNegativeOrDefault(&s.AuthWindowLength, consts.DefaultAuthWindowLength)
|
||||
durationNonNegativeOrDefault(&s.Scanner.WatcherWait, consts.DefaultWatcherWait)
|
||||
|
||||
durationNonNegativeOrDefault(&Server.DevActivityPanelUpdateRate, consts.DefaultActivityPanelUpdateRate)
|
||||
durationNonNegativeOrDefault(&Server.DevArtworkThrottleBacklogTimeout, consts.RequestThrottleBacklogTimeout)
|
||||
durationNonNegativeOrDefault(&Server.DevArtistInfoTimeToLive, consts.ArtistInfoTimeToLive)
|
||||
durationNonNegativeOrDefault(&Server.DevAlbumInfoTimeToLive, consts.AlbumInfoTimeToLive)
|
||||
durationNonNegativeOrDefault(&Server.DevInsightsInitialDelay, consts.InsightsInitialDelay)
|
||||
durationNonNegativeOrDefault(&Server.DevPluginCompilationTimeout, consts.DefaultPluginCompilationTimeout)
|
||||
durationNonNegativeOrDefault(&s.DevActivityPanelUpdateRate, consts.DefaultActivityPanelUpdateRate)
|
||||
durationNonNegativeOrDefault(&s.DevArtworkThrottleBacklogTimeout, consts.RequestThrottleBacklogTimeout)
|
||||
durationNonNegativeOrDefault(&s.DevArtistInfoTimeToLive, consts.ArtistInfoTimeToLive)
|
||||
durationNonNegativeOrDefault(&s.DevAlbumInfoTimeToLive, consts.AlbumInfoTimeToLive)
|
||||
durationNonNegativeOrDefault(&s.DevInsightsInitialDelay, consts.InsightsInitialDelay)
|
||||
durationNonNegativeOrDefault(&s.DevPluginCompilationTimeout, consts.DefaultPluginCompilationTimeout)
|
||||
|
||||
// Log deprecated, removed and unknown options
|
||||
for _, o := range deprecatedOptions {
|
||||
@ -450,35 +432,35 @@ func Load(noConfigDump bool) {
|
||||
logUnknownOptions()
|
||||
|
||||
err = run.Sequentially(
|
||||
validateScanSchedule,
|
||||
validateBackupSchedule,
|
||||
validatePlaylistsPath,
|
||||
validatePurgeMissingOption,
|
||||
validateByteSize("MaxImageUploadSize", Server.MaxImageUploadSize),
|
||||
validateByteSize("MaxImageSize", Server.MaxImageSize),
|
||||
validateURL("ExtAuth.LogoutURL", Server.ExtAuth.LogoutURL),
|
||||
s.validateScanSchedule,
|
||||
s.validateBackupSchedule,
|
||||
s.validatePlaylistsPath,
|
||||
s.validatePurgeMissingOption,
|
||||
validateByteSize("MaxImageUploadSize", s.MaxImageUploadSize),
|
||||
validateByteSize("MaxImageSize", s.MaxImageSize),
|
||||
validateURL("ExtAuth.LogoutURL", s.ExtAuth.LogoutURL),
|
||||
)
|
||||
if err != nil {
|
||||
logFatal(err)
|
||||
}
|
||||
|
||||
Server.Search.Backend = normalizeSearchBackend(Server.Search.Backend)
|
||||
s.Search.Backend = normalizeSearchBackend(s.Search.Backend)
|
||||
|
||||
if Server.BaseURL != "" {
|
||||
u, err := url.Parse(Server.BaseURL)
|
||||
if s.BaseURL != "" {
|
||||
u, err := url.Parse(s.BaseURL)
|
||||
if err != nil {
|
||||
logFatal("Invalid BaseURL:", err)
|
||||
}
|
||||
Server.BasePath = u.Path
|
||||
s.BasePath = u.Path
|
||||
u.Path = ""
|
||||
u.RawQuery = ""
|
||||
Server.BaseHost = u.Host
|
||||
Server.BaseScheme = u.Scheme
|
||||
s.BaseHost = u.Host
|
||||
s.BaseScheme = u.Scheme
|
||||
}
|
||||
|
||||
// Log configuration source
|
||||
if Server.ConfigFile != "" {
|
||||
log.Info("Loaded configuration", "file", Server.ConfigFile)
|
||||
if s.ConfigFile != "" {
|
||||
log.Info("Loaded configuration", "file", s.ConfigFile)
|
||||
} else if hasNDEnvVars() {
|
||||
log.Info("No configuration file found. Loaded configuration only from environment variables")
|
||||
} else {
|
||||
@ -487,47 +469,49 @@ func Load(noConfigDump bool) {
|
||||
|
||||
// Print current configuration if log level is Debug
|
||||
if log.IsGreaterOrEqualTo(log.LevelDebug) && !noConfigDump {
|
||||
prettyConf := pretty.Sprintf("Configuration: %# v", Server)
|
||||
if Server.EnableLogRedacting {
|
||||
prettyConf := pretty.Sprintf("Configuration: %# v", s)
|
||||
if s.EnableLogRedacting {
|
||||
prettyConf = log.Redact(prettyConf)
|
||||
}
|
||||
_, _ = fmt.Fprintln(out, prettyConf)
|
||||
}
|
||||
|
||||
if !Server.EnableExternalServices {
|
||||
disableExternalServices()
|
||||
if !s.EnableExternalServices {
|
||||
s.disableExternalServices()
|
||||
}
|
||||
|
||||
// Make sure we don't have empty PIDs
|
||||
Server.PID.Album = cmp.Or(Server.PID.Album, consts.DefaultAlbumPID)
|
||||
Server.PID.Track = cmp.Or(Server.PID.Track, consts.DefaultTrackPID)
|
||||
s.PID.Album = cmp.Or(s.PID.Album, consts.DefaultAlbumPID)
|
||||
s.PID.Track = cmp.Or(s.PID.Track, consts.DefaultTrackPID)
|
||||
|
||||
// Parse LastFM.Language into Languages slice (comma-separated, with fallback to DefaultInfoLanguage)
|
||||
Server.LastFM.Languages = parseLanguages(Server.LastFM.Language)
|
||||
s.LastFM.Languages = parseLanguages(s.LastFM.Language)
|
||||
|
||||
// Parse Deezer.Language into Languages slice (comma-separated, with fallback to DefaultInfoLanguage)
|
||||
Server.Deezer.Languages = parseLanguages(Server.Deezer.Language)
|
||||
s.Deezer.Languages = parseLanguages(s.Deezer.Language)
|
||||
|
||||
// Validate other options
|
||||
if Server.UICoverArtSize < 200 || Server.UICoverArtSize > 1200 {
|
||||
newValue := max(200, min(1200, Server.UICoverArtSize))
|
||||
log.Warn("UICoverArtSize must be between 200 and 1200, clamping", "value", Server.UICoverArtSize, "newValue", newValue)
|
||||
Server.UICoverArtSize = newValue
|
||||
if s.UICoverArtSize < 200 || s.UICoverArtSize > 1200 {
|
||||
newValue := max(200, min(1200, s.UICoverArtSize))
|
||||
log.Warn("UICoverArtSize must be between 200 and 1200, clamping", "value", s.UICoverArtSize, "newValue", newValue)
|
||||
s.UICoverArtSize = newValue
|
||||
}
|
||||
|
||||
if Server.Scanner.Extractor != consts.DefaultScannerExtractor {
|
||||
log.Warn("Invalid Scanner.Extractor, using default", "value", Server.Scanner.Extractor, "default", consts.DefaultScannerExtractor)
|
||||
Server.Scanner.Extractor = consts.DefaultScannerExtractor
|
||||
if s.Scanner.Extractor != consts.DefaultScannerExtractor {
|
||||
log.Warn("Invalid Scanner.Extractor, using default", "value", s.Scanner.Extractor, "default", consts.DefaultScannerExtractor)
|
||||
s.Scanner.Extractor = consts.DefaultScannerExtractor
|
||||
}
|
||||
|
||||
// Floor MaxImageSize at MaxImageUploadSize so accepted uploads can always be read back.
|
||||
imgSize, _ := humanize.ParseBytes(Server.MaxImageSize)
|
||||
uploadSize, _ := humanize.ParseBytes(Server.MaxImageUploadSize)
|
||||
imgSize, _ := humanize.ParseBytes(s.MaxImageSize)
|
||||
uploadSize, _ := humanize.ParseBytes(s.MaxImageUploadSize)
|
||||
if imgSize < uploadSize {
|
||||
log.Warn("MaxImageSize must be at least MaxImageUploadSize, raising", "value", Server.MaxImageSize, "newValue", Server.MaxImageUploadSize)
|
||||
Server.MaxImageSize = Server.MaxImageUploadSize
|
||||
log.Warn("MaxImageSize must be at least MaxImageUploadSize, raising", "value", s.MaxImageSize, "newValue", s.MaxImageUploadSize)
|
||||
s.MaxImageSize = s.MaxImageUploadSize
|
||||
}
|
||||
|
||||
current.Store(s)
|
||||
|
||||
// Call init hooks
|
||||
for _, hook := range hooks {
|
||||
hook()
|
||||
@ -768,7 +752,7 @@ var configKeys = sync.OnceValues(func() (map[string]string, []string) {
|
||||
}
|
||||
}
|
||||
}
|
||||
collect(reflect.TypeFor[configOptions](), "")
|
||||
collect(reflect.TypeFor[Options](), "")
|
||||
|
||||
for _, o := range deprecatedOptions {
|
||||
keys[strings.ToLower(o.name)] = o.name
|
||||
@ -803,21 +787,21 @@ func parseIniFileConfiguration() {
|
||||
}
|
||||
}
|
||||
|
||||
func disableExternalServices() {
|
||||
func (s *Options) disableExternalServices() {
|
||||
log.Info("All external integrations are DISABLED!")
|
||||
Server.EnableInsightsCollector = false
|
||||
Server.EnableM3UExternalAlbumArt = false
|
||||
Server.LastFM.Enabled = false
|
||||
Server.Deezer.Enabled = false
|
||||
Server.ListenBrainz.Enabled = false
|
||||
Server.Agents = ""
|
||||
if Server.UILoginBackgroundURL == consts.DefaultUILoginBackgroundURL {
|
||||
Server.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURLOffline
|
||||
s.EnableInsightsCollector = false
|
||||
s.EnableM3UExternalAlbumArt = false
|
||||
s.LastFM.Enabled = false
|
||||
s.Deezer.Enabled = false
|
||||
s.ListenBrainz.Enabled = false
|
||||
s.Agents = ""
|
||||
if s.UILoginBackgroundURL == consts.DefaultUILoginBackgroundURL {
|
||||
s.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURLOffline
|
||||
}
|
||||
}
|
||||
|
||||
func validatePlaylistsPath() error {
|
||||
for path := range strings.SplitSeq(Server.PlaylistsPath, string(filepath.ListSeparator)) {
|
||||
func (s *Options) validatePlaylistsPath() error {
|
||||
for path := range strings.SplitSeq(s.PlaylistsPath, string(filepath.ListSeparator)) {
|
||||
_, err := doublestar.Match(path, "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid PlaylistsPath %q: %w", path, err)
|
||||
@ -842,12 +826,12 @@ func parseLanguages(lang string) []string {
|
||||
return languages
|
||||
}
|
||||
|
||||
func validatePurgeMissingOption() error {
|
||||
func (s *Options) validatePurgeMissingOption() error {
|
||||
allowedValues := []string{consts.PurgeMissingNever, consts.PurgeMissingAlways, consts.PurgeMissingFull}
|
||||
valid := slices.Contains(allowedValues, Server.Scanner.PurgeMissing)
|
||||
valid := slices.Contains(allowedValues, s.Scanner.PurgeMissing)
|
||||
if !valid {
|
||||
err := fmt.Errorf("invalid Scanner.PurgeMissing value: '%s'. Must be one of: %v", Server.Scanner.PurgeMissing, allowedValues)
|
||||
Server.Scanner.PurgeMissing = consts.PurgeMissingNever
|
||||
err := fmt.Errorf("invalid Scanner.PurgeMissing value: '%s'. Must be one of: %v", s.Scanner.PurgeMissing, allowedValues)
|
||||
s.Scanner.PurgeMissing = consts.PurgeMissingNever
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
@ -869,8 +853,8 @@ func validateByteSize(name, value string) func() error {
|
||||
}
|
||||
}
|
||||
|
||||
func validateEnforceNonRootUser() error {
|
||||
if !Server.EnforceNonRootUser || currentGOOS() == "windows" {
|
||||
func (s *Options) validateEnforceNonRootUser() error {
|
||||
if !s.EnforceNonRootUser || currentGOOS() == "windows" {
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -881,23 +865,23 @@ func validateEnforceNonRootUser() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateScanSchedule() error {
|
||||
if Server.Scanner.Schedule == "0" || Server.Scanner.Schedule == "" {
|
||||
Server.Scanner.Schedule = ""
|
||||
func (s *Options) validateScanSchedule() error {
|
||||
if s.Scanner.Schedule == "0" || s.Scanner.Schedule == "" {
|
||||
s.Scanner.Schedule = ""
|
||||
return nil
|
||||
}
|
||||
var err error
|
||||
Server.Scanner.Schedule, err = validateSchedule(Server.Scanner.Schedule, "Scanner.Schedule")
|
||||
s.Scanner.Schedule, err = validateSchedule(s.Scanner.Schedule, "Scanner.Schedule")
|
||||
return err
|
||||
}
|
||||
|
||||
func validateBackupSchedule() error {
|
||||
if Server.Backup.Path.String() == "" || Server.Backup.Schedule == "" || Server.Backup.Count == 0 {
|
||||
Server.Backup.Schedule = ""
|
||||
func (s *Options) validateBackupSchedule() error {
|
||||
if s.Backup.Path.String() == "" || s.Backup.Schedule == "" || s.Backup.Count == 0 {
|
||||
s.Backup.Schedule = ""
|
||||
return nil
|
||||
}
|
||||
var err error
|
||||
Server.Backup.Schedule, err = validateSchedule(Server.Backup.Schedule, "Backup.Schedule")
|
||||
s.Backup.Schedule, err = validateSchedule(s.Backup.Schedule, "Backup.Schedule")
|
||||
return err
|
||||
}
|
||||
|
||||
@ -1152,6 +1136,7 @@ func setViperDefaults() {
|
||||
viper.SetDefault("devexternalartistfetchmultiplier", 1.5)
|
||||
viper.SetDefault("devpreserveunicodeinexternalcalls", false)
|
||||
viper.SetDefault("devenablemediafileprobe", true)
|
||||
viper.SetDefault("devmatchestimatedcontentlength", true)
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
||||
@ -23,6 +23,8 @@ func TestConfiguration(t *testing.T) {
|
||||
RunSpecs(t, "Configuration Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
var _ = Describe("Configuration", func() {
|
||||
BeforeEach(func() {
|
||||
// Reset viper configuration
|
||||
@ -67,13 +69,13 @@ var _ = Describe("Configuration", func() {
|
||||
Describe("scheduled DB analysis", func() {
|
||||
It("is enabled by default", func() {
|
||||
conf.Load(true)
|
||||
Expect(conf.Server.EnableScheduledDBAnalyze).To(BeTrue())
|
||||
Expect(conf.Server().EnableScheduledDBAnalyze).To(BeTrue())
|
||||
})
|
||||
|
||||
It("can be disabled", func() {
|
||||
viper.Set("enablescheduleddbanalyze", false)
|
||||
conf.Load(true)
|
||||
Expect(conf.Server.EnableScheduledDBAnalyze).To(BeFalse())
|
||||
Expect(conf.Server().EnableScheduledDBAnalyze).To(BeFalse())
|
||||
})
|
||||
})
|
||||
|
||||
@ -158,9 +160,9 @@ var _ = Describe("Configuration", func() {
|
||||
conf.InitConfig(filename, false)
|
||||
conf.Load(true)
|
||||
|
||||
Expect(conf.Server.Address).To(Equal("127.0.0.1"))
|
||||
Expect(conf.Server.Port).To(Equal(4531))
|
||||
Expect(conf.Server.Scanner.Schedule).To(Equal("@every 1h"))
|
||||
Expect(conf.Server().Address).To(Equal("127.0.0.1"))
|
||||
Expect(conf.Server().Port).To(Equal(4531))
|
||||
Expect(conf.Server().Scanner.Schedule).To(Equal("@every 1h"))
|
||||
})
|
||||
|
||||
It("exits with fatal error when both ND_ and canonical key exist", func() {
|
||||
@ -180,7 +182,7 @@ var _ = Describe("Configuration", func() {
|
||||
conf.Load(true)
|
||||
|
||||
// Verify normal config loading still works
|
||||
Expect(conf.Server.MusicFolder).To(Equal("/toml/music"))
|
||||
Expect(conf.Server().MusicFolder).To(Equal("/toml/music"))
|
||||
})
|
||||
})
|
||||
|
||||
@ -254,14 +256,14 @@ var _ = Describe("Configuration", func() {
|
||||
conf.Load(true)
|
||||
|
||||
Expect(conf.UnknownConfigKeys()).To(ConsistOf("ND_TOTALLY_BOGUS_OPTION"))
|
||||
Expect(conf.Server.Scanner.Schedule).To(Equal("@every 1h"))
|
||||
Expect(conf.Server().Scanner.Schedule).To(Equal("@every 1h"))
|
||||
})
|
||||
|
||||
It("migrates every deprecated option that has a replacement", func() {
|
||||
conf.InitConfig(filepath.Join("testdata", "cfg_deprecated_search.toml"), false)
|
||||
conf.Load(true)
|
||||
|
||||
Expect(conf.Server.Search.FullString).To(BeTrue())
|
||||
Expect(conf.Server().Search.FullString).To(BeTrue())
|
||||
Expect(conf.UnknownConfigKeys()).To(BeEmpty())
|
||||
})
|
||||
|
||||
@ -296,7 +298,7 @@ var _ = Describe("Configuration", func() {
|
||||
})
|
||||
|
||||
It("keeps an explicit replacement over the deprecated value", func() {
|
||||
Expect(conf.Server.Search.FullString).To(BeFalse())
|
||||
Expect(conf.Server().Search.FullString).To(BeFalse())
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -392,13 +394,13 @@ var _ = Describe("Configuration", func() {
|
||||
viper.SetDefault("maximagesize", "5MB")
|
||||
viper.SetDefault("maximageuploadsize", "50MB")
|
||||
conf.Load(true)
|
||||
Expect(conf.Server.MaxImageSize).To(Equal("50MB"))
|
||||
Expect(conf.Server().MaxImageSize).To(Equal("50MB"))
|
||||
})
|
||||
|
||||
It("keeps a larger MaxImageSize unchanged", func() {
|
||||
viper.SetDefault("maximagesize", "30MB")
|
||||
conf.Load(true)
|
||||
Expect(conf.Server.MaxImageSize).To(Equal("30MB"))
|
||||
Expect(conf.Server().MaxImageSize).To(Equal("30MB"))
|
||||
})
|
||||
})
|
||||
|
||||
@ -414,12 +416,12 @@ var _ = Describe("Configuration", func() {
|
||||
It("falls back to taglib for an unknown extractor", func() {
|
||||
viper.SetDefault("scanner.extractor", "ffmpeg")
|
||||
conf.Load(true)
|
||||
Expect(conf.Server.Scanner.Extractor).To(Equal("taglib"))
|
||||
Expect(conf.Server().Scanner.Extractor).To(Equal("taglib"))
|
||||
})
|
||||
|
||||
It("keeps taglib", func() {
|
||||
conf.Load(true)
|
||||
Expect(conf.Server.Scanner.Extractor).To(Equal("taglib"))
|
||||
Expect(conf.Server().Scanner.Extractor).To(Equal("taglib"))
|
||||
})
|
||||
})
|
||||
|
||||
@ -427,7 +429,7 @@ var _ = Describe("Configuration", func() {
|
||||
It("defaults to false", func() {
|
||||
conf.Load(true)
|
||||
|
||||
Expect(conf.Server.EnforceNonRootUser).To(BeFalse())
|
||||
Expect(conf.Server().EnforceNonRootUser).To(BeFalse())
|
||||
})
|
||||
|
||||
It("allows startup for non-root users when enabled", func() {
|
||||
@ -436,7 +438,7 @@ var _ = Describe("Configuration", func() {
|
||||
|
||||
conf.Load(true)
|
||||
|
||||
Expect(conf.Server.EnforceNonRootUser).To(BeTrue())
|
||||
Expect(conf.Server().EnforceNonRootUser).To(BeTrue())
|
||||
})
|
||||
|
||||
It("exits when enabled and running as root without having created a data folder", func() {
|
||||
@ -462,7 +464,7 @@ var _ = Describe("Configuration", func() {
|
||||
|
||||
conf.Load(true)
|
||||
|
||||
Expect(conf.Server.EnforceNonRootUser).To(BeTrue())
|
||||
Expect(conf.Server().EnforceNonRootUser).To(BeTrue())
|
||||
})
|
||||
})
|
||||
|
||||
@ -476,16 +478,16 @@ var _ = Describe("Configuration", func() {
|
||||
conf.Load(true)
|
||||
|
||||
// Execute the format-specific assertions
|
||||
Expect(conf.Server.MusicFolder).To(Equal(fmt.Sprintf("/%s/music", format)))
|
||||
Expect(conf.Server.UIWelcomeMessage).To(Equal("Welcome " + format))
|
||||
Expect(conf.Server.Tags["custom"].Aliases).To(Equal([]string{format, "test"}))
|
||||
Expect(conf.Server.Tags["artist"].Split).To(Equal([]string{";"}))
|
||||
Expect(conf.Server().MusicFolder).To(Equal(fmt.Sprintf("/%s/music", format)))
|
||||
Expect(conf.Server().UIWelcomeMessage).To(Equal("Welcome " + format))
|
||||
Expect(conf.Server().Tags["custom"].Aliases).To(Equal([]string{format, "test"}))
|
||||
Expect(conf.Server().Tags["artist"].Split).To(Equal([]string{";"}))
|
||||
|
||||
// Check deprecated option mapping
|
||||
Expect(conf.Server.ExtAuth.UserHeader).To(Equal("X-Auth-User"))
|
||||
Expect(conf.Server().ExtAuth.UserHeader).To(Equal("X-Auth-User"))
|
||||
|
||||
// The config file used should be the one we created
|
||||
Expect(conf.Server.ConfigFile).To(Equal(filename))
|
||||
Expect(conf.Server().ConfigFile).To(Equal(filename))
|
||||
},
|
||||
Entry("TOML format", "toml"),
|
||||
Entry("YAML format", "yaml"),
|
||||
@ -498,7 +500,7 @@ var _ = Describe("Configuration", func() {
|
||||
conf.InitConfig(filename, false)
|
||||
conf.Load(true)
|
||||
|
||||
server := conf.Server
|
||||
server := conf.Server()
|
||||
Expect(server.SessionTimeout).To(Equal(consts.DefaultSessionTimeout))
|
||||
Expect(server.SmartPlaylistRefreshDelay).To(Equal(consts.DefaultSmartRefresh))
|
||||
Expect(server.DefaultShareExpiration).To(Equal(consts.DefaultShareExpiration))
|
||||
@ -520,7 +522,7 @@ var _ = Describe("Configuration", func() {
|
||||
|
||||
configured := 1 * time.Second
|
||||
|
||||
server := conf.Server
|
||||
server := conf.Server()
|
||||
Expect(server.SessionTimeout).To(Equal(configured))
|
||||
Expect(server.SmartPlaylistRefreshDelay).To(Equal(configured))
|
||||
Expect(server.DefaultShareExpiration).To(Equal(configured))
|
||||
@ -538,27 +540,26 @@ var _ = Describe("Configuration", func() {
|
||||
})
|
||||
|
||||
var _ = Describe("TLSEnabled", func() {
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
})
|
||||
|
||||
It("is false when neither the certificate nor the key is set", func() {
|
||||
Expect(conf.Server.TLSEnabled()).To(BeFalse())
|
||||
Expect(conf.Server().TLSEnabled()).To(BeFalse())
|
||||
})
|
||||
|
||||
It("is true when both the certificate and the key are set", func() {
|
||||
conf.Server.TLSCert = "cert.pem"
|
||||
conf.Server.TLSKey = "key.pem"
|
||||
Expect(conf.Server.TLSEnabled()).To(BeTrue())
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.TLSCert = "cert.pem"
|
||||
c.TLSKey = "key.pem"
|
||||
})
|
||||
Expect(conf.Server().TLSEnabled()).To(BeTrue())
|
||||
})
|
||||
|
||||
It("is false when only the certificate is set", func() {
|
||||
conf.Server.TLSCert = "cert.pem"
|
||||
Expect(conf.Server.TLSEnabled()).To(BeFalse())
|
||||
conf.Update(func(c *conf.Options) { c.TLSCert = "cert.pem" })
|
||||
Expect(conf.Server().TLSEnabled()).To(BeFalse())
|
||||
})
|
||||
|
||||
It("is false when only the key is set", func() {
|
||||
conf.Server.TLSKey = "key.pem"
|
||||
Expect(conf.Server.TLSEnabled()).To(BeFalse())
|
||||
conf.Update(func(c *conf.Options) { c.TLSKey = "key.pem" })
|
||||
Expect(conf.Server().TLSEnabled()).To(BeFalse())
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
package conf
|
||||
|
||||
func ResetConf() {
|
||||
Server = &configOptions{}
|
||||
current.Store(&Options{})
|
||||
}
|
||||
|
||||
var SetViperDefaults = setViperDefaults
|
||||
|
||||
87
conf/server.go
Normal file
87
conf/server.go
Normal file
@ -0,0 +1,87 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
var current atomic.Pointer[Options]
|
||||
|
||||
func init() {
|
||||
current.Store(&Options{})
|
||||
}
|
||||
|
||||
// Server returns a copy of the current configuration. A published Options is never changed in place,
|
||||
// so readers need no locking. Use Update to change it.
|
||||
func Server() Options {
|
||||
return *current.Load()
|
||||
}
|
||||
|
||||
// Update applies fn to a deep copy of the current configuration and publishes the result.
|
||||
// fn may run more than once if another change lands first, so it must only set fields.
|
||||
func Update(fn func(*Options)) {
|
||||
for {
|
||||
old := current.Load()
|
||||
next := clone(old)
|
||||
fn(next)
|
||||
if current.CompareAndSwap(old, next) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SnapshotConfig returns a function that restores the configuration to its current state.
|
||||
func SnapshotConfig() func() {
|
||||
snapshot := current.Load()
|
||||
return func() { current.Store(snapshot) }
|
||||
}
|
||||
|
||||
func clone(o *Options) *Options {
|
||||
var c Options
|
||||
deepCopy(reflect.ValueOf(&c).Elem(), reflect.ValueOf(o).Elem())
|
||||
return &c
|
||||
}
|
||||
|
||||
func deepCopy(dst, src reflect.Value) {
|
||||
switch src.Kind() {
|
||||
case reflect.Struct:
|
||||
dst.Set(src)
|
||||
for i := range src.NumField() {
|
||||
if dst.Field(i).CanSet() {
|
||||
deepCopy(dst.Field(i), src.Field(i))
|
||||
}
|
||||
}
|
||||
case reflect.Map:
|
||||
if src.IsNil() {
|
||||
dst.Set(src)
|
||||
return
|
||||
}
|
||||
m := reflect.MakeMapWithSize(src.Type(), src.Len())
|
||||
for k, v := range src.Seq2() {
|
||||
nv := reflect.New(v.Type()).Elem()
|
||||
deepCopy(nv, v)
|
||||
m.SetMapIndex(k, nv)
|
||||
}
|
||||
dst.Set(m)
|
||||
case reflect.Slice:
|
||||
if src.IsNil() {
|
||||
dst.Set(src)
|
||||
return
|
||||
}
|
||||
s := reflect.MakeSlice(src.Type(), src.Len(), src.Len())
|
||||
for i := range src.Len() {
|
||||
deepCopy(s.Index(i), src.Index(i))
|
||||
}
|
||||
dst.Set(s)
|
||||
case reflect.Pointer:
|
||||
if src.IsNil() {
|
||||
dst.Set(src)
|
||||
return
|
||||
}
|
||||
p := reflect.New(src.Type().Elem())
|
||||
deepCopy(p.Elem(), src.Elem())
|
||||
dst.Set(p)
|
||||
default:
|
||||
dst.Set(src)
|
||||
}
|
||||
}
|
||||
89
conf/server_test.go
Normal file
89
conf/server_test.go
Normal file
@ -0,0 +1,89 @@
|
||||
package conf_test
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Server state", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.Tags = map[string]conf.TagConf{"genre": {Aliases: []string{"genre", "style"}}}
|
||||
c.DevLogLevels = map[string]string{"scanner": "info"}
|
||||
c.Scanner.ArtistSplitExceptions = []string{"AC/DC"}
|
||||
})
|
||||
})
|
||||
|
||||
It("keeps a copy taken from Server unchanged by later updates", func() {
|
||||
before := conf.Server()
|
||||
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.Tags["genre"].Aliases[0] = "changed"
|
||||
c.DevLogLevels["scanner"] = "debug"
|
||||
c.Scanner.ArtistSplitExceptions[0] = "changed"
|
||||
})
|
||||
|
||||
Expect(before.Tags["genre"].Aliases).To(Equal([]string{"genre", "style"}))
|
||||
Expect(before.DevLogLevels).To(Equal(map[string]string{"scanner": "info"}))
|
||||
Expect(before.Scanner.ArtistSplitExceptions).To(Equal([]string{"AC/DC"}))
|
||||
Expect(conf.Server().DevLogLevels["scanner"]).To(Equal("debug"))
|
||||
})
|
||||
|
||||
It("restores map and slice contents changed in place by Update", func() {
|
||||
restore := conf.SnapshotConfig()
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.Tags["genre"].Aliases[0] = "changed"
|
||||
c.DevLogLevels["scanner"] = "debug"
|
||||
})
|
||||
|
||||
restore()
|
||||
|
||||
Expect(conf.Server().Tags["genre"].Aliases).To(Equal([]string{"genre", "style"}))
|
||||
Expect(conf.Server().DevLogLevels).To(Equal(map[string]string{"scanner": "info"}))
|
||||
})
|
||||
|
||||
It("lets readers run while the config is updated and restored", func() {
|
||||
stop := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
wg.Go(func() {
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
_ = conf.Server().DevLogLevels["scanner"]
|
||||
_ = conf.Server().Scanner.Enabled
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
for range 100 {
|
||||
restore := conf.SnapshotConfig()
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DevLogLevels["scanner"] = "debug"
|
||||
c.Scanner.Enabled = !c.Scanner.Enabled
|
||||
})
|
||||
restore()
|
||||
}
|
||||
close(stop)
|
||||
wg.Wait()
|
||||
})
|
||||
|
||||
It("keeps every change when updates run at the same time", func() {
|
||||
conf.Update(func(c *conf.Options) { c.Port = 0 })
|
||||
var wg sync.WaitGroup
|
||||
for range 50 {
|
||||
wg.Go(func() {
|
||||
for range 20 {
|
||||
conf.Update(func(c *conf.Options) { c.Port++ })
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
Expect(conf.Server().Port).To(Equal(1000))
|
||||
})
|
||||
})
|
||||
@ -94,7 +94,7 @@ type enabledAgent struct {
|
||||
// Each enabledAgent contains the name and whether it's a plugin (true) or built-in (false)
|
||||
func (a *Agents) getEnabledAgentNames() []enabledAgent {
|
||||
// If no agents configured, ONLY use the local agent
|
||||
if conf.Server.Agents == "" {
|
||||
if conf.Server().Agents == "" {
|
||||
return []enabledAgent{{name: LocalAgentName, isPlugin: false}}
|
||||
}
|
||||
|
||||
@ -105,7 +105,7 @@ func (a *Agents) getEnabledAgentNames() []enabledAgent {
|
||||
}
|
||||
log.Trace("Available MetadataAgent plugins", "plugins", availablePlugins)
|
||||
|
||||
configuredAgents := strings.Split(conf.Server.Agents, ",")
|
||||
configuredAgents := strings.Split(conf.Server().Agents, ",")
|
||||
|
||||
// Always add LocalAgentName if not already included
|
||||
hasLocalAgent := slices.Contains(configuredAgents, LocalAgentName)
|
||||
@ -181,7 +181,7 @@ type AlbumImageAgent struct {
|
||||
}
|
||||
|
||||
// ArtistImageAgents returns the enabled agents implementing ArtistImageRetriever,
|
||||
// in conf.Server.Agents order (same order the aggregate dispatch uses).
|
||||
// in conf.Server().Agents order (same order the aggregate dispatch uses).
|
||||
func (a *Agents) ArtistImageAgents() []ArtistImageAgent {
|
||||
var result []ArtistImageAgent
|
||||
for _, ea := range a.getEnabledAgentNames() {
|
||||
@ -193,7 +193,7 @@ func (a *Agents) ArtistImageAgents() []ArtistImageAgent {
|
||||
}
|
||||
|
||||
// AlbumImageAgents returns the enabled agents implementing AlbumImageRetriever,
|
||||
// in conf.Server.Agents order (same order the aggregate dispatch uses).
|
||||
// in conf.Server().Agents order (same order the aggregate dispatch uses).
|
||||
func (a *Agents) AlbumImageAgents() []AlbumImageAgent {
|
||||
var result []AlbumImageAgent
|
||||
for _, ea := range a.getEnabledAgentNames() {
|
||||
@ -256,7 +256,7 @@ func (a *Agents) GetArtistBiography(ctx context.Context, id, name, mbid string)
|
||||
}
|
||||
|
||||
// GetSimilarArtists returns similar artists by id, name, and/or mbid. Because some artists returned from an enabled
|
||||
// agent may not exist in the database, return at most limit * conf.Server.DevExternalArtistFetchMultiplier items.
|
||||
// agent may not exist in the database, return at most limit * conf.Server().DevExternalArtistFetchMultiplier items.
|
||||
func (a *Agents) GetSimilarArtists(ctx context.Context, id, name, mbid string, limit int) ([]Artist, error) {
|
||||
switch id {
|
||||
case consts.UnknownArtistID:
|
||||
@ -265,7 +265,7 @@ func (a *Agents) GetSimilarArtists(ctx context.Context, id, name, mbid string, l
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
overLimit := int(float64(limit) * conf.Server.DevExternalArtistFetchMultiplier)
|
||||
overLimit := int(float64(limit) * conf.Server().DevExternalArtistFetchMultiplier)
|
||||
|
||||
start := time.Now()
|
||||
attempts := newAttempts(&a.cooldowns)
|
||||
@ -316,7 +316,7 @@ func (a *Agents) GetArtistImages(ctx context.Context, id, name, mbid string) ([]
|
||||
}
|
||||
|
||||
// GetArtistTopSongs returns top songs by id, name, and/or mbid. Because some songs returned from an enabled
|
||||
// agent may not exist in the database, return at most limit * conf.Server.DevExternalArtistFetchMultiplier items.
|
||||
// agent may not exist in the database, return at most limit * conf.Server().DevExternalArtistFetchMultiplier items.
|
||||
func (a *Agents) GetArtistTopSongs(ctx context.Context, id, artistName, mbid string, count int) ([]Song, error) {
|
||||
switch id {
|
||||
case consts.UnknownArtistID:
|
||||
@ -325,7 +325,7 @@ func (a *Agents) GetArtistTopSongs(ctx context.Context, id, artistName, mbid str
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
overLimit := int(float64(count) * conf.Server.DevExternalArtistFetchMultiplier)
|
||||
overLimit := int(float64(count) * conf.Server().DevExternalArtistFetchMultiplier)
|
||||
|
||||
return callAgentSliceMethod(ctx, a, "GetArtistTopSongs", func(ag Interface) ([]Song, error) {
|
||||
retriever, ok := ag.(ArtistTopSongsRetriever)
|
||||
|
||||
@ -68,7 +68,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||
Context("Dynamic agent discovery", func() {
|
||||
It("should include ONLY local agent when no config is specified", func() {
|
||||
// Ensure no specific agents are configured
|
||||
conf.Server.Agents = ""
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "" })
|
||||
|
||||
// Add some plugin agents that should be ignored
|
||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent", "another_plugin")
|
||||
@ -82,7 +82,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||
|
||||
It("should NOT include plugin agents when no config is specified", func() {
|
||||
// Ensure no specific agents are configured
|
||||
conf.Server.Agents = ""
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "" })
|
||||
|
||||
// Add a plugin agent
|
||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent")
|
||||
@ -99,13 +99,13 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent")
|
||||
|
||||
// With no config, should not include plugin
|
||||
conf.Server.Agents = ""
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "" })
|
||||
enabledAgents := agents.getEnabledAgentNames()
|
||||
Expect(enabledAgents).To(HaveLen(1))
|
||||
Expect(enabledAgents[0].name).To(Equal(LocalAgentName))
|
||||
|
||||
// When explicitly configured, should include plugin
|
||||
conf.Server.Agents = "plugin_agent"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "plugin_agent" })
|
||||
enabledAgents = agents.getEnabledAgentNames()
|
||||
var agentNames []string
|
||||
var pluginAgentFound bool
|
||||
@ -125,7 +125,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_one", "plugin_two")
|
||||
|
||||
// Configure only one of them
|
||||
conf.Server.Agents = "plugin_one"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "plugin_one" })
|
||||
|
||||
// Verify only the configured one is included
|
||||
enabledAgents := agents.getEnabledAgentNames()
|
||||
@ -147,7 +147,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||
ctx := context.Background()
|
||||
|
||||
// Configure to use our plugin
|
||||
conf.Server.Agents = "plugin_agent"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "plugin_agent" })
|
||||
|
||||
// Add a plugin agent
|
||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent")
|
||||
@ -177,7 +177,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||
}()
|
||||
|
||||
// Configure to use both built-in and plugin
|
||||
conf.Server.Agents = "built_in,plugin_agent"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "built_in,plugin_agent" })
|
||||
|
||||
// Add a plugin agent
|
||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent")
|
||||
@ -223,7 +223,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_x", "plugin_y")
|
||||
|
||||
// Configure specific order - plugin first, then built-ins
|
||||
conf.Server.Agents = "plugin_y,agent_b,plugin_x,agent_a"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "plugin_y,agent_b,plugin_x,agent_a" })
|
||||
|
||||
// Get the agent names
|
||||
enabledAgents := agents.getEnabledAgentNames()
|
||||
@ -250,7 +250,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||
}()
|
||||
|
||||
// Configure to use only built-in agents
|
||||
conf.Server.Agents = "builtin_agent"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "builtin_agent" })
|
||||
|
||||
// Call GetArtistMBID which should only use the built-in agent
|
||||
mbid, err := agents.GetArtistMBID(ctx, "123", "Artist")
|
||||
@ -266,7 +266,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||
ctx := context.Background()
|
||||
|
||||
// Configure with an invalid agent name (not built-in, not a plugin)
|
||||
conf.Server.Agents = "invalid_agent"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "invalid_agent" })
|
||||
|
||||
// This should only result in using the local agent (as the invalid one is ignored)
|
||||
_, err := agents.GetArtistMBID(ctx, "123", "Artist")
|
||||
|
||||
@ -3,6 +3,7 @@ package agents
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -15,3 +16,5 @@ func TestAgents(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Agents Test Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
@ -6,7 +6,6 @@ import (
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
@ -45,7 +44,6 @@ var _ = Describe("Agents", func() {
|
||||
var ds model.DataStore
|
||||
var mfRepo *tests.MockMediaFileRepo
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
ctx, cancel = context.WithCancel(context.Background())
|
||||
mfRepo = tests.CreateMockMediaFileRepo()
|
||||
ds = &tests.MockDataStore{MockedMediaFile: mfRepo}
|
||||
@ -54,7 +52,7 @@ var _ = Describe("Agents", func() {
|
||||
Describe("Local", func() {
|
||||
var ag *Agents
|
||||
BeforeEach(func() {
|
||||
conf.Server.Agents = ""
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "" })
|
||||
ag = createAgents(ds, nil)
|
||||
})
|
||||
|
||||
@ -74,7 +72,7 @@ var _ = Describe("Agents", func() {
|
||||
Register("fake", func(model.DataStore) Interface { return mock })
|
||||
Register("disabled", func(model.DataStore) Interface { return nil })
|
||||
Register("empty", func(model.DataStore) Interface { return &emptyAgent{} })
|
||||
conf.Server.Agents = "empty,fake,disabled"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "empty,fake,disabled" })
|
||||
ag = createAgents(ds, nil)
|
||||
Expect(ag.AgentName()).To(Equal("agents"))
|
||||
})
|
||||
@ -252,7 +250,7 @@ var _ = Describe("Agents", func() {
|
||||
It("returns ErrNotFound when another agent answered with a definitive miss", func() {
|
||||
other := &mockAgent{Err: ErrNotFound}
|
||||
Register("fake2", func(model.DataStore) Interface { return other })
|
||||
conf.Server.Agents = "fake,fake2"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "fake,fake2" })
|
||||
ag = createAgents(ds, nil)
|
||||
mock.Err = &RetryLaterError{RetryIn: time.Hour}
|
||||
|
||||
@ -269,7 +267,7 @@ var _ = Describe("Agents", func() {
|
||||
It("returns ErrNotFound when another agent answered with an empty slice", func() {
|
||||
empty := &testImageAgent{Name: "emptyImages"}
|
||||
Register("emptyImages", func(model.DataStore) Interface { return empty })
|
||||
conf.Server.Agents = "fake,emptyImages"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "fake,emptyImages" })
|
||||
ag = createAgents(ds, nil)
|
||||
mock.Err = &RetryLaterError{RetryIn: time.Hour}
|
||||
|
||||
@ -287,7 +285,7 @@ var _ = Describe("Agents", func() {
|
||||
It("returns ErrNotFound from GetSimilarArtists when another agent answered", func() {
|
||||
other := &mockAgent{Err: ErrNotFound}
|
||||
Register("fake2", func(model.DataStore) Interface { return other })
|
||||
conf.Server.Agents = "fake,fake2"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "fake,fake2" })
|
||||
ag = createAgents(ds, nil)
|
||||
mock.Err = &RetryLaterError{RetryIn: time.Hour}
|
||||
|
||||
@ -330,7 +328,7 @@ var _ = Describe("Agents", func() {
|
||||
})
|
||||
|
||||
It("falls back to the next agent on error", func() {
|
||||
conf.Server.Agents = "imgFail,imgOk"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "imgFail,imgOk" })
|
||||
ag = createAgents(ds, nil)
|
||||
|
||||
images, err := ag.GetArtistImages(ctx, "id", "artist", "mbid")
|
||||
@ -343,7 +341,7 @@ var _ = Describe("Agents", func() {
|
||||
It("falls back if the first agent returns no images", func() {
|
||||
first.Err = nil
|
||||
first.Images = []ExternalImage{}
|
||||
conf.Server.Agents = "imgFail,imgOk"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "imgFail,imgOk" })
|
||||
ag = createAgents(ds, nil)
|
||||
|
||||
images, err := ag.GetArtistImages(ctx, "id", "artist", "mbid")
|
||||
@ -379,7 +377,7 @@ var _ = Describe("Agents", func() {
|
||||
|
||||
Describe("GetArtistTopSongs", func() {
|
||||
It("returns on first match", func() {
|
||||
conf.Server.DevExternalArtistFetchMultiplier = 1
|
||||
conf.Update(func(c *conf.Options) { c.DevExternalArtistFetchMultiplier = 1 })
|
||||
Expect(ag.GetArtistTopSongs(ctx, "123", "test", "mb123", 2)).To(Equal([]Song{{
|
||||
Name: "A Song",
|
||||
MBID: "mbid444",
|
||||
@ -387,7 +385,7 @@ var _ = Describe("Agents", func() {
|
||||
Expect(mock.Args).To(HaveExactElements("123", "test", "mb123", 2))
|
||||
})
|
||||
It("skips the agent if it returns an error", func() {
|
||||
conf.Server.DevExternalArtistFetchMultiplier = 1
|
||||
conf.Update(func(c *conf.Options) { c.DevExternalArtistFetchMultiplier = 1 })
|
||||
mock.Err = errors.New("error")
|
||||
_, err := ag.GetArtistTopSongs(ctx, "123", "test", "mb123", 2)
|
||||
Expect(err).To(MatchError(ErrNotFound))
|
||||
@ -400,7 +398,7 @@ var _ = Describe("Agents", func() {
|
||||
Expect(mock.Args).To(BeEmpty())
|
||||
})
|
||||
It("fetches with multiplier", func() {
|
||||
conf.Server.DevExternalArtistFetchMultiplier = 2
|
||||
conf.Update(func(c *conf.Options) { c.DevExternalArtistFetchMultiplier = 2 })
|
||||
Expect(ag.GetArtistTopSongs(ctx, "123", "test", "mb123", 2)).To(Equal([]Song{{
|
||||
Name: "A Song",
|
||||
MBID: "mbid444",
|
||||
@ -519,7 +517,7 @@ var _ = Describe("Agents", func() {
|
||||
|
||||
Describe("ArtistImageAgents", func() {
|
||||
It("returns only ArtistImageRetriever agents, named, in configured order", func() {
|
||||
conf.Server.Agents = "artistImg,noImages,artistImg2"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "artistImg,noImages,artistImg2" })
|
||||
ag = createAgents(ds, nil)
|
||||
|
||||
result := ag.ArtistImageAgents()
|
||||
@ -531,7 +529,7 @@ var _ = Describe("Agents", func() {
|
||||
})
|
||||
|
||||
It("is empty when external services are disabled", func() {
|
||||
conf.Server.Agents = "" // what disableExternalServices() sets when EnableExternalServices=false
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "" }) // what disableExternalServices() sets when EnableExternalServices=false
|
||||
ag = createAgents(ds, nil)
|
||||
Expect(ag.ArtistImageAgents()).To(BeEmpty())
|
||||
})
|
||||
@ -539,7 +537,7 @@ var _ = Describe("Agents", func() {
|
||||
|
||||
Describe("AlbumImageAgents", func() {
|
||||
It("returns only AlbumImageRetriever agents, named, in configured order", func() {
|
||||
conf.Server.Agents = "albumImg,noImages,albumImg2"
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "albumImg,noImages,albumImg2" })
|
||||
ag = createAgents(ds, nil)
|
||||
|
||||
result := ag.AlbumImageAgents()
|
||||
@ -551,7 +549,7 @@ var _ = Describe("Agents", func() {
|
||||
})
|
||||
|
||||
It("is empty when external services are disabled", func() {
|
||||
conf.Server.Agents = "" // what disableExternalServices() sets when EnableExternalServices=false
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "" }) // what disableExternalServices() sets when EnableExternalServices=false
|
||||
ag = createAgents(ds, nil)
|
||||
Expect(ag.AlbumImageAgents()).To(BeEmpty())
|
||||
})
|
||||
|
||||
@ -10,7 +10,6 @@ import (
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core"
|
||||
"github.com/navidrome/navidrome/core/artwork"
|
||||
"github.com/navidrome/navidrome/core/stream"
|
||||
@ -119,9 +118,6 @@ var _ = Describe("Archiver", func() {
|
||||
})
|
||||
|
||||
When("albums that share a name", func() {
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
})
|
||||
|
||||
// zipArtistEntries zips the given tracks as artist "1" and returns the entry names in zip order.
|
||||
zipArtistEntries := func(mfs model.MediaFiles) []string {
|
||||
@ -179,7 +175,7 @@ var _ = Describe("Archiver", func() {
|
||||
})
|
||||
|
||||
It("prefers the album version over the year when it is not part of the name", func() {
|
||||
conf.Server.Subsonic.AppendAlbumVersion = false
|
||||
conf.Update(func(c *conf.Options) { c.Subsonic.AppendAlbumVersion = false })
|
||||
names := zipArtistEntries(model.MediaFiles{
|
||||
{Path: "a/01.mp3", Suffix: "mp3", AlbumID: "1", Album: "Greatest Hits", Year: 2001,
|
||||
Tags: model.Tags{model.TagAlbumVersion: {"Original"}}},
|
||||
@ -190,7 +186,7 @@ var _ = Describe("Archiver", func() {
|
||||
})
|
||||
|
||||
It("leaves the one album without the field unsuffixed", func() {
|
||||
conf.Server.Subsonic.AppendAlbumVersion = false
|
||||
conf.Update(func(c *conf.Options) { c.Subsonic.AppendAlbumVersion = false })
|
||||
names := zipArtistEntries(model.MediaFiles{
|
||||
{Path: "a/01.mp3", Suffix: "mp3", AlbumID: "1", Album: "Greatest Hits", Year: 2001},
|
||||
{Path: "b/01.mp3", Suffix: "mp3", AlbumID: "2", Album: "Greatest Hits", Year: 2005,
|
||||
@ -200,7 +196,7 @@ var _ = Describe("Archiver", func() {
|
||||
})
|
||||
|
||||
It("skips a field that is empty on more than one album", func() {
|
||||
conf.Server.Subsonic.AppendAlbumVersion = false
|
||||
conf.Update(func(c *conf.Options) { c.Subsonic.AppendAlbumVersion = false })
|
||||
names := zipArtistEntries(model.MediaFiles{
|
||||
{Path: "a/01.mp3", Suffix: "mp3", AlbumID: "1", Album: "Greatest Hits", Year: 2001},
|
||||
{Path: "b/01.mp3", Suffix: "mp3", AlbumID: "2", Album: "Greatest Hits", Year: 2005},
|
||||
@ -235,7 +231,7 @@ var _ = Describe("Archiver", func() {
|
||||
})
|
||||
|
||||
It("sanitizes the suffix", func() {
|
||||
conf.Server.Subsonic.AppendAlbumVersion = false
|
||||
conf.Update(func(c *conf.Options) { c.Subsonic.AppendAlbumVersion = false })
|
||||
names := zipArtistEntries(model.MediaFiles{
|
||||
{Path: "a/01.mp3", Suffix: "mp3", AlbumID: "1", Album: "Hits", Tags: model.Tags{model.TagAlbumVersion: {"Vinyl"}}},
|
||||
{Path: "b/01.mp3", Suffix: "mp3", AlbumID: "2", Album: "Hits", Tags: model.Tags{model.TagAlbumVersion: {"CD/Digital"}}},
|
||||
|
||||
@ -16,7 +16,7 @@ import (
|
||||
|
||||
// externalName mirrors the normalization the aggregate provider applies, so agent searches match.
|
||||
func externalName(name string) string {
|
||||
if conf.Server.DevPreserveUnicodeInExternalCalls {
|
||||
if conf.Server().DevPreserveUnicodeInExternalCalls {
|
||||
return name
|
||||
}
|
||||
return str.Clear(name)
|
||||
|
||||
@ -11,7 +11,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
@ -65,7 +64,7 @@ func imageAgents(fakes ...*fakeImageAgent) *agents.Agents {
|
||||
agents.Register(fake.name, func(model.DataStore) agents.Interface { return fake })
|
||||
names = append(names, fake.name)
|
||||
}
|
||||
conf.Server.Agents = strings.Join(names, ",")
|
||||
conf.Update(func(c *conf.Options) { c.Agents = strings.Join(names, ",") })
|
||||
return agents.GetAgents(&tests.MockDataStore{}, nil)
|
||||
}
|
||||
|
||||
@ -76,7 +75,6 @@ var _ = Describe("agent images", func() {
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
ctx = context.Background()
|
||||
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte("image-bytes"))
|
||||
@ -200,7 +198,7 @@ var _ = Describe("agent images", func() {
|
||||
})
|
||||
|
||||
It("clears typographic characters from the query name unless preserving unicode", func() {
|
||||
conf.Server.DevPreserveUnicodeInExternalCalls = false
|
||||
conf.Update(func(c *conf.Options) { c.DevPreserveUnicodeInExternalCalls = false })
|
||||
a := &fakeImageAgent{name: "agentA"}
|
||||
ag := imageAgents(a)
|
||||
|
||||
|
||||
@ -263,7 +263,7 @@ func (s *service) serveResolution(ctx context.Context, res resolution, size int,
|
||||
func (s *service) serveMediaFile(ctx context.Context, artID model.ArtworkID, size int, square bool) (*Image, error) {
|
||||
// The setting is not in the config fingerprint, so honor it at serve time: a direct mf- URL
|
||||
// must fall back to disc/album instead of serving stale persisted embedded art.
|
||||
if !conf.Server.EnableMediaFileCoverArt {
|
||||
if !conf.Server().EnableMediaFileCoverArt {
|
||||
mf, err := s.ds.MediaFile().Get(ctx, artID.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -287,7 +287,7 @@ func (s *service) serveMediaFile(ctx context.Context, artID model.ArtworkID, siz
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if noRow && conf.Server.EnableMediaFileCoverArt && mf.HasCoverArt {
|
||||
if noRow && conf.Server().EnableMediaFileCoverArt && mf.HasCoverArt {
|
||||
return s.provisionalEmbedded(ctx, artID, *mf, size, square)
|
||||
}
|
||||
// Mirror MediaFile.CoverArtID: a track defers to its disc art, which falls back to the album.
|
||||
@ -317,13 +317,13 @@ func (s *service) serveDisc(ctx context.Context, artID model.ArtworkID, size int
|
||||
}
|
||||
// Single-disc albums run the chain too: a disc can carry art distinct from the album cover.
|
||||
selectImage := func() (io.ReadCloser, error) {
|
||||
res, err := dr.selectImage(ctx, s.ffmpeg, conf.Server.DiscArtPriority, &chainState{})
|
||||
res, err := dr.selectImage(ctx, s.ffmpeg, conf.Server().DiscArtPriority, &chainState{})
|
||||
return res.reader, err
|
||||
}
|
||||
albumArtID := model.ArtworkID{Kind: model.KindAlbumArtwork, ID: dr.album.ID}
|
||||
// Disc art has no state row, hence no content hash: keying on id, album mtime and
|
||||
// DiscArtPriority lets a warm cache answer without running the chain or touching the disk.
|
||||
key := fmt.Sprintf("%s|%d|%s", artID.ID, dr.cacheTime().UnixNano(), conf.Server.DiscArtPriority)
|
||||
key := fmt.Sprintf("%s|%d|%s", artID.ID, dr.cacheTime().UnixNano(), conf.Server().DiscArtPriority)
|
||||
img, err := s.serveSource(ctx, key, "", dr.cacheTime(), size, square, selectImage)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
|
||||
@ -12,6 +12,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core/storage"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
@ -41,6 +42,8 @@ func TestArtwork(t *testing.T) {
|
||||
RunSpecs(t, "Artwork Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
// productionImageClient keeps the guarded client for the specs that assert it refuses loopback.
|
||||
var productionImageClient = remoteImageClient
|
||||
|
||||
|
||||
@ -10,7 +10,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/resources"
|
||||
@ -71,7 +70,6 @@ var _ = Describe("Artwork", func() {
|
||||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
ctx = context.Background()
|
||||
var err error
|
||||
repoRoot, err = os.Getwd()
|
||||
@ -79,11 +77,13 @@ var _ = Describe("Artwork", func() {
|
||||
coverBytes, err = os.ReadFile(filepath.Join(repoRoot, "tests/fixtures/artist/an-album/cover.jpg"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
conf.Server.EnableWebPEncoding = false
|
||||
conf.Server.CoverArtQuality = 75
|
||||
conf.Server.CoverArtPriority = "cover.*"
|
||||
conf.Server.DiscArtPriority = "cover.*"
|
||||
conf.Server.CacheFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.EnableWebPEncoding = false
|
||||
c.CoverArtQuality = 75
|
||||
c.CoverArtPriority = "cover.*"
|
||||
c.DiscArtPriority = "cover.*"
|
||||
c.CacheFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
})
|
||||
|
||||
artRepo = tests.CreateMockArtworkRepo()
|
||||
queueRepo = tests.CreateMockArtworkQueueRepo()
|
||||
@ -298,7 +298,7 @@ var _ = Describe("Artwork", func() {
|
||||
})
|
||||
|
||||
It("ignores a resolved mf row and delegates to the album when per-track art is disabled", func() {
|
||||
conf.Server.EnableMediaFileCoverArt = false
|
||||
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false })
|
||||
seedFoundStore("mf", "mf7", []byte("stale embedded track art"))
|
||||
seedFoundStore("al", "albz", coverBytes)
|
||||
mfRepo.SetData(model.MediaFiles{{ID: "mf7", AlbumID: "albz"}})
|
||||
@ -321,7 +321,7 @@ var _ = Describe("Artwork", func() {
|
||||
})
|
||||
|
||||
It("delegates to the album (no enqueue) when the track is not embedded-eligible", func() {
|
||||
conf.Server.EnableMediaFileCoverArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
|
||||
seedFoundStore("al", "albn", coverBytes)
|
||||
mfRepo.SetData(model.MediaFiles{{ID: "mf3", AlbumID: "albn", HasCoverArt: false}})
|
||||
|
||||
@ -333,7 +333,7 @@ var _ = Describe("Artwork", func() {
|
||||
})
|
||||
|
||||
It("extracts embedded art provisionally and enqueues the track when eligible", func() {
|
||||
conf.Server.EnableMediaFileCoverArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
|
||||
mfRepo.SetData(model.MediaFiles{{
|
||||
ID: "mf4", AlbumID: "albo", HasCoverArt: true,
|
||||
Path: "tests/fixtures/artist/an-album/test.mp3", LibraryID: 0,
|
||||
@ -360,7 +360,7 @@ var _ = Describe("Artwork", func() {
|
||||
})
|
||||
|
||||
It("falls back to the album when an eligible track's embedded art will not extract", func() {
|
||||
conf.Server.EnableMediaFileCoverArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
|
||||
// HasCoverArt is set, but the file is not audio, so nothing extracts.
|
||||
mfRepo.SetData(model.MediaFiles{{
|
||||
ID: "mfbad", AlbumID: "albad", LibraryID: 0, HasCoverArt: true,
|
||||
|
||||
@ -5,13 +5,11 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
)
|
||||
|
||||
func BenchmarkResizeFullPipeline(b *testing.B) {
|
||||
cleanup := configtest.SetupConfig()
|
||||
b.Cleanup(cleanup)
|
||||
conf.Server.CoverArtQuality = 75
|
||||
b.Cleanup(conf.SnapshotConfig())
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtQuality = 75 })
|
||||
|
||||
sourceSizes := []int{1000, 3000}
|
||||
targetSize := 300
|
||||
|
||||
@ -10,7 +10,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/core/artwork"
|
||||
@ -64,18 +63,19 @@ var _ = Describe("Acquisition → serve loop", func() {
|
||||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
ctx = context.Background()
|
||||
repoRoot, err := os.Getwd()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
coverBytes = readFixture(coverFixture)
|
||||
|
||||
conf.Server.CacheFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
conf.Server.DataFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
conf.Server.CoverArtPriority = "cover.jpg"
|
||||
conf.Server.ArtistArtPriority = "artist.png" // keeps artist resolution offline
|
||||
conf.Server.EnableMediaFileCoverArt = true
|
||||
conf.Server.DevArtworkWorkerConcurrency = 1
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CacheFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
c.DataFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
c.CoverArtPriority = "cover.jpg"
|
||||
c.ArtistArtPriority = "artist.png" // keeps artist resolution offline
|
||||
c.EnableMediaFileCoverArt = true
|
||||
c.DevArtworkWorkerConcurrency = 1
|
||||
})
|
||||
|
||||
folderRepo = &fakeFolderRepo{}
|
||||
libRepo = &tests.MockLibraryRepo{}
|
||||
@ -122,7 +122,7 @@ var _ = Describe("Acquisition → serve loop", func() {
|
||||
Expect(os.MkdirAll(filepath.Join(libDir, "an-album"), 0755)).To(Succeed())
|
||||
Expect(os.WriteFile(filepath.Join(libDir, "an-album", "cover.jxl"), jxlFixture, 0600)).To(Succeed())
|
||||
|
||||
conf.Server.CoverArtPriority = "cover.*"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*" })
|
||||
libRepo.SetData(model.Libraries{{ID: 0, Path: libDir}})
|
||||
folderRepo.result = []model.Folder{{Path: "an-album", ImageFiles: []string{"cover.jxl"}}}
|
||||
albumRepo.SetData(model.Albums{{ID: "al1", Name: "Album", FolderIDs: []string{"f1"}, LibraryID: 0}})
|
||||
|
||||
@ -22,7 +22,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── cover.jpg ← matched by cover.*
|
||||
It("returns the album-root cover", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/cover.jpg": smallPNG("album-root"),
|
||||
@ -46,7 +46,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// │ └── cover.jpg
|
||||
// └── cover.jpg ← should win (album-root fallback)
|
||||
It("prefers the album-root cover over per-disc covers", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/CD1/01 - Track.mp3": trackFile(1, "Track CD1"),
|
||||
"Artist/Album/CD2/01 - Track.mp3": trackFile(1, "Track CD2"),
|
||||
@ -77,7 +77,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// │ └── folder.jpg
|
||||
// └── folder.jpg ← should win (album-root fallback)
|
||||
It("prefers the album-root folder.jpg over per-disc folder.jpg", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/CD1/01 - Track.mp3": trackFile(1, "Track CD1"),
|
||||
"Artist/Album/CD2/01 - Track.mp3": trackFile(1, "Track CD2"),
|
||||
@ -99,7 +99,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// │ └── 01 - Track.mp3
|
||||
// └── cover.jpg ← should win (parent-folder fallback)
|
||||
It("uses the parent-folder cover for single-disc-subfolder albums", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/disc1/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/cover.jpg": smallPNG("album-root"),
|
||||
@ -120,7 +120,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// │ └── folder.jpg
|
||||
// └── cover.jpg ← should win (album-root)
|
||||
It("prefers the album-root cover.jpg", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Album/CD1/01 - Track.mp3": trackFile(1, "Track CD1"),
|
||||
"Album/CD2/01 - Track.mp3": trackFile(1, "Track CD2"),
|
||||
@ -139,7 +139,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3 ← has embedded picture (wins via "embedded")
|
||||
// └── cover.jpg
|
||||
It("returns the embedded image", func() {
|
||||
conf.Server.CoverArtPriority = "embedded, cover.*, folder.*, front.*, external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "embedded, cover.*, folder.*, front.*, external" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track", map[string]any{"has_picture": "true"}),
|
||||
"Artist/Album/cover.jpg": smallPNG("external"),
|
||||
@ -158,7 +158,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// └── Album/
|
||||
// └── 01 - Track.mp3 ← has embedded picture (falls through to "embedded")
|
||||
It("falls through to embedded artwork", func() {
|
||||
conf.Server.CoverArtPriority = "external, embedded"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external, embedded" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track", map[string]any{"has_picture": "true"}),
|
||||
})
|
||||
@ -177,7 +177,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── Cover.JPG ← matched case-insensitively by cover.*
|
||||
It("matches case-insensitively against cover.*", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*, folder.*"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*, folder.*" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/Cover.JPG": smallPNG("case-insensitive"),
|
||||
@ -194,7 +194,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── cover.jpg ← wins (no numeric suffix)
|
||||
// └── cover.1.jpg
|
||||
It("prefers the file without a numeric suffix", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/cover.jpg": smallPNG("primary"),
|
||||
@ -210,7 +210,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// └── Album/
|
||||
// └── 01 - Track.mp3 (no image files — settles absent)
|
||||
It("settles absent", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*, folder.*"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*, folder.*" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
})
|
||||
@ -228,7 +228,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── folder.jpg ← matched by folder.*
|
||||
It("falls through to folder.jpg", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/folder.jpg": smallPNG("folder"),
|
||||
@ -244,7 +244,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── front.jpg ← matched by front.*
|
||||
It("falls through to front.jpg", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/front.jpg": smallPNG("front"),
|
||||
@ -262,7 +262,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── folder.jpg
|
||||
// └── front.jpg
|
||||
It("prefers cover.* (first in CoverArtPriority)", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/cover.jpg": smallPNG("cover"),
|
||||
@ -281,7 +281,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── folder.jpg ← wins (folder.* comes before front.*)
|
||||
// └── front.jpg
|
||||
It("prefers folder.* over front.*", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/folder.jpg": smallPNG("folder"),
|
||||
@ -300,7 +300,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── cover.1.jpg
|
||||
// └── cover.2.jpg
|
||||
It("selects the unsuffixed file first regardless of numeric-suffix order", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/cover.2.jpg": smallPNG("second"),
|
||||
@ -318,7 +318,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── cover.jpg ← wins (unknown "bogus.*" is skipped)
|
||||
It("skips the unknown pattern and falls through to the matching one", func() {
|
||||
conf.Server.CoverArtPriority = "bogus.*, cover.*"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "bogus.*, cover.*" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/cover.jpg": smallPNG("cover"),
|
||||
@ -340,7 +340,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── cover.jpg
|
||||
It("does not use the artist image as album art", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/folder.jpg": smallPNG("artist-thumbnail"),
|
||||
"Artist/Album A/01 - Track.mp3": trackFile(1, "Track A", map[string]any{"album": "Album A", "albumartist": "Artist"}),
|
||||
@ -366,7 +366,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── cover.jpg
|
||||
It("does not use the artist image as album art for the spread album", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/folder.jpg": smallPNG("artist-thumbnail"),
|
||||
"Artist/Album A/01 - Track.mp3": trackFile(1, "Track A1", map[string]any{"album": "Album A", "albumartist": "Artist"}),
|
||||
@ -392,7 +392,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// └── CD2/
|
||||
// └── 01 - Track.mp3
|
||||
It("does not adopt the library-root image as album art", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"cover.jpg": smallPNG("library-root"),
|
||||
"CD1/01 - Track.mp3": trackFile(1, "T1", map[string]any{"album": "Rootless", "disc": "1"}),
|
||||
@ -412,7 +412,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── cover.jpg ← should win
|
||||
It("prefers the album's own cover over the shallower artist-folder cover", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/cover.jpg": smallPNG("artist-image"),
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track", map[string]any{"albumartist": "Artist"}),
|
||||
@ -435,7 +435,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// └── Album B/
|
||||
// └── 01 - Track.mp3 (other-album audio: rejects the artist folder as a root)
|
||||
It("prefers the album's own art over the artist image", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/cover.jpg": smallPNG("artist-image"),
|
||||
"Artist/Album A/01 - Track.mp3": trackFile(1, "Track A1", map[string]any{"album": "Album A", "albumartist": "Artist"}),
|
||||
@ -458,7 +458,7 @@ var _ = Describe("Album artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3 (no embedded picture)
|
||||
// └── cover.jpg ← wins (embedded skipped, falls through)
|
||||
It("falls through to the next priority entry", func() {
|
||||
conf.Server.CoverArtPriority = "embedded, cover.*"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "embedded, cover.*" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/cover.jpg": smallPNG("cover"),
|
||||
|
||||
@ -30,7 +30,7 @@ var _ = Describe("Artist artwork resolution", func() {
|
||||
// └── Album/
|
||||
// └── 01 - Track.mp3
|
||||
It("returns the artist.* image from the artist folder", func() {
|
||||
conf.Server.ArtistArtPriority = "artist.*, album/artist.*, external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "artist.*, album/artist.*, external" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track", map[string]any{"albumartist": "Artist"}),
|
||||
"Artist/artist.jpg": smallPNG("artist-folder"),
|
||||
@ -46,7 +46,7 @@ var _ = Describe("Artist artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── artist.jpg ← matched by album/artist.*
|
||||
It("falls through to album/artist.* and returns that image", func() {
|
||||
conf.Server.ArtistArtPriority = "artist.*, album/artist.*, external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "artist.*, album/artist.*, external" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track", map[string]any{"albumartist": "Artist"}),
|
||||
"Artist/Album/artist.jpg": smallPNG("album-artist"),
|
||||
@ -63,7 +63,7 @@ var _ = Describe("Artist artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── artist.jpg
|
||||
It("prefers the artist-folder image (artist.* comes before album/artist.*)", func() {
|
||||
conf.Server.ArtistArtPriority = "artist.*, album/artist.*, external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "artist.*, album/artist.*, external" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track", map[string]any{"albumartist": "Artist"}),
|
||||
"Artist/artist.jpg": smallPNG("artist-folder"),
|
||||
@ -80,7 +80,7 @@ var _ = Describe("Artist artwork resolution", func() {
|
||||
// └── Album/
|
||||
// └── 01 - Track.mp3
|
||||
It("still resolves the artist folder and returns artist.*", func() {
|
||||
conf.Server.ArtistArtPriority = "artist.*"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "artist.*" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track", map[string]any{"albumartist": "Artist"}),
|
||||
"Artist/artist.jpg": smallPNG("artist-folder"),
|
||||
@ -99,7 +99,7 @@ var _ = Describe("Artist artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── 02 - Track.mp3
|
||||
It("resolves the artist folder, not the library root", func() {
|
||||
conf.Server.ArtistArtPriority = "folder.*, artist.*, album/artist.*"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "folder.*, artist.*, album/artist.*" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track 1", map[string]any{"albumartist": "Artist", "album": "Album"}),
|
||||
"Artist/Album/02 - Track.mp3": trackFile(2, "Track 2", map[string]any{"albumartist": "Artist", "album": "Album"}),
|
||||
@ -120,7 +120,7 @@ var _ = Describe("Artist artwork resolution", func() {
|
||||
// ├── CD1/01 - Track.mp3
|
||||
// └── CD2/02 - Track.mp3
|
||||
It("prefers the artist-folder image over the album-folder one", func() {
|
||||
conf.Server.ArtistArtPriority = "artist.*, album/artist.*, external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "artist.*, album/artist.*, external" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/CD1/01 - Track.mp3": trackFile(1, "Track 1", map[string]any{"albumartist": "Artist", "album": "Album"}),
|
||||
"Artist/Album/CD2/02 - Track.mp3": trackFile(2, "Track 2", map[string]any{"albumartist": "Artist", "album": "Album"}),
|
||||
@ -141,7 +141,7 @@ var _ = Describe("Artist artwork resolution", func() {
|
||||
// │ └── CD2/02 - Track.mp3
|
||||
// └── Album2/03 - Track.mp3
|
||||
It("prefers the artist-folder image over the album-folder one", func() {
|
||||
conf.Server.ArtistArtPriority = "artist.*, album/artist.*, external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "artist.*, album/artist.*, external" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album1/CD1/01 - Track.mp3": trackFile(1, "Track 1", map[string]any{"albumartist": "Artist", "album": "Album1"}),
|
||||
"Artist/Album1/CD2/02 - Track.mp3": trackFile(2, "Track 2", map[string]any{"albumartist": "Artist", "album": "Album1"}),
|
||||
@ -165,7 +165,7 @@ var _ = Describe("Artist artwork resolution", func() {
|
||||
// ├── CD1/03 - Track.mp3
|
||||
// └── CD2/04 - Track.mp3
|
||||
It("prefers the artist-folder image over the album-folder one", func() {
|
||||
conf.Server.ArtistArtPriority = "artist.*, album/artist.*, external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "artist.*, album/artist.*, external" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album1/CD1/01 - Track.mp3": trackFile(1, "Track 1", map[string]any{"albumartist": "Artist", "album": "Album1"}),
|
||||
"Artist/Album1/CD2/02 - Track.mp3": trackFile(2, "Track 2", map[string]any{"albumartist": "Artist", "album": "Album1"}),
|
||||
@ -190,7 +190,7 @@ var _ = Describe("Artist artwork resolution", func() {
|
||||
// └── Album/
|
||||
// └── 01 - Track.mp3
|
||||
It("prefers the uploaded image over any priority-chain match", func() {
|
||||
conf.Server.ArtistArtPriority = "artist.*, album/artist.*, external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "artist.*, album/artist.*, external" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track", map[string]any{"albumartist": "Artist"}),
|
||||
"Artist/artist.jpg": smallPNG("artist-folder"),
|
||||
@ -215,7 +215,7 @@ var _ = Describe("Artist artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── artist.jpg ← matched by album/artist.*
|
||||
It("resolves the pattern against the artist's album image files", func() {
|
||||
conf.Server.ArtistArtPriority = "album/artist.*, external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "album/artist.*, external" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track", map[string]any{"albumartist": "Artist"}),
|
||||
"Artist/Album/artist.jpg": smallPNG("album-artist"),
|
||||
@ -233,7 +233,7 @@ var _ = Describe("Artist artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── artist.jpg ← must NOT become the artist image
|
||||
It("ignores the album's images and settles absent", func() {
|
||||
conf.Server.ArtistArtPriority = "album/artist.*"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "album/artist.*" })
|
||||
// " / " is a default artists split separator, so this single tag yields two album artists.
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Collab Album/01 - Track.mp3": trackFile(1, "Track", map[string]any{"albumartist": "Artist / Collaborator"}),
|
||||
@ -261,8 +261,10 @@ var _ = Describe("Artist artwork resolution", func() {
|
||||
It("returns the image from the configured artist image folder", func() {
|
||||
imgFolder := GinkgoT().TempDir()
|
||||
Expect(os.WriteFile(filepath.Join(imgFolder, "Artist.jpg"), pngBytes("image-folder"), 0o600)).To(Succeed())
|
||||
conf.Server.ArtistImageFolder = imgFolder
|
||||
conf.Server.ArtistArtPriority = "image-folder, artist.*, album/artist.*"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.ArtistImageFolder = imgFolder
|
||||
c.ArtistArtPriority = "image-folder, artist.*, album/artist.*"
|
||||
})
|
||||
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track", map[string]any{"albumartist": "Artist"}),
|
||||
|
||||
@ -23,7 +23,7 @@ var _ = Describe("Disc artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── disc1.jpg ← matched by disc*.*
|
||||
It("returns the disc1.jpg image (matched as disc*.*)", func() {
|
||||
conf.Server.DiscArtPriority = "disc*.*, cd*.*, cover.*, folder.*, front.*, embedded"
|
||||
conf.Update(func(c *conf.Options) { c.DiscArtPriority = "disc*.*, cd*.*, cover.*, folder.*, front.*, embedded" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/disc1.jpg": smallPNG("disc1-image"),
|
||||
@ -38,8 +38,10 @@ var _ = Describe("Disc artwork resolution", func() {
|
||||
// └── Album/
|
||||
// └── 01 - Track.mp3 (no disc or album art — nothing to serve)
|
||||
It("reports the disc lookup as unavailable", func() {
|
||||
conf.Server.DiscArtPriority = "disc*.*, cd*.*"
|
||||
conf.Server.CoverArtPriority = "cover.*, folder.*"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DiscArtPriority = "disc*.*, cd*.*"
|
||||
c.CoverArtPriority = "cover.*, folder.*"
|
||||
})
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
})
|
||||
@ -54,8 +56,10 @@ var _ = Describe("Disc artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── cover.jpg ← album-level fallback (no disc art present)
|
||||
It("falls back to the album cover", func() {
|
||||
conf.Server.DiscArtPriority = "disc*.*, cd*.*"
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DiscArtPriority = "disc*.*, cd*.*"
|
||||
c.CoverArtPriority = defaultCoverPriority
|
||||
})
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/cover.jpg": smallPNG("album-cover"),
|
||||
@ -72,7 +76,7 @@ var _ = Describe("Disc artwork resolution", func() {
|
||||
// ├── disc1.jpg ← matches request for disc 1
|
||||
// └── disc10.jpg
|
||||
It("matches the requested disc number, not a higher-numbered one", func() {
|
||||
conf.Server.DiscArtPriority = "disc*.*"
|
||||
conf.Update(func(c *conf.Options) { c.DiscArtPriority = "disc*.*" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/disc1.jpg": smallPNG("disc-one"),
|
||||
@ -93,7 +97,7 @@ var _ = Describe("Disc artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── disc2.jpg ← matches request for disc 2
|
||||
It("returns the requested disc's image", func() {
|
||||
conf.Server.DiscArtPriority = "disc*.*"
|
||||
conf.Update(func(c *conf.Options) { c.DiscArtPriority = "disc*.*" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/CD1/01 - Track.mp3": trackFile(1, "T1", map[string]any{"disc": "1"}),
|
||||
"Artist/Album/CD2/01 - Track.mp3": trackFile(1, "T2", map[string]any{"disc": "2"}),
|
||||
@ -118,7 +122,7 @@ var _ = Describe("Disc artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── cd2.png ← matched by cd*.* for disc 2
|
||||
It("matches via the cd*.* pattern", func() {
|
||||
conf.Server.DiscArtPriority = defaultDiscPriority
|
||||
conf.Update(func(c *conf.Options) { c.DiscArtPriority = defaultDiscPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/CD1/01 - Track.mp3": trackFile(1, "T1", map[string]any{"disc": "1"}),
|
||||
"Artist/Album/CD2/01 - Track.mp3": trackFile(1, "T2", map[string]any{"disc": "2"}),
|
||||
@ -140,7 +144,7 @@ var _ = Describe("Disc artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── cover.jpg
|
||||
It("falls through to cover.* inside the disc folder", func() {
|
||||
conf.Server.DiscArtPriority = defaultDiscPriority
|
||||
conf.Update(func(c *conf.Options) { c.DiscArtPriority = defaultDiscPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/CD1/01 - Track.mp3": trackFile(1, "T1", map[string]any{"disc": "1"}),
|
||||
"Artist/Album/CD2/01 - Track.mp3": trackFile(1, "T2", map[string]any{"disc": "2"}),
|
||||
@ -163,8 +167,10 @@ var _ = Describe("Disc artwork resolution", func() {
|
||||
// │ └── cd2.png (ignored — DiscArtPriority is empty)
|
||||
// └── cover.jpg ← used for every disc (album-level fallback)
|
||||
It("skips every disc-level source and returns the album cover", func() {
|
||||
conf.Server.DiscArtPriority = ""
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DiscArtPriority = ""
|
||||
c.CoverArtPriority = defaultCoverPriority
|
||||
})
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/CD1/01 - Track.mp3": trackFile(1, "T1", map[string]any{"disc": "1"}),
|
||||
"Artist/Album/CD2/01 - Track.mp3": trackFile(1, "T2", map[string]any{"disc": "2"}),
|
||||
@ -194,8 +200,10 @@ var _ = Describe("Disc artwork resolution", func() {
|
||||
// │ └── 02 - Track.mp3
|
||||
// └── cover.jpg (album-level fallback, unused here)
|
||||
It("matches the per-disc image for each disc", func() {
|
||||
conf.Server.DiscArtPriority = defaultDiscPriority
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DiscArtPriority = defaultDiscPriority
|
||||
c.CoverArtPriority = defaultCoverPriority
|
||||
})
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/disc1/01 - Track.mp3": trackFile(1, "T1", map[string]any{"disc": "1"}),
|
||||
"Artist/Album/disc1/02 - Track.mp3": trackFile(2, "T2", map[string]any{"disc": "1"}),
|
||||
@ -219,7 +227,7 @@ var _ = Describe("Disc artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3 (discsubtitle="Bonus Tracks")
|
||||
// └── Bonus Tracks.jpg ← matched by "discsubtitle" keyword
|
||||
It("selects the subtitle-named image", func() {
|
||||
conf.Server.DiscArtPriority = "discsubtitle"
|
||||
conf.Update(func(c *conf.Options) { c.DiscArtPriority = "discsubtitle" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "T1", map[string]any{"disc": "1", "discsubtitle": "Bonus Tracks"}),
|
||||
"Artist/Album/Bonus Tracks.jpg": smallPNG("bonus-tracks"),
|
||||
@ -242,8 +250,10 @@ var _ = Describe("Disc artwork resolution", func() {
|
||||
// │ └── folder.jpg
|
||||
// └── ... (12 discs)
|
||||
It("uses album-root cover.jpg for album art and per-disc folder.jpg for each disc", func() {
|
||||
conf.Server.DiscArtPriority = defaultDiscPriority
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DiscArtPriority = defaultDiscPriority
|
||||
c.CoverArtPriority = defaultCoverPriority
|
||||
})
|
||||
discNames := []string{
|
||||
"Disc 01 (Birth of the Dead - The Studio Sides)",
|
||||
"Disc 02 (Birth of the Dead - The Live Sides)",
|
||||
@ -294,8 +304,10 @@ var _ = Describe("Disc artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3
|
||||
// └── folder.jpg
|
||||
It("uses album-root cover.jpg for album art and per-disc folder.jpg for each disc", func() {
|
||||
conf.Server.DiscArtPriority = defaultDiscPriority
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DiscArtPriority = defaultDiscPriority
|
||||
c.CoverArtPriority = defaultCoverPriority
|
||||
})
|
||||
layout := fstest.MapFS{
|
||||
"Album/cover.jpg": smallPNG("album-root-cover"),
|
||||
}
|
||||
@ -321,7 +333,7 @@ var _ = Describe("Disc artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3 (discsubtitle="Bonus Tracks")
|
||||
// └── cover.jpg ← wins (discsubtitle has no match, falls through)
|
||||
It("falls through to the next priority entry", func() {
|
||||
conf.Server.DiscArtPriority = "discsubtitle, cover.*"
|
||||
conf.Update(func(c *conf.Options) { c.DiscArtPriority = "discsubtitle, cover.*" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "T1", map[string]any{"disc": "1", "discsubtitle": "Bonus Tracks"}),
|
||||
"Artist/Album/cover.jpg": smallPNG("cover"),
|
||||
|
||||
@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
_ "github.com/navidrome/navidrome/adapters/gotaglib" // registers the "taglib" local-storage extractor
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core/artwork"
|
||||
_ "github.com/navidrome/navidrome/core/storage/local"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
@ -27,6 +28,8 @@ func TestArtworkE2E(t *testing.T) {
|
||||
RunSpecs(t, "Artwork Pipeline E2E Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
// Fixtures relative to the project root (tests.Init chdirs there).
|
||||
const (
|
||||
coverFixture = "tests/fixtures/artist/an-album/cover.jpg"
|
||||
|
||||
@ -35,8 +35,10 @@ var _ = Describe("MediaFile artwork resolution", func() {
|
||||
// │ └── disc2.jpg ← wins (disc-level before album-level)
|
||||
// └── cover.jpg
|
||||
It("falls back to the disc-level artwork (not the album cover)", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Server.DiscArtPriority = defaultDiscPriority
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = defaultCoverPriority
|
||||
c.DiscArtPriority = defaultDiscPriority
|
||||
})
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/CD1/01 - Track.mp3": trackFile(1, "T1", map[string]any{"disc": "1"}),
|
||||
"Artist/Album/CD2/01 - Track.mp3": trackFile(1, "T2", map[string]any{"disc": "2"}),
|
||||
@ -57,8 +59,10 @@ var _ = Describe("MediaFile artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3 ← track requested
|
||||
// └── cover.jpg ← wins (album-level fallback, no disc subfolder)
|
||||
It("falls back to the album cover", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Server.DiscArtPriority = defaultDiscPriority
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = defaultCoverPriority
|
||||
c.DiscArtPriority = defaultDiscPriority
|
||||
})
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track"),
|
||||
"Artist/Album/cover.jpg": smallPNG("album-cover"),
|
||||
@ -79,8 +83,10 @@ var _ = Describe("MediaFile artwork resolution", func() {
|
||||
// │ └── 01 - Track.mp3 ← track requested
|
||||
// └── cover.jpg ← wins (no disc image → album-level fallback)
|
||||
It("falls through from disc to album cover", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Server.DiscArtPriority = defaultDiscPriority
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = defaultCoverPriority
|
||||
c.DiscArtPriority = defaultDiscPriority
|
||||
})
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/CD1/01 - Track.mp3": trackFile(1, "T1", map[string]any{"disc": "1"}),
|
||||
"Artist/Album/CD2/01 - Track.mp3": trackFile(1, "T2", map[string]any{"disc": "2"}),
|
||||
@ -98,7 +104,7 @@ var _ = Describe("MediaFile artwork resolution", func() {
|
||||
// └── Album/
|
||||
// └── 01 - Track.mp3 ← has embedded picture (wins over every fallback)
|
||||
It("resolves the track's embedded image into the store", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track", map[string]any{"has_picture": "true"}),
|
||||
})
|
||||
@ -118,7 +124,7 @@ var _ = Describe("MediaFile artwork resolution", func() {
|
||||
// ├── 01 - Track.mp3 ← has embedded picture (must NOT be served)
|
||||
// └── cover.jpg ← wins (per-track art disabled at serve time)
|
||||
It("serves the album cover instead of the track's embedded art", func() {
|
||||
conf.Server.CoverArtPriority = defaultCoverPriority
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = defaultCoverPriority })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/Album/01 - Track.mp3": trackFile(1, "Track", map[string]any{"has_picture": "true"}),
|
||||
"Artist/Album/cover.jpg": smallPNG("album-cover"),
|
||||
@ -127,7 +133,7 @@ var _ = Describe("MediaFile artwork resolution", func() {
|
||||
replaceWithRealMP3("Artist/Album/01 - Track.mp3")
|
||||
|
||||
// The setting is not part of the artwork fingerprint, so it must be honored at serve time.
|
||||
conf.Server.EnableMediaFileCoverArt = false
|
||||
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false })
|
||||
mf := mediafileOn("Artist/Album/01 - Track.mp3")
|
||||
trackArtID := model.NewArtworkID(model.KindMediaFileArtwork, mf.ID, nil)
|
||||
Expect(serveBytes(trackArtID)).To(Equal(pngBytes("album-cover")))
|
||||
|
||||
@ -82,7 +82,7 @@ var _ = Describe("Playlist artwork resolution", func() {
|
||||
// <tempdir>/
|
||||
// └── cover.jpg ← absolute path stored in ExternalImageURL
|
||||
It("returns the local file regardless of EnableM3UExternalAlbumArt", func() {
|
||||
conf.Server.EnableM3UExternalAlbumArt = false // local paths bypass the toggle
|
||||
conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = false }) // local paths bypass the toggle
|
||||
dir := GinkgoT().TempDir()
|
||||
imgPath := filepath.Join(dir, "cover.jpg")
|
||||
Expect(os.WriteFile(imgPath, pngBytes("external-local"), 0o600)).To(Succeed())
|
||||
@ -96,7 +96,7 @@ var _ = Describe("Playlist artwork resolution", func() {
|
||||
When("a playlist has an http(s) ExternalImageURL and EnableM3UExternalAlbumArt is false", func() {
|
||||
// (no local files — the http source is gated off, so resolution settles absent)
|
||||
It("skips the URL and settles absent", func() {
|
||||
conf.Server.EnableM3UExternalAlbumArt = false
|
||||
conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = false })
|
||||
pl := putPlaylist(model.Playlist{ID: "pl-5", Name: "HttpGated", ExternalImageURL: "https://example.com/cover.jpg"})
|
||||
|
||||
ia := acquire(model.KindPlaylistArtwork, pl.ID)
|
||||
@ -133,7 +133,7 @@ var _ = Describe("Playlist artwork resolution", func() {
|
||||
// Playlist "pl-7" references tracks from both albums, so the worker generates a tiled
|
||||
// cover from 2 distinct album art tiles (mirrored to fill the 2x2 grid).
|
||||
It("generates a tiled cover from album art", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*" })
|
||||
setLayout(fstest.MapFS{
|
||||
"Artist/AlbumA/01 - Track.mp3": trackFile(1, "TA", map[string]any{"album": "AlbumA"}),
|
||||
"Artist/AlbumA/cover.png": smallPNG("albumA"),
|
||||
@ -171,7 +171,7 @@ var _ = Describe("Playlist artwork resolution", func() {
|
||||
// ├── AlbumC/{01 - Track.mp3, cover.png} ← tile 3
|
||||
// └── AlbumD/{01 - Track.mp3, cover.png} ← tile 4
|
||||
It("fills all four grid quadrants with distinct album art", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*" })
|
||||
layout := fstest.MapFS{}
|
||||
for _, name := range []string{"AlbumA", "AlbumB", "AlbumC", "AlbumD"} {
|
||||
layout["Artist/"+name+"/01 - Track.mp3"] = trackFile(1, "T"+name, map[string]any{"album": name})
|
||||
|
||||
@ -19,7 +19,6 @@ import (
|
||||
|
||||
_ "github.com/navidrome/navidrome/adapters/gotaglib"
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/core/artwork"
|
||||
@ -67,9 +66,10 @@ var userTables []string
|
||||
var _ = BeforeSuite(func() {
|
||||
suiteDBTempDir = GinkgoT().TempDir()
|
||||
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.DbPath = filepath.Join(suiteDBTempDir, "artwork-resolution-e2e.db") + "?_journal_mode=WAL"
|
||||
conf.Server.DataFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DbPath = filepath.Join(suiteDBTempDir, "artwork-resolution-e2e.db") + "?_journal_mode=WAL"
|
||||
c.DataFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
})
|
||||
db.Db().SetMaxOpenConns(1)
|
||||
db.Init(request.WithUser(context.Background(), model.User{ID: "admin-1", IsAdmin: true}))
|
||||
|
||||
@ -81,17 +81,19 @@ var _ = AfterSuite(func() {
|
||||
})
|
||||
|
||||
func setupResolutionHarness() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
DeferCleanup(conf.SnapshotConfig())
|
||||
|
||||
tempDir := GinkgoT().TempDir()
|
||||
conf.Server.DbPath = filepath.Join(suiteDBTempDir, "artwork-resolution-e2e.db") + "?_journal_mode=WAL"
|
||||
conf.Server.DataFolder = conf.NewDir(tempDir)
|
||||
conf.Server.MusicFolder = fakeLibPath
|
||||
conf.Server.DevExternalScanner = false
|
||||
conf.Server.ImageCacheSize = "0"
|
||||
conf.Server.EnableExternalServices = false
|
||||
conf.Server.EnableMediaFileCoverArt = true
|
||||
conf.Server.DevArtworkWorkerConcurrency = 1
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DbPath = filepath.Join(suiteDBTempDir, "artwork-resolution-e2e.db") + "?_journal_mode=WAL"
|
||||
c.DataFolder = conf.NewDir(tempDir)
|
||||
c.MusicFolder = fakeLibPath
|
||||
c.DevExternalScanner = false
|
||||
c.ImageCacheSize = "0"
|
||||
c.EnableExternalServices = false
|
||||
c.EnableMediaFileCoverArt = true
|
||||
c.DevArtworkWorkerConcurrency = 1
|
||||
})
|
||||
|
||||
rctx = request.WithUser(GinkgoT().Context(), model.User{ID: "admin-1", UserName: "admin", IsAdmin: true})
|
||||
harness.TruncateDB(userTables)
|
||||
|
||||
@ -75,7 +75,7 @@ func (w *Worker) gateFor(name string) *extGate {
|
||||
if g, ok := w.gates[name]; ok {
|
||||
return g
|
||||
}
|
||||
rps := conf.Server.DevArtworkExternalMaxRPS
|
||||
rps := conf.Server().DevArtworkExternalMaxRPS
|
||||
limit := rate.Inf
|
||||
if rps > 0 {
|
||||
limit = rate.Limit(rps)
|
||||
|
||||
@ -50,12 +50,12 @@ type FingerprintInput struct {
|
||||
// FingerprintInputs is the single listing of what ConfigFingerprint hashes.
|
||||
func FingerprintInputs() []FingerprintInput {
|
||||
return []FingerprintInput{
|
||||
{"CoverArtPriority", conf.Server.CoverArtPriority},
|
||||
{"ArtistArtPriority", conf.Server.ArtistArtPriority},
|
||||
{"ArtistImageFolder", conf.Server.ArtistImageFolder},
|
||||
{"Agents", conf.Server.Agents},
|
||||
{"EnableExternalServices", strconv.FormatBool(conf.Server.EnableExternalServices)},
|
||||
{"EnableM3UExternalAlbumArt", strconv.FormatBool(conf.Server.EnableM3UExternalAlbumArt)},
|
||||
{"CoverArtPriority", conf.Server().CoverArtPriority},
|
||||
{"ArtistArtPriority", conf.Server().ArtistArtPriority},
|
||||
{"ArtistImageFolder", conf.Server().ArtistImageFolder},
|
||||
{"Agents", conf.Server().Agents},
|
||||
{"EnableExternalServices", strconv.FormatBool(conf.Server().EnableExternalServices)},
|
||||
{"EnableM3UExternalAlbumArt", strconv.FormatBool(conf.Server().EnableM3UExternalAlbumArt)},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -5,7 +5,6 @@ import (
|
||||
"slices"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
@ -35,12 +34,13 @@ var _ = Describe("Housekeeping", func() {
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
ctx = context.Background()
|
||||
conf.Server.CoverArtPriority = "embedded, folder"
|
||||
conf.Server.ArtistArtPriority = "artist.jpg"
|
||||
conf.Server.Agents = "spotify"
|
||||
conf.Server.EnableExternalServices = true
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "embedded, folder"
|
||||
c.ArtistArtPriority = "artist.jpg"
|
||||
c.Agents = "spotify"
|
||||
c.EnableExternalServices = true
|
||||
})
|
||||
|
||||
queueRepo = tests.CreateMockArtworkQueueRepo()
|
||||
propRepo = &tests.MockedPropertyRepo{}
|
||||
@ -49,31 +49,35 @@ var _ = Describe("Housekeeping", func() {
|
||||
|
||||
Describe("Fingerprint", func() {
|
||||
DescribeTable("changes when a fingerprint-affecting config value changes",
|
||||
func(change func()) {
|
||||
func(change func(*conf.Options)) {
|
||||
before := ConfigFingerprint()
|
||||
change()
|
||||
conf.Update(change)
|
||||
Expect(ConfigFingerprint()).NotTo(Equal(before))
|
||||
},
|
||||
Entry("CoverArtPriority", func() { conf.Server.CoverArtPriority = "folder, embedded" }),
|
||||
Entry("ArtistImageFolder", func() { conf.Server.ArtistImageFolder = "/after" }),
|
||||
Entry("EnableM3UExternalAlbumArt", func() { conf.Server.EnableM3UExternalAlbumArt = true }),
|
||||
Entry("CoverArtPriority", func(c *conf.Options) { c.CoverArtPriority = "folder, embedded" }),
|
||||
Entry("ArtistImageFolder", func(c *conf.Options) { c.ArtistImageFolder = "/after" }),
|
||||
Entry("EnableM3UExternalAlbumArt", func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true }),
|
||||
)
|
||||
|
||||
// Pinned: a changed formula tells every existing install its artwork config went stale.
|
||||
It("hashes a given config to a stable value", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*, embedded"
|
||||
conf.Server.ArtistArtPriority = "artist.*, external"
|
||||
conf.Server.ArtistImageFolder = ""
|
||||
conf.Server.Agents = "lastfm,spotify"
|
||||
conf.Server.EnableExternalServices = true
|
||||
conf.Server.EnableM3UExternalAlbumArt = false
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "cover.*, embedded"
|
||||
c.ArtistArtPriority = "artist.*, external"
|
||||
c.ArtistImageFolder = ""
|
||||
c.Agents = "lastfm,spotify"
|
||||
c.EnableExternalServices = true
|
||||
c.EnableM3UExternalAlbumArt = false
|
||||
})
|
||||
|
||||
Expect(ConfigFingerprint()).To(Equal("7b538a83a870c16d"))
|
||||
})
|
||||
|
||||
It("reports the config inputs it hashes, so a change can be traced to a setting", func() {
|
||||
conf.Server.Agents = "lastfm,spotify"
|
||||
conf.Server.CoverArtPriority = "cover.*, embedded"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.Agents = "lastfm,spotify"
|
||||
c.CoverArtPriority = "cover.*, embedded"
|
||||
})
|
||||
|
||||
Expect(FingerprintInputs()).To(ContainElements(
|
||||
FingerprintInput{Name: "Agents", Value: "lastfm,spotify"},
|
||||
|
||||
@ -26,7 +26,7 @@ type imageCache struct {
|
||||
func GetImageCache() cache.FileCache {
|
||||
return singleton.GetInstance(func() *imageCache {
|
||||
return &imageCache{
|
||||
FileCache: cache.NewFileCache("Image", conf.Server.ImageCacheSize, consts.ImageCacheDir, consts.DefaultImageCacheMaxItems,
|
||||
FileCache: cache.NewFileCache("Image", conf.Server().ImageCacheSize, consts.ImageCacheDir, consts.DefaultImageCacheMaxItems,
|
||||
func(ctx context.Context, arg cache.Item) (io.Reader, error) {
|
||||
return arg.(artworkReader).Reader(ctx)
|
||||
}),
|
||||
|
||||
@ -27,7 +27,7 @@ func NewImageStore(rootDir string) *ImageStore {
|
||||
}
|
||||
|
||||
func GetImageStore() *ImageStore {
|
||||
return NewImageStore(filepath.Join(conf.Server.DataFolder.String(), consts.ArtworkFolder, consts.HashedArtworkFolder))
|
||||
return NewImageStore(filepath.Join(conf.Server().DataFolder.String(), consts.ArtworkFolder, consts.HashedArtworkFolder))
|
||||
}
|
||||
|
||||
// extForMime must stay stable across OSes: extensions are baked into stored paths and re-derived on Open.
|
||||
|
||||
@ -56,7 +56,7 @@ const thumbnailSize = 100
|
||||
// maxImageBytes caps a resolved image read: a user-editable ExternalImageURL could point at
|
||||
// an arbitrarily large endpoint.
|
||||
func maxImageBytes() int64 {
|
||||
return parseSize(conf.Server.MaxImageSize, consts.DefaultMaxImageSize)
|
||||
return parseSize(conf.Server().MaxImageSize, consts.DefaultMaxImageSize)
|
||||
}
|
||||
|
||||
// maxImagePixels guards against decompression bombs: a tiny file can declare a canvas that
|
||||
|
||||
@ -16,7 +16,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
@ -57,7 +56,6 @@ var _ = Describe("processor.acquire", func() {
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
ctx = context.Background()
|
||||
var err error
|
||||
repoRoot, err = os.Getwd()
|
||||
@ -78,7 +76,7 @@ var _ = Describe("processor.acquire", func() {
|
||||
store = NewImageStore(GinkgoT().TempDir())
|
||||
proc = &processor{ds: ds, store: store, resolver: newResolver(ds, ag, ffm, nil)}
|
||||
|
||||
conf.Server.CoverArtPriority = "cover.jpg, embedded"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg, embedded" })
|
||||
})
|
||||
|
||||
It("found-folder: persists state from a folder image, writes no store file, keeps sourcePath/refMtime", func() {
|
||||
@ -187,7 +185,7 @@ var _ = Describe("processor.acquire", func() {
|
||||
})
|
||||
|
||||
It("failed-on-unreadable-local: a listed cover that will not open never records absent", func() {
|
||||
conf.Server.CoverArtPriority = "cover.jpg"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg" })
|
||||
// A folder listing that names a cover the FS will not hand over: a stale mount.
|
||||
libRoot := GinkgoT().TempDir()
|
||||
Expect(os.MkdirAll(filepath.Join(libRoot, "an-album"), 0o755)).To(Succeed())
|
||||
@ -214,7 +212,7 @@ var _ = Describe("processor.acquire", func() {
|
||||
radioRepo.Data = map[string]*model.Radio{}
|
||||
ds.MockedRadio = radioRepo
|
||||
dir := GinkgoT().TempDir()
|
||||
conf.Server.DataFolder = conf.NewDir(dir)
|
||||
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(dir) })
|
||||
upload := model.UploadedImagePath(consts.EntityRadio, "ra-io.jpg")
|
||||
Expect(os.MkdirAll(filepath.Dir(upload), 0o755)).To(Succeed())
|
||||
Expect(os.WriteFile(upload, []byte("x"), 0o600)).To(Succeed())
|
||||
@ -240,7 +238,7 @@ var _ = Describe("processor.acquire", func() {
|
||||
radioRepo.Data = map[string]*model.Radio{}
|
||||
ds.MockedRadio = radioRepo
|
||||
dir := GinkgoT().TempDir()
|
||||
conf.Server.DataFolder = conf.NewDir(dir)
|
||||
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(dir) })
|
||||
upload := model.UploadedImagePath(consts.EntityRadio, "ra-tr.jpg")
|
||||
// A plain file where the upload's parent should be makes os.Open fault with ENOTDIR,
|
||||
// deterministically and regardless of the test user's privileges.
|
||||
@ -259,7 +257,7 @@ var _ = Describe("processor.acquire", func() {
|
||||
})
|
||||
|
||||
It("failed-on-extError: leaves the item's state untouched", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
|
||||
{ID: "al4", Name: "Album"},
|
||||
})
|
||||
@ -274,7 +272,7 @@ var _ = Describe("processor.acquire", func() {
|
||||
})
|
||||
|
||||
It("failed-on-extError: reports the delay a throttled provider asked for", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
|
||||
{ID: "al4r", Name: "Album"},
|
||||
})
|
||||
@ -286,7 +284,7 @@ var _ = Describe("processor.acquire", func() {
|
||||
})
|
||||
|
||||
It("found-stale: a fallback hit after a transient external failure persists state and returns outcomeFoundStale", func() {
|
||||
conf.Server.CoverArtPriority = "external, cover.jpg"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external, cover.jpg" })
|
||||
folderRepo.result = []model.Folder{{
|
||||
Path: "tests/fixtures/artist/an-album",
|
||||
ImageFiles: []string{"cover.jpg"},
|
||||
@ -342,7 +340,7 @@ var _ = Describe("processor.acquire", func() {
|
||||
|
||||
// An agent answering 200 with a non-image body must keep retrying, not pin garbage as a cover.
|
||||
It("undecodable external body: fails without writing state", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte("<html>rate limited</html>"))
|
||||
}))
|
||||
@ -359,7 +357,7 @@ var _ = Describe("processor.acquire", func() {
|
||||
})
|
||||
|
||||
It("found-external: persists source as external:<agentName> and stores the fetched bytes", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
imgBytes, err := os.ReadFile(filepath.Join(repoRoot, "tests/fixtures/artist/an-album/cover.jpg"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
@ -470,7 +468,7 @@ var _ = Describe("processor.acquire", func() {
|
||||
|
||||
It("decode failure on found bytes: fails without writing state", func() {
|
||||
tmpDir := GinkgoT().TempDir()
|
||||
conf.Server.DataFolder = conf.NewDir(tmpDir)
|
||||
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) })
|
||||
Expect(os.MkdirAll(filepath.Join(tmpDir, "artwork", "radio"), 0755)).To(Succeed())
|
||||
imgPath := filepath.Join(tmpDir, "artwork", "radio", "ra1_test.jpg")
|
||||
// Truncated PNG: a known format, so this is a real decode failure, not a missing decoder.
|
||||
@ -489,7 +487,7 @@ var _ = Describe("processor.acquire", func() {
|
||||
|
||||
It("oversized read: a resolved image larger than the cap fails without writing state", func() {
|
||||
tmpDir := GinkgoT().TempDir()
|
||||
conf.Server.DataFolder = conf.NewDir(tmpDir)
|
||||
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) })
|
||||
Expect(os.MkdirAll(filepath.Join(tmpDir, "artwork", "radio"), 0755)).To(Succeed())
|
||||
imgPath := filepath.Join(tmpDir, "artwork", "radio", "big_test.jpg")
|
||||
f, err := os.Create(imgPath)
|
||||
@ -643,12 +641,9 @@ var _ = Describe("makeThumbnail", func() {
|
||||
})
|
||||
|
||||
var _ = Describe("maxImageBytes", func() {
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
})
|
||||
|
||||
It("reads MaxImageSize from config", func() {
|
||||
conf.Server.MaxImageSize = "30MB"
|
||||
conf.Update(func(c *conf.Options) { c.MaxImageSize = "30MB" })
|
||||
Expect(maxImageBytes()).To(Equal(int64(30_000_000)))
|
||||
})
|
||||
})
|
||||
|
||||
@ -48,7 +48,7 @@ func resizeImageData(ctx context.Context, ffm ffmpeg.FFmpeg, data []byte, size i
|
||||
if isAnimatedGIF(data) {
|
||||
if ffm.IsAvailable() {
|
||||
// Animated GIF: convert to animated WebP via ffmpeg (with optional resize)
|
||||
r, err := ffm.ConvertAnimatedImage(ctx, bytes.NewReader(data), size, conf.Server.CoverArtQuality)
|
||||
r, err := ffm.ConvertAnimatedImage(ctx, bytes.NewReader(data), size, conf.Server().CoverArtQuality)
|
||||
if err == nil {
|
||||
return r, 0, nil
|
||||
}
|
||||
@ -117,12 +117,12 @@ func resizeStaticImage(data []byte, size int, square bool) (io.Reader, int, erro
|
||||
|
||||
buf := bufPool.Get().(*bytes.Buffer)
|
||||
buf.Reset()
|
||||
if conf.Server.EnableWebPEncoding {
|
||||
err = webp.Encode(buf, dst, webp.Options{Quality: conf.Server.CoverArtQuality})
|
||||
if conf.Server().EnableWebPEncoding {
|
||||
err = webp.Encode(buf, dst, webp.Options{Quality: conf.Server().CoverArtQuality})
|
||||
} else if format == "png" || square {
|
||||
err = png.Encode(buf, dst)
|
||||
} else {
|
||||
err = jpeg.Encode(buf, dst, &jpeg.Options{Quality: conf.Server.CoverArtQuality})
|
||||
err = jpeg.Encode(buf, dst, &jpeg.Options{Quality: conf.Server().CoverArtQuality})
|
||||
}
|
||||
if err != nil {
|
||||
bufPool.Put(buf)
|
||||
@ -137,8 +137,8 @@ func resizeStaticImage(data []byte, size int, square bool) (io.Reader, int, erro
|
||||
// formatQualityTag folds the encoder config (WebP toggle + quality) into a cache-key
|
||||
// fragment, so flipping either setting invalidates previously-encoded sized artwork.
|
||||
func formatQualityTag() string {
|
||||
if conf.Server.EnableWebPEncoding {
|
||||
return fmt.Sprintf("webp%d", conf.Server.CoverArtQuality)
|
||||
if conf.Server().EnableWebPEncoding {
|
||||
return fmt.Sprintf("webp%d", conf.Server().CoverArtQuality)
|
||||
}
|
||||
return fmt.Sprintf("q%d", conf.Server.CoverArtQuality)
|
||||
return fmt.Sprintf("q%d", conf.Server().CoverArtQuality)
|
||||
}
|
||||
|
||||
@ -125,11 +125,11 @@ func Explainable(kind model.Kind) bool {
|
||||
func MayFetchExternal(kind model.Kind) bool {
|
||||
switch kind {
|
||||
case model.KindArtistArtwork:
|
||||
return chainFetchesExternal(conf.Server.ArtistArtPriority)
|
||||
return chainFetchesExternal(conf.Server().ArtistArtPriority)
|
||||
case model.KindAlbumArtwork:
|
||||
return chainFetchesExternal(conf.Server.CoverArtPriority)
|
||||
return chainFetchesExternal(conf.Server().CoverArtPriority)
|
||||
case model.KindPlaylistArtwork:
|
||||
return conf.Server.EnableM3UExternalAlbumArt || chainFetchesExternal(conf.Server.CoverArtPriority)
|
||||
return conf.Server().EnableM3UExternalAlbumArt || chainFetchesExternal(conf.Server().CoverArtPriority)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
@ -160,10 +160,10 @@ func ExternalLookupsPerItem(kind model.Kind, agents ImageAgentCount) int64 {
|
||||
return int64(max(agents.Album, 1))
|
||||
case model.KindPlaylistArtwork:
|
||||
var n int64
|
||||
if conf.Server.EnableM3UExternalAlbumArt {
|
||||
if conf.Server().EnableM3UExternalAlbumArt {
|
||||
n++
|
||||
}
|
||||
if chainFetchesExternal(conf.Server.CoverArtPriority) {
|
||||
if chainFetchesExternal(conf.Server().CoverArtPriority) {
|
||||
n += PlaylistGridSamples * int64(max(agents.Album, 1))
|
||||
}
|
||||
return n
|
||||
@ -196,7 +196,7 @@ func (r *resolver) fetchExternalArtist(ctx context.Context, ar model.Artist) (io
|
||||
return fetchArtistImage(ctx, r.ext.agents, r.ext.gate, ar)
|
||||
}
|
||||
|
||||
// resolveAlbum walks conf.Server.CoverArtPriority over the folder, embedded and external sources.
|
||||
// resolveAlbum walks conf.Server().CoverArtPriority over the folder, embedded and external sources.
|
||||
func (r *resolver) resolveAlbum(ctx context.Context, albumID string) (resolution, error) {
|
||||
al, err := r.ds.Album().Get(ctx, albumID)
|
||||
if err != nil {
|
||||
@ -212,7 +212,7 @@ func (r *resolver) resolveAlbum(ctx context.Context, albumID string) (resolution
|
||||
}
|
||||
|
||||
chain := chainState{trace: traceFrom(ctx)}
|
||||
for pattern := range strings.SplitSeq(strings.ToLower(conf.Server.CoverArtPriority), ",") {
|
||||
for pattern := range strings.SplitSeq(strings.ToLower(conf.Server().CoverArtPriority), ",") {
|
||||
pattern = strings.TrimSpace(pattern)
|
||||
if pattern == "" {
|
||||
continue
|
||||
@ -241,7 +241,7 @@ func (r *resolver) resolveAlbum(ctx context.Context, albumID string) (resolution
|
||||
return chain.exhausted(), nil
|
||||
}
|
||||
|
||||
// resolveArtist tries the uploaded image first, then walks conf.Server.ArtistArtPriority.
|
||||
// resolveArtist tries the uploaded image first, then walks conf.Server().ArtistArtPriority.
|
||||
func (r *resolver) resolveArtist(ctx context.Context, artistID string) (resolution, error) {
|
||||
ar, err := r.ds.Artist().Get(ctx, artistID)
|
||||
if err != nil {
|
||||
@ -279,7 +279,7 @@ func (r *resolver) resolveArtist(ctx context.Context, artistID string) (resoluti
|
||||
}
|
||||
}
|
||||
|
||||
for pattern := range strings.SplitSeq(strings.ToLower(conf.Server.ArtistArtPriority), ",") {
|
||||
for pattern := range strings.SplitSeq(strings.ToLower(conf.Server().ArtistArtPriority), ",") {
|
||||
pattern = strings.TrimSpace(pattern)
|
||||
if pattern == "" {
|
||||
continue
|
||||
@ -362,7 +362,7 @@ func (r *resolver) resolvePlaylist(ctx context.Context, playlistID string) (reso
|
||||
// The remote fetch and the generated grid are worker-only; a request must do neither.
|
||||
return resolution{}, nil
|
||||
}
|
||||
if remoteImg != nil && conf.Server.EnableM3UExternalAlbumArt {
|
||||
if remoteImg != nil && conf.Server().EnableM3UExternalAlbumArt {
|
||||
sf := func() (io.ReadCloser, string, error) { return fromURL(ctx, remoteImg) }
|
||||
if res, ok, err := resolveExternalStep(r.ext.gate, "m3u", sf); ok {
|
||||
return res, nil
|
||||
@ -448,7 +448,7 @@ func (r *resolver) resolveMediaFile(ctx context.Context, id string) (resolution,
|
||||
}
|
||||
chain := chainState{trace: traceFrom(ctx)}
|
||||
switch {
|
||||
case !conf.Server.EnableMediaFileCoverArt:
|
||||
case !conf.Server().EnableMediaFileCoverArt:
|
||||
chain.record("embedded", OutcomeSkipped, "EnableMediaFileCoverArt is off")
|
||||
return resolution{}, nil
|
||||
case !mf.HasCoverArt:
|
||||
@ -466,7 +466,7 @@ func (r *resolver) resolveMediaFile(ctx context.Context, id string) (resolution,
|
||||
return chain.exhausted(), nil
|
||||
}
|
||||
|
||||
// resolveDisc walks conf.Server.DiscArtPriority. Disc artwork keeps no state row and is never
|
||||
// resolveDisc walks conf.Server().DiscArtPriority. Disc artwork keeps no state row and is never
|
||||
// queued: the serving path reads it through on every request, so this only ever explains.
|
||||
func (r *resolver) resolveDisc(ctx context.Context, id string) (resolution, error) {
|
||||
dr, err := newDiscArtworkReader(ctx, r.ds, model.ArtworkID{Kind: model.KindDiscArtwork, ID: id})
|
||||
@ -474,7 +474,7 @@ func (r *resolver) resolveDisc(ctx context.Context, id string) (resolution, erro
|
||||
return resolution{}, err
|
||||
}
|
||||
chain := chainState{trace: traceFrom(ctx)}
|
||||
return dr.selectImage(ctx, r.ffmpeg, conf.Server.DiscArtPriority, &chain)
|
||||
return dr.selectImage(ctx, r.ffmpeg, conf.Server().DiscArtPriority, &chain)
|
||||
}
|
||||
|
||||
// resolveExternalStep runs a single external sourceFunc through the named gate. A not-found is a
|
||||
@ -544,7 +544,7 @@ func resolveFolderFile(ctx context.Context, lib libraryView, imgFiles []string,
|
||||
// Basename-only on purpose: the chain climbs parent folders, so a token's prefix is not fixed.
|
||||
func IsArtistImageFile(name string) bool {
|
||||
name = strings.ToLower(name)
|
||||
for pattern := range strings.SplitSeq(strings.ToLower(conf.Server.ArtistArtPriority), ",") {
|
||||
for pattern := range strings.SplitSeq(strings.ToLower(conf.Server().ArtistArtPriority), ",") {
|
||||
pattern = strings.TrimSpace(pattern)
|
||||
if pattern == "" || pattern == externalCandidate || pattern == "image-folder" {
|
||||
continue
|
||||
@ -557,7 +557,7 @@ func IsArtistImageFile(name string) bool {
|
||||
}
|
||||
|
||||
func resolveArtistImageFolder(ar *model.Artist) (resolution, bool) {
|
||||
folder := conf.Server.ArtistImageFolder
|
||||
folder := conf.Server().ArtistImageFolder
|
||||
if folder == "" {
|
||||
return resolution{}, false
|
||||
}
|
||||
|
||||
@ -13,7 +13,6 @@ import (
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
@ -22,25 +21,22 @@ import (
|
||||
)
|
||||
|
||||
var _ = Describe("IsArtistImageFile", func() {
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
})
|
||||
|
||||
It("matches bare and album/-prefixed glob tokens, case-insensitively", func() {
|
||||
conf.Server.ArtistArtPriority = "artist.*, album/artistfolder.*, external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "artist.*, album/artistfolder.*, external" })
|
||||
Expect(IsArtistImageFile("Artist.jpg")).To(BeTrue())
|
||||
Expect(IsArtistImageFile("artistfolder.png")).To(BeTrue())
|
||||
Expect(IsArtistImageFile("cover.jpg")).To(BeFalse())
|
||||
})
|
||||
|
||||
It("matches a directory-bearing glob by its basename", func() {
|
||||
conf.Server.ArtistArtPriority = "images/artist.*, external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "images/artist.*, external" })
|
||||
Expect(IsArtistImageFile("artist.jpg")).To(BeTrue())
|
||||
Expect(IsArtistImageFile("cover.jpg")).To(BeFalse())
|
||||
})
|
||||
|
||||
It("does not treat non-file tokens as globs", func() {
|
||||
conf.Server.ArtistArtPriority = "image-folder, external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "image-folder, external" })
|
||||
Expect(IsArtistImageFile("image-folder")).To(BeFalse())
|
||||
Expect(IsArtistImageFile("external")).To(BeFalse())
|
||||
})
|
||||
@ -58,7 +54,6 @@ var _ = Describe("resolveItem", func() {
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
ctx = context.Background()
|
||||
var err error
|
||||
repoRoot, err = os.Getwd()
|
||||
@ -84,7 +79,7 @@ var _ = Describe("resolveItem", func() {
|
||||
|
||||
Describe("media file", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.EnableMediaFileCoverArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
|
||||
ds.MockedMediaFile = tests.CreateMockMediaFileRepo()
|
||||
})
|
||||
|
||||
@ -115,7 +110,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("resolves absent when media file cover art is disabled", func() {
|
||||
conf.Server.EnableMediaFileCoverArt = false
|
||||
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false })
|
||||
ds.MockedMediaFile.(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
|
||||
{ID: "mf3", LibraryID: 0, Path: "tests/fixtures/artist/an-album/test.mp3", HasCoverArt: true},
|
||||
})
|
||||
@ -134,7 +129,7 @@ var _ = Describe("resolveItem", func() {
|
||||
|
||||
Describe("album", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.CoverArtPriority = "cover.jpg, embedded"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg, embedded" })
|
||||
ds.MockedAlbum = tests.CreateMockAlbumRepo()
|
||||
})
|
||||
|
||||
@ -173,7 +168,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("sets extErr when the external source errors without being not-found", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
|
||||
{ID: "al3", Name: "Album"},
|
||||
})
|
||||
@ -186,7 +181,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("does not set extErr when the external source reports not-found", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
|
||||
{ID: "al4", Name: "Album"},
|
||||
})
|
||||
@ -199,7 +194,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("carries extErr onto a fallback folder hit after a transient external failure", func() {
|
||||
conf.Server.CoverArtPriority = "external, cover.jpg"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external, cover.jpg" })
|
||||
folderRepo.result = []model.Folder{{
|
||||
Path: "tests/fixtures/artist/an-album",
|
||||
ImageFiles: []string{"cover.jpg"},
|
||||
@ -218,7 +213,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("does not carry extErr onto a fallback folder hit after a definitive external not-found", func() {
|
||||
conf.Server.CoverArtPriority = "external, cover.jpg"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external, cover.jpg" })
|
||||
folderRepo.result = []model.Folder{{
|
||||
Path: "tests/fixtures/artist/an-album",
|
||||
ImageFiles: []string{"cover.jpg"},
|
||||
@ -237,7 +232,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("routes the external step through the injected gate, keyed by agent name", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
|
||||
{ID: "al5", Name: "Album"},
|
||||
})
|
||||
@ -258,7 +253,7 @@ var _ = Describe("resolveItem", func() {
|
||||
Describe("artist", func() {
|
||||
It("resolves the uploaded image before any priority chain lookup", func() {
|
||||
tmpDir := GinkgoT().TempDir()
|
||||
conf.Server.DataFolder = conf.NewDir(tmpDir)
|
||||
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) })
|
||||
Expect(os.MkdirAll(filepath.Join(tmpDir, "artwork", "artist"), 0755)).To(Succeed())
|
||||
imgPath := filepath.Join(tmpDir, "artwork", "artist", "ar1_test.jpg")
|
||||
Expect(os.WriteFile(imgPath, []byte("uploaded artist image"), 0600)).To(Succeed())
|
||||
@ -276,7 +271,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("falls through to the ArtistArtPriority chain when there is no upload", func() {
|
||||
conf.Server.ArtistArtPriority = "album/artist.*"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "album/artist.*" })
|
||||
folderRepo.result = []model.Folder{{
|
||||
LibraryPath: testFileLibPath(repoRoot),
|
||||
Path: "tests/fixtures/artist/an-album",
|
||||
@ -299,7 +294,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("sets extErr when the external source errors without being not-found", func() {
|
||||
conf.Server.ArtistArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external" })
|
||||
artistRepo := tests.CreateMockArtistRepo()
|
||||
artistRepo.SetData(model.Artists{{ID: "ar3", Name: "Artist"}})
|
||||
ds.MockedArtist = artistRepo
|
||||
@ -312,7 +307,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("does not set extErr when the external source reports not-found", func() {
|
||||
conf.Server.ArtistArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external" })
|
||||
artistRepo := tests.CreateMockArtistRepo()
|
||||
artistRepo.SetData(model.Artists{{ID: "ar4", Name: "Artist"}})
|
||||
ds.MockedArtist = artistRepo
|
||||
@ -325,7 +320,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("routes the external step through the injected gate, keyed by agent name", func() {
|
||||
conf.Server.ArtistArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external" })
|
||||
artistRepo := tests.CreateMockArtistRepo()
|
||||
artistRepo.SetData(model.Artists{{ID: "ar5", Name: "Artist"}})
|
||||
ds.MockedArtist = artistRepo
|
||||
@ -346,7 +341,7 @@ var _ = Describe("resolveItem", func() {
|
||||
Describe("radio", func() {
|
||||
It("yields an empty resolution when there is no uploaded image", func() {
|
||||
tmpDir := GinkgoT().TempDir()
|
||||
conf.Server.DataFolder = conf.NewDir(tmpDir)
|
||||
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) })
|
||||
|
||||
radioRepo := tests.CreateMockedRadioRepo()
|
||||
radioRepo.Data = map[string]*model.Radio{"ra1": {ID: "ra1", Name: "Radio"}}
|
||||
@ -359,7 +354,7 @@ var _ = Describe("resolveItem", func() {
|
||||
|
||||
It("resolves the uploaded image when set", func() {
|
||||
tmpDir := GinkgoT().TempDir()
|
||||
conf.Server.DataFolder = conf.NewDir(tmpDir)
|
||||
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) })
|
||||
Expect(os.MkdirAll(filepath.Join(tmpDir, "artwork", "radio"), 0755)).To(Succeed())
|
||||
imgPath := filepath.Join(tmpDir, "artwork", "radio", "ra2_test.jpg")
|
||||
Expect(os.WriteFile(imgPath, []byte("uploaded radio image"), 0600)).To(Succeed())
|
||||
@ -379,7 +374,7 @@ var _ = Describe("resolveItem", func() {
|
||||
|
||||
Describe("playlist", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.CoverArtPriority = "cover.jpg"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg" })
|
||||
folderRepo.result = []model.Folder{{
|
||||
Path: "tests/fixtures/artist/an-album",
|
||||
ImageFiles: []string{"cover.jpg"},
|
||||
@ -422,8 +417,10 @@ var _ = Describe("resolveItem", func() {
|
||||
// The grid samples album art through the full album chain, so a playlist reaches the
|
||||
// network even with the m3u fetch off.
|
||||
It("calls the album image agents for its grid tiles when m3u art is disabled", func() {
|
||||
conf.Server.EnableM3UExternalAlbumArt = false
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.EnableM3UExternalAlbumArt = false
|
||||
c.CoverArtPriority = "external"
|
||||
})
|
||||
folderRepo.result = nil
|
||||
plRepo := tests.CreateMockPlaylistRepo()
|
||||
plRepo.SetData(model.Playlists{{ID: "plgrid", Name: "Playlist"}})
|
||||
@ -443,7 +440,7 @@ var _ = Describe("resolveItem", func() {
|
||||
|
||||
It("resolves the uploaded image before the generated grid", func() {
|
||||
tmpDir := GinkgoT().TempDir()
|
||||
conf.Server.DataFolder = conf.NewDir(tmpDir)
|
||||
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) })
|
||||
Expect(os.MkdirAll(filepath.Join(tmpDir, "artwork", "playlist"), 0755)).To(Succeed())
|
||||
imgPath := filepath.Join(tmpDir, "artwork", "playlist", "plu_test.jpg")
|
||||
Expect(os.WriteFile(imgPath, []byte("uploaded playlist image"), 0600)).To(Succeed())
|
||||
@ -516,7 +513,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("routes ExternalImageURL through extGate and sets extError on transient failure", func() {
|
||||
conf.Server.EnableM3UExternalAlbumArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true })
|
||||
folderRepo.result = nil // no grid tiles, so the external failure is what surfaces
|
||||
|
||||
plRepo := tests.CreateMockPlaylistRepo()
|
||||
@ -538,7 +535,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("records the m3u failure in the trace even when album sampling adds its own steps", func() {
|
||||
conf.Server.EnableM3UExternalAlbumArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true })
|
||||
folderRepo.result = nil // the sampled album yields no tile, so the m3u failure is what forced the retry
|
||||
|
||||
plRepo := tests.CreateMockPlaylistRepo()
|
||||
@ -583,7 +580,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("treats an ExternalImageURL 404 as a definitive miss and falls through to the grid", func() {
|
||||
conf.Server.EnableM3UExternalAlbumArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true })
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
@ -604,7 +601,7 @@ var _ = Describe("resolveItem", func() {
|
||||
|
||||
// A local resolver holds no agents: reaching the external branch would panic, not degrade.
|
||||
It("skips the external step instead of dereferencing absent agents", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum = tests.CreateMockAlbumRepo()
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alx", Name: "Album"}})
|
||||
|
||||
@ -616,7 +613,7 @@ var _ = Describe("resolveItem", func() {
|
||||
|
||||
// The worker resolving the same playlist is asserted alongside, so this cannot pass vacuously.
|
||||
It("resolves a playlist locally without fetching remotely or building the grid", func() {
|
||||
conf.Server.EnableM3UExternalAlbumArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true })
|
||||
var hits atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
hits.Add(1)
|
||||
@ -644,7 +641,7 @@ var _ = Describe("resolveItem", func() {
|
||||
})
|
||||
|
||||
It("treats an ExternalImageURL 500 as a transient failure and sets extError", func() {
|
||||
conf.Server.EnableM3UExternalAlbumArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true })
|
||||
folderRepo.result = nil // no grid tiles, so the external failure is what surfaces
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
@ -752,15 +749,18 @@ var _ = Describe("Explainable", func() {
|
||||
|
||||
var _ = Describe("MayFetchExternal", func() {
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.CoverArtPriority = "cover.*, embedded"
|
||||
conf.Server.ArtistArtPriority = "artist.*"
|
||||
conf.Server.EnableM3UExternalAlbumArt = false
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "cover.*, embedded"
|
||||
c.ArtistArtPriority = "artist.*"
|
||||
c.EnableM3UExternalAlbumArt = false
|
||||
})
|
||||
})
|
||||
|
||||
It("is true for the kinds whose chain includes the external candidate", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*, external"
|
||||
conf.Server.ArtistArtPriority = "artist.*, external"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "cover.*, external"
|
||||
c.ArtistArtPriority = "artist.*, external"
|
||||
})
|
||||
Expect(MayFetchExternal(model.KindAlbumArtwork)).To(BeTrue())
|
||||
Expect(MayFetchExternal(model.KindArtistArtwork)).To(BeTrue())
|
||||
})
|
||||
@ -771,12 +771,12 @@ var _ = Describe("MayFetchExternal", func() {
|
||||
})
|
||||
|
||||
It("is true for playlists when the m3u image fetch is enabled", func() {
|
||||
conf.Server.EnableM3UExternalAlbumArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true })
|
||||
Expect(MayFetchExternal(model.KindPlaylistArtwork)).To(BeTrue())
|
||||
})
|
||||
|
||||
It("is true for playlists whose grid tiles resolve through an external album chain", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*, external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*, external" })
|
||||
Expect(MayFetchExternal(model.KindPlaylistArtwork)).To(BeTrue())
|
||||
})
|
||||
|
||||
@ -785,9 +785,11 @@ var _ = Describe("MayFetchExternal", func() {
|
||||
})
|
||||
|
||||
It("is false for the kinds that only read local files", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Server.ArtistArtPriority = "external"
|
||||
conf.Server.EnableM3UExternalAlbumArt = true
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "external"
|
||||
c.ArtistArtPriority = "external"
|
||||
c.EnableM3UExternalAlbumArt = true
|
||||
})
|
||||
Expect(MayFetchExternal(model.KindRadioArtwork)).To(BeFalse())
|
||||
Expect(MayFetchExternal(model.KindMediaFileArtwork)).To(BeFalse())
|
||||
})
|
||||
@ -797,10 +799,11 @@ var _ = Describe("ExternalLookupsPerItem", func() {
|
||||
count := ImageAgentCount{Artist: 3, Album: 2}
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.CoverArtPriority = "cover.*, external"
|
||||
conf.Server.ArtistArtPriority = "artist.*, external"
|
||||
conf.Server.EnableM3UExternalAlbumArt = false
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "cover.*, external"
|
||||
c.ArtistArtPriority = "artist.*, external"
|
||||
c.EnableM3UExternalAlbumArt = false
|
||||
})
|
||||
})
|
||||
|
||||
It("bills one call per agent, since the walk only stops early on a hit", func() {
|
||||
@ -814,14 +817,16 @@ var _ = Describe("ExternalLookupsPerItem", func() {
|
||||
})
|
||||
|
||||
It("adds the m3u image fetch on top of the grid", func() {
|
||||
conf.Server.EnableM3UExternalAlbumArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true })
|
||||
Expect(ExternalLookupsPerItem(model.KindPlaylistArtwork, count)).
|
||||
To(Equal(int64(PlaylistGridSamples)*2 + 1))
|
||||
})
|
||||
|
||||
It("bills only the m3u fetch when the album chain stays local", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*"
|
||||
conf.Server.EnableM3UExternalAlbumArt = true
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "cover.*"
|
||||
c.EnableM3UExternalAlbumArt = true
|
||||
})
|
||||
Expect(ExternalLookupsPerItem(model.KindPlaylistArtwork, count)).To(Equal(int64(1)))
|
||||
})
|
||||
|
||||
@ -834,8 +839,10 @@ var _ = Describe("ExternalLookupsPerItem", func() {
|
||||
})
|
||||
|
||||
It("is zero whenever the kind reaches no agent at all", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*"
|
||||
conf.Server.ArtistArtPriority = "artist.*"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "cover.*"
|
||||
c.ArtistArtPriority = "artist.*"
|
||||
})
|
||||
Expect(ExternalLookupsPerItem(model.KindArtistArtwork, count)).To(BeZero())
|
||||
Expect(ExternalLookupsPerItem(model.KindAlbumArtwork, count)).To(BeZero())
|
||||
Expect(ExternalLookupsPerItem(model.KindPlaylistArtwork, count)).To(BeZero())
|
||||
|
||||
@ -10,7 +10,6 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
@ -212,8 +211,7 @@ var _ = Describe("resolveAlbum tracing", func() {
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.CoverArtPriority = "cover.jpg, embedded"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg, embedded" })
|
||||
repoRoot, err := os.Getwd()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
libRepo := &tests.MockLibraryRepo{}
|
||||
@ -266,7 +264,7 @@ var _ = Describe("resolveAlbum tracing", func() {
|
||||
})
|
||||
|
||||
It("ignores an empty priority token", func() {
|
||||
conf.Server.CoverArtPriority = "cover.jpg,"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg," })
|
||||
albumRepo.SetData(model.Albums{{ID: "al2", Name: "Album", FolderIDs: []string{"f1"}}})
|
||||
|
||||
_, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al2"})
|
||||
@ -298,9 +296,10 @@ var _ = Describe("resolveArtist tracing", func() {
|
||||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.DataFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
conf.Server.ArtistArtPriority = "album/artist.*"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DataFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
c.ArtistArtPriority = "album/artist.*"
|
||||
})
|
||||
var err error
|
||||
repoRoot, err = os.Getwd()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
@ -372,7 +371,7 @@ var _ = Describe("resolveArtist tracing", func() {
|
||||
})
|
||||
|
||||
It("records why an artist folder pattern was skipped", func() {
|
||||
conf.Server.ArtistArtPriority = "artist.*"
|
||||
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "artist.*" })
|
||||
artistRepo.SetData(model.Artists{{ID: "ar6", Name: "Artist"}})
|
||||
albumRepo.All = model.Albums{{ID: "al10", Name: "Album", LibraryID: 0, FolderIDs: []string{"f1"}}}
|
||||
|
||||
@ -413,10 +412,11 @@ var _ = Describe("NewTracingResolver", func() {
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.DataFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
conf.Server.CoverArtPriority = "external, embedded"
|
||||
conf.Server.ArtistArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DataFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
c.CoverArtPriority = "external, embedded"
|
||||
c.ArtistArtPriority = "external"
|
||||
})
|
||||
repoRoot, err := os.Getwd()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
libRepo := &tests.MockLibraryRepo{}
|
||||
@ -487,7 +487,7 @@ var _ = Describe("NewTracingResolver", func() {
|
||||
})
|
||||
|
||||
It("closes the reader it does not hand back", func() {
|
||||
conf.Server.CoverArtPriority = "embedded"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "embedded" })
|
||||
ffm = tests.NewMockFFmpeg("fake image bytes")
|
||||
albumRepo.SetData(model.Albums{{
|
||||
ID: "al2", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/no-such-file.mp3", FolderIDs: []string{"f1"},
|
||||
@ -503,9 +503,11 @@ var _ = Describe("NewTracingResolver", func() {
|
||||
// Serving falls back disc -> album and track -> disc -> album. The resolver does not, but
|
||||
// if it ever did, an explain without --live would start calling providers uninvited.
|
||||
It("cannot reach a provider without live, whatever the chain does", func() {
|
||||
conf.Server.DiscArtPriority = "external, cover.*"
|
||||
conf.Server.CoverArtPriority = "external, cover.*"
|
||||
conf.Server.EnableMediaFileCoverArt = true
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DiscArtPriority = "external, cover.*"
|
||||
c.CoverArtPriority = "external, cover.*"
|
||||
c.EnableMediaFileCoverArt = true
|
||||
})
|
||||
mfRepo := tests.CreateMockMediaFileRepo()
|
||||
mfRepo.SetData(model.MediaFiles{{ID: "mf1", LibraryID: 0, HasCoverArt: true,
|
||||
Path: "tests/fixtures/artist/an-album/test.mp3"}})
|
||||
@ -539,7 +541,6 @@ var _ = Describe("resolveDisc tracing", func() {
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
repoRoot, err := os.Getwd()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
libRepo := &tests.MockLibraryRepo{}
|
||||
@ -561,7 +562,7 @@ var _ = Describe("resolveDisc tracing", func() {
|
||||
})
|
||||
|
||||
It("accounts for every configured entry, including the ones that map to no source", func() {
|
||||
conf.Server.DiscArtPriority = "external, discsubtitle, cover.jpg"
|
||||
conf.Update(func(c *conf.Options) { c.DiscArtPriority = "external, discsubtitle, cover.jpg" })
|
||||
|
||||
res, err := newResolver(ds, nil, ffm, nil).resolveDisc(ctx, model.DiscArtworkID("al1", 2))
|
||||
|
||||
@ -575,7 +576,7 @@ var _ = Describe("resolveDisc tracing", func() {
|
||||
})
|
||||
|
||||
It("records the entry that won and stops there", func() {
|
||||
conf.Server.DiscArtPriority = "disc*.*, cover.jpg, embedded"
|
||||
conf.Update(func(c *conf.Options) { c.DiscArtPriority = "disc*.*, cover.jpg, embedded" })
|
||||
folderRepo.result = []model.Folder{{
|
||||
Path: "tests/fixtures/artist/an-album",
|
||||
ImageFiles: []string{"cover.jpg"},
|
||||
@ -597,7 +598,7 @@ var _ = Describe("resolveDisc tracing", func() {
|
||||
})
|
||||
|
||||
It("reports an unparseable disc id rather than explaining another disc", func() {
|
||||
conf.Server.DiscArtPriority = "cover.jpg"
|
||||
conf.Update(func(c *conf.Options) { c.DiscArtPriority = "cover.jpg" })
|
||||
_, err := newResolver(ds, nil, ffm, nil).resolveDisc(ctx, "al1")
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
@ -613,8 +614,7 @@ var _ = Describe("resolveMediaFile tracing", func() {
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.EnableMediaFileCoverArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
|
||||
repoRoot, err := os.Getwd()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
libRepo := &tests.MockLibraryRepo{}
|
||||
@ -630,7 +630,7 @@ var _ = Describe("resolveMediaFile tracing", func() {
|
||||
})
|
||||
|
||||
It("separates a disabled setting from a track with nothing embedded", func() {
|
||||
conf.Server.EnableMediaFileCoverArt = false
|
||||
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false })
|
||||
|
||||
_, err := newResolver(ds, nil, ffm, nil).resolveMediaFile(ctx, "mf1")
|
||||
|
||||
|
||||
@ -17,7 +17,7 @@ import (
|
||||
|
||||
// MaxImageUploadSize returns the configured max upload size in bytes, or the built-in default.
|
||||
func MaxImageUploadSize() int64 {
|
||||
return parseSize(conf.Server.MaxImageUploadSize, consts.DefaultMaxImageUploadSize)
|
||||
return parseSize(conf.Server().MaxImageUploadSize, consts.DefaultMaxImageUploadSize)
|
||||
}
|
||||
|
||||
func parseSize(value, fallback string) int64 {
|
||||
|
||||
@ -7,7 +7,6 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
@ -24,9 +23,8 @@ var _ = Describe("Uploader", func() {
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
tmpDir = GinkgoT().TempDir()
|
||||
conf.Server.DataFolder = conf.NewDir(tmpDir)
|
||||
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) })
|
||||
artRepo = tests.CreateMockArtworkRepo()
|
||||
queueRepo = tests.CreateMockArtworkQueueRepo()
|
||||
ds := &tests.MockDataStore{MockedArtwork: artRepo, MockedArtworkQueue: queueRepo}
|
||||
@ -141,27 +139,24 @@ var _ = Describe("Uploader", func() {
|
||||
})
|
||||
|
||||
var _ = Describe("MaxImageUploadSize", func() {
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
})
|
||||
|
||||
It("returns the configured size when valid", func() {
|
||||
conf.Server.MaxImageUploadSize = "20MB"
|
||||
conf.Update(func(c *conf.Options) { c.MaxImageUploadSize = "20MB" })
|
||||
Expect(MaxImageUploadSize()).To(Equal(int64(20_000_000)))
|
||||
})
|
||||
|
||||
It("returns the default size when config is empty", func() {
|
||||
conf.Server.MaxImageUploadSize = ""
|
||||
conf.Update(func(c *conf.Options) { c.MaxImageUploadSize = "" })
|
||||
Expect(MaxImageUploadSize()).To(Equal(int64(10_000_000)))
|
||||
})
|
||||
|
||||
It("returns the default size when config is invalid", func() {
|
||||
conf.Server.MaxImageUploadSize = "not-a-size"
|
||||
conf.Update(func(c *conf.Options) { c.MaxImageUploadSize = "not-a-size" })
|
||||
Expect(MaxImageUploadSize()).To(Equal(int64(10_000_000)))
|
||||
})
|
||||
|
||||
It("parses raw byte values", func() {
|
||||
conf.Server.MaxImageUploadSize = "52428800"
|
||||
conf.Update(func(c *conf.Options) { c.MaxImageUploadSize = "52428800" })
|
||||
Expect(MaxImageUploadSize()).To(Equal(int64(52_428_800)))
|
||||
})
|
||||
})
|
||||
|
||||
@ -74,9 +74,9 @@ func NewWorker(ds model.DataStore, store *ImageStore, ag *agents.Agents, ffmpeg
|
||||
// rate-limit permit, so a sleeping lookup would crowd out a cover sitting on disk.
|
||||
func newDrainPools() []*drainPool {
|
||||
budget := conf.MaxOpenConns() // floored at 4, so both remainders below stay positive
|
||||
local := min(max(1, conf.Server.DevArtworkWorkerConcurrency), budget-1)
|
||||
local := min(max(1, conf.Server().DevArtworkWorkerConcurrency), budget-1)
|
||||
// More external slots than the rate allows would only sleep in the limiter.
|
||||
external := min(max(2, 2*conf.Server.DevArtworkExternalMaxRPS), budget-local)
|
||||
external := min(max(2, 2*conf.Server().DevArtworkExternalMaxRPS), budget-local)
|
||||
return []*drainPool{
|
||||
{name: "local", kinds: localDrainKinds, concurrency: local},
|
||||
{name: "external", kinds: externalDrainKinds, concurrency: external},
|
||||
@ -326,7 +326,7 @@ func (w *Worker) hasResolvedArtwork(ctx context.Context, item model.ArtworkQueue
|
||||
// precache warms the resize cache at the UI cover size from the bytes just acquired, so the
|
||||
// first UI request hits without re-reading the rows or the file.
|
||||
func (w *Worker) precache(ctx context.Context, got *acquired) {
|
||||
if !conf.Server.EnableArtworkPrecache || w.cache == nil || w.cache.Disabled(ctx) {
|
||||
if !conf.Server().EnableArtworkPrecache || w.cache == nil || w.cache.Disabled(ctx) {
|
||||
return
|
||||
}
|
||||
precacheStart := time.Now()
|
||||
@ -334,7 +334,7 @@ func (w *Worker) precache(ctx context.Context, got *acquired) {
|
||||
// warms a key nothing reads.
|
||||
item := &resizedItem{
|
||||
hash: got.ia.Hash,
|
||||
size: conf.Server.UICoverArtSize,
|
||||
size: conf.Server().UICoverArtSize,
|
||||
square: true,
|
||||
ffmpeg: w.ffmpeg,
|
||||
open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(got.data)), nil },
|
||||
@ -347,7 +347,7 @@ func (w *Worker) precache(ctx context.Context, got *acquired) {
|
||||
_, _ = io.Copy(io.Discard, stream)
|
||||
_ = stream.Close()
|
||||
log.Trace(ctx, "Artwork: Precached UI size", "kind", got.ia.ItemKind, "id", got.ia.ItemID,
|
||||
"size", conf.Server.UICoverArtSize, "elapsed", time.Since(precacheStart))
|
||||
"size", conf.Server().UICoverArtSize, "elapsed", time.Since(precacheStart))
|
||||
}
|
||||
|
||||
// backoffFor returns min(5s×4^n, giveUpAfter) scaled by (1+jitter), with jitter in [-0.4, 0.4].
|
||||
|
||||
@ -9,7 +9,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
@ -31,7 +30,6 @@ var _ = Describe("Worker soak", func() {
|
||||
if testing.Short() {
|
||||
Skip("skipping soak test in short mode")
|
||||
}
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
|
||||
repoRoot, err := os.Getwd()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
@ -58,7 +56,7 @@ var _ = Describe("Worker soak", func() {
|
||||
}
|
||||
store := NewImageStore(GinkgoT().TempDir())
|
||||
proc := &processor{ds: ds, store: store, resolver: newResolver(ds, ag, ffm, nil)}
|
||||
conf.Server.CoverArtPriority = "cover.jpg, embedded"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg, embedded" })
|
||||
|
||||
// Dangling refs mirror an entity deleted after being enqueued.
|
||||
items := []model.ArtworkQueueItem{
|
||||
|
||||
@ -12,7 +12,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/model/request"
|
||||
@ -179,11 +178,10 @@ var _ = Describe("Worker", func() {
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
var err error
|
||||
repoRoot, err = os.Getwd()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
conf.Server.CacheFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
conf.Update(func(c *conf.Options) { c.CacheFolder = conf.NewDir(GinkgoT().TempDir()) })
|
||||
|
||||
folderRepo = &fakeFolderRepo{}
|
||||
libRepo = &tests.MockLibraryRepo{}
|
||||
@ -200,8 +198,10 @@ var _ = Describe("Worker", func() {
|
||||
}
|
||||
ds.MockedAlbum = tests.CreateMockAlbumRepo()
|
||||
store = NewImageStore(GinkgoT().TempDir())
|
||||
conf.Server.CoverArtPriority = "cover.jpg, embedded"
|
||||
conf.Server.DevArtworkExternalMaxRPS = 1000 // keep the limiter out of the way of behavior tests
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "cover.jpg, embedded"
|
||||
c.DevArtworkExternalMaxRPS = 1000
|
||||
}) // keep the limiter out of the way of behavior tests
|
||||
broker = &fakeEventBroker{}
|
||||
imgCache = &recordingCache{FileCache: cache.NewFileCache("WorkerTest", "100MB", "images", 0,
|
||||
func(ctx context.Context, arg cache.Item) (io.Reader, error) {
|
||||
@ -239,7 +239,7 @@ var _ = Describe("Worker", func() {
|
||||
})
|
||||
|
||||
It("processes an mf queue item, writing state and storing embedded bytes", func() {
|
||||
conf.Server.EnableMediaFileCoverArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
|
||||
ds.MockedMediaFile = tests.CreateMockMediaFileRepo()
|
||||
ds.MockedMediaFile.(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
|
||||
{ID: "mf1", LibraryID: 0, Path: "tests/fixtures/artist/an-album/test.mp3", HasCoverArt: true},
|
||||
@ -272,7 +272,7 @@ var _ = Describe("Worker", func() {
|
||||
})
|
||||
|
||||
It("reschedules a failed item via MarkFailed with a backed-off retry_at", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al4", Name: "Album"}})
|
||||
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
|
||||
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al4"})).To(Succeed())
|
||||
@ -321,7 +321,7 @@ var _ = Describe("Worker", func() {
|
||||
})
|
||||
|
||||
It("reschedules past the provider's requested delay when it exceeds the backoff", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al9", Name: "Album"}})
|
||||
// Well above backoff(0)'s jittered ceiling, so only the hint can produce this retry_at.
|
||||
const askedFor = 90 * time.Minute
|
||||
@ -338,7 +338,7 @@ var _ = Describe("Worker", func() {
|
||||
})
|
||||
|
||||
It("reschedules a found-stale item via MarkFailed while keeping its served state", func() {
|
||||
conf.Server.CoverArtPriority = "external, cover.jpg"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external, cover.jpg" })
|
||||
folderRepo.result = []model.Folder{{
|
||||
Path: "tests/fixtures/artist/an-album",
|
||||
ImageFiles: []string{"cover.jpg"},
|
||||
@ -394,7 +394,7 @@ var _ = Describe("Worker", func() {
|
||||
})
|
||||
|
||||
It("keeps a fresh re-enqueue ahead of a stale failure backoff", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al8", Name: "Album"}})
|
||||
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
|
||||
racing := &reenqueueOnDequeue{MockArtworkQueueRepo: queueRepo}
|
||||
@ -415,7 +415,7 @@ var _ = Describe("Worker", func() {
|
||||
})
|
||||
|
||||
It("gives up and settles absent once the retry budget is exhausted", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al9", Name: "Album"}})
|
||||
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
|
||||
w = NewWorker(ds, store, ag, ffm, broker, imgCache)
|
||||
@ -434,7 +434,7 @@ var _ = Describe("Worker", func() {
|
||||
})
|
||||
|
||||
It("keeps already-served art when the retry budget is exhausted", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al10", Name: "Album"}})
|
||||
Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{
|
||||
ItemKind: "al", ItemID: "al10", ImageType: model.ImageTypePrimary,
|
||||
@ -456,7 +456,7 @@ var _ = Describe("Worker", func() {
|
||||
})
|
||||
|
||||
It("records on the queue row why the last attempt failed", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al11", Name: "Album"}})
|
||||
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
|
||||
w = NewWorker(ds, store, ag, ffm, broker, imgCache)
|
||||
@ -477,7 +477,7 @@ var _ = Describe("Worker", func() {
|
||||
// The give-up path settles absent before recording, so the row exists by the time the
|
||||
// failure is written. Recording first would silently lose it for every unresolved item.
|
||||
It("keeps the failure for an item that never resolved at all", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al13", Name: "Album"}})
|
||||
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
|
||||
w = NewWorker(ds, store, ag, ffm, broker, imgCache)
|
||||
@ -494,7 +494,7 @@ var _ = Describe("Worker", func() {
|
||||
})
|
||||
|
||||
It("keeps the failure on the state row after the queue row is deleted", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al12", Name: "Album"}})
|
||||
Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{
|
||||
ItemKind: "al", ItemID: "al12", ImageType: model.ImageTypePrimary,
|
||||
@ -519,7 +519,7 @@ var _ = Describe("Worker", func() {
|
||||
// Only a view enqueues a media file, and an absent row is exactly what stops a view from
|
||||
// doing so: a transient read error would look permanent.
|
||||
It("does not settle absent on exhaustion for a media file", func() {
|
||||
conf.Server.EnableMediaFileCoverArt = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
|
||||
ds.MockedMediaFile = tests.CreateMockMediaFileRepo()
|
||||
ds.MockedMediaFile.(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
|
||||
{ID: "mfX", LibraryID: 0, Path: "tests/fixtures/artist/an-album/gone.mp3", HasCoverArt: true},
|
||||
@ -620,7 +620,7 @@ var _ = Describe("Worker", func() {
|
||||
)
|
||||
|
||||
It("broadcasts a refresh when an item resolves to absent (removed cover)", func() {
|
||||
conf.Server.CoverArtPriority = "cover.*" // local-only; no folder image → absent
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*" }) // local-only; no folder image → absent
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al3", Name: "Artless"}})
|
||||
folderRepo.result = nil
|
||||
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al3", Priority: model.ArtworkPriorityScan})).To(Succeed())
|
||||
@ -639,7 +639,7 @@ var _ = Describe("Worker", func() {
|
||||
})
|
||||
|
||||
It("does not broadcast when no item is found", func() {
|
||||
conf.Server.CoverArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alx", Name: "Album"}})
|
||||
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
|
||||
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alx"})).To(Succeed())
|
||||
@ -775,14 +775,14 @@ var _ = Describe("Worker", func() {
|
||||
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
|
||||
{ID: "alpc", Name: "Album", FolderIDs: []string{"f1"}},
|
||||
})
|
||||
conf.Server.UICoverArtSize = 300
|
||||
conf.Update(func(c *conf.Options) { c.UICoverArtSize = 300 })
|
||||
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
|
||||
ItemKind: "al", ItemID: "alpc", Priority: model.ArtworkPriorityScan,
|
||||
})).To(Succeed())
|
||||
})
|
||||
|
||||
It("warms the resize cache at the UI cover size after a found acquisition", func() {
|
||||
conf.Server.EnableArtworkPrecache = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableArtworkPrecache = true })
|
||||
|
||||
n, err := w.drain(ctx, 1)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
@ -793,7 +793,7 @@ var _ = Describe("Worker", func() {
|
||||
})
|
||||
|
||||
It("skips warming when precache is disabled", func() {
|
||||
conf.Server.EnableArtworkPrecache = false
|
||||
conf.Update(func(c *conf.Options) { c.EnableArtworkPrecache = false })
|
||||
|
||||
n, err := w.drain(ctx, 1)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
@ -804,7 +804,7 @@ var _ = Describe("Worker", func() {
|
||||
|
||||
// It warms from the bytes acquisition already held, so no state row or store file is needed.
|
||||
It("warms from the acquired bytes without reading them back", func() {
|
||||
conf.Server.EnableArtworkPrecache = true
|
||||
conf.Update(func(c *conf.Options) { c.EnableArtworkPrecache = true })
|
||||
ia := &model.ItemArtwork{
|
||||
ItemKind: "al", ItemID: "unpersisted", ImageType: model.ImageTypePrimary,
|
||||
Hash: "abcdef0123456789", UpdatedAt: time.Now(),
|
||||
@ -844,8 +844,10 @@ var _ = Describe("Worker", func() {
|
||||
// Artists resolve through a rate-limited agent that holds its slot while waiting, so one
|
||||
// shared pool would park every album behind them.
|
||||
It("resolves albums while artists are stuck on a slow agent", func() {
|
||||
conf.Server.CoverArtPriority = "cover.jpg"
|
||||
conf.Server.ArtistArtPriority = "external"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "cover.jpg"
|
||||
c.ArtistArtPriority = "external"
|
||||
})
|
||||
folderRepo.result = []model.Folder{{
|
||||
Path: "tests/fixtures/artist/an-album",
|
||||
ImageFiles: []string{"cover.jpg"},
|
||||
@ -875,7 +877,7 @@ var _ = Describe("Worker", func() {
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); _ = w.Run(runCtx) }()
|
||||
// Join Run: a leaked pool goroutine would race the config snapshot Ginkgo restores.
|
||||
// Join Run so no pool goroutine outlives the spec.
|
||||
DeferCleanup(func() {
|
||||
cancel()
|
||||
close(block) // unpark the blocked lookups so the pools can unwind
|
||||
@ -1000,7 +1002,6 @@ var _ = Describe("Worker", func() {
|
||||
})
|
||||
|
||||
It("does not leak goroutines after Run exits", func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
|
||||
ignore := goleak.IgnoreCurrent()
|
||||
DeferCleanup(func() { goleak.VerifyNone(GinkgoT(), ignore) })
|
||||
|
||||
@ -40,7 +40,7 @@ const (
|
||||
func Init(ds model.DataStore) {
|
||||
once.Do(func() {
|
||||
ctx := context.TODO()
|
||||
log.Info("Setting Session Timeout", "value", conf.Server.SessionTimeout)
|
||||
log.Info("Setting Session Timeout", "value", conf.Server().SessionTimeout)
|
||||
|
||||
TokenAuth = jwtauth.New("HS256", []byte(loadOrCreateSecret(ctx, ds, consts.JWTSecretKey)), nil)
|
||||
PublicTokenAuth = jwtauth.New("HS256", []byte(loadOrCreateSecret(ctx, ds, consts.JWTPublicSecretKey)), nil)
|
||||
@ -108,7 +108,7 @@ func TouchToken(token jwt.Token) (string, error) {
|
||||
}
|
||||
|
||||
func TouchClaims(c Claims) (string, error) {
|
||||
c = c.WithExpiresAt(time.Now().UTC().Add(conf.Server.SessionTimeout))
|
||||
c = c.WithExpiresAt(time.Now().UTC().Add(conf.Server().SessionTimeout))
|
||||
_, newToken, err := TokenAuth.Encode(c.ToMap())
|
||||
return newToken, err
|
||||
}
|
||||
@ -198,7 +198,7 @@ func DecodeAndVerifyToken(tokenStr string) (jwt.Token, error) {
|
||||
|
||||
func EncryptionKey() []byte {
|
||||
key := cmp.Or(
|
||||
conf.Server.PasswordEncryptionKey,
|
||||
conf.Server().PasswordEncryptionKey,
|
||||
consts.DefaultEncryptionKey,
|
||||
)
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
|
||||
@ -5,6 +5,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/core/auth"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
@ -21,12 +22,14 @@ func TestAuth(t *testing.T) {
|
||||
RunSpecs(t, "Auth Test Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
const (
|
||||
oneDay = 24 * time.Hour
|
||||
)
|
||||
|
||||
var _ = BeforeSuite(func() {
|
||||
conf.Server.SessionTimeout = 2 * oneDay
|
||||
conf.Update(func(c *conf.Options) { c.SessionTimeout = 2 * oneDay })
|
||||
})
|
||||
|
||||
var _ = Describe("Auth", func() {
|
||||
|
||||
@ -3,6 +3,7 @@ package core
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -15,3 +16,5 @@ func TestCore(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Core Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
3
core/external/extdata_suite_test.go
vendored
3
core/external/extdata_suite_test.go
vendored
@ -3,6 +3,7 @@ package external
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -15,3 +16,5 @@ func TestExternal(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "External Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
8
core/external/provider.go
vendored
8
core/external/provider.go
vendored
@ -54,7 +54,7 @@ type auxAlbum struct {
|
||||
// Name returns the appropriate album name for external API calls
|
||||
// based on the DevPreserveUnicodeInExternalCalls configuration option
|
||||
func (a *auxAlbum) Name() string {
|
||||
if conf.Server.DevPreserveUnicodeInExternalCalls {
|
||||
if conf.Server().DevPreserveUnicodeInExternalCalls {
|
||||
return a.Album.Name
|
||||
}
|
||||
return str.Clear(a.Album.Name)
|
||||
@ -67,7 +67,7 @@ type auxArtist struct {
|
||||
// Name returns the appropriate artist name for external API calls
|
||||
// based on the DevPreserveUnicodeInExternalCalls configuration option
|
||||
func (a *auxArtist) Name() string {
|
||||
if conf.Server.DevPreserveUnicodeInExternalCalls {
|
||||
if conf.Server().DevPreserveUnicodeInExternalCalls {
|
||||
return a.Artist.Name
|
||||
}
|
||||
return str.Clear(a.Artist.Name)
|
||||
@ -136,7 +136,7 @@ func (e *provider) UpdateAlbumInfo(ctx context.Context, id string) (*model.Album
|
||||
}
|
||||
|
||||
// If info is expired, trigger a populateAlbumInfo in the background
|
||||
if time.Since(updatedAt) > conf.Server.DevAlbumInfoTimeToLive {
|
||||
if time.Since(updatedAt) > conf.Server().DevAlbumInfoTimeToLive {
|
||||
log.Debug("Found expired cached AlbumInfo, refreshing in the background", "updatedAt", album.ExternalInfoUpdatedAt, "name", albumName)
|
||||
e.albumQueue.enqueue(&album)
|
||||
}
|
||||
@ -243,7 +243,7 @@ func (e *provider) refreshArtistInfo(ctx context.Context, id string) (auxArtist,
|
||||
}
|
||||
|
||||
// If info is expired, trigger a populateArtistInfo in the background
|
||||
if time.Since(updatedAt) > conf.Server.DevArtistInfoTimeToLive {
|
||||
if time.Since(updatedAt) > conf.Server().DevArtistInfoTimeToLive {
|
||||
log.Debug("Found expired cached ArtistInfo, refreshing in the background", "updatedAt", updatedAt, "name", artistName)
|
||||
e.artistQueue.enqueue(&artist)
|
||||
}
|
||||
|
||||
4
core/external/provider_topsongs_test.go
vendored
4
core/external/provider_topsongs_test.go
vendored
@ -7,7 +7,6 @@ import (
|
||||
_ "github.com/navidrome/navidrome/adapters/lastfm"
|
||||
_ "github.com/navidrome/navidrome/adapters/listenbrainz"
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
. "github.com/navidrome/navidrome/core/external"
|
||||
"github.com/navidrome/navidrome/core/matcher"
|
||||
@ -28,9 +27,8 @@ var _ = Describe("Provider - TopSongs", func() {
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
// Disable fuzzy matching for these tests to avoid unexpected GetAll calls
|
||||
conf.Server.Matcher.FuzzyThreshold = 100
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 })
|
||||
|
||||
ctx = GinkgoT().Context()
|
||||
|
||||
|
||||
@ -36,7 +36,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() {
|
||||
ag = new(mockAgents)
|
||||
p = external.NewProvider(ds, ag, matcher.New(ds), &fakeBroker{})
|
||||
mockAlbumRepo = ds.Album().(*tests.MockAlbumRepo)
|
||||
conf.Server.DevAlbumInfoTimeToLive = 1 * time.Hour
|
||||
conf.Update(func(c *conf.Options) { c.DevAlbumInfoTimeToLive = 1 * time.Hour })
|
||||
})
|
||||
|
||||
It("returns error when album is not found", func() {
|
||||
@ -89,7 +89,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() {
|
||||
ExternalUrl: "http://cached.com/album",
|
||||
Description: "Cached Desc",
|
||||
LargeImageUrl: "http://cached.com/large.jpg",
|
||||
ExternalInfoUpdatedAt: new(now.Add(-conf.Server.DevAlbumInfoTimeToLive / 2)),
|
||||
ExternalInfoUpdatedAt: new(now.Add(-conf.Server().DevAlbumInfoTimeToLive / 2)),
|
||||
}
|
||||
mockAlbumRepo.SetData(model.Albums{*originalAlbum})
|
||||
|
||||
@ -104,7 +104,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() {
|
||||
|
||||
It("returns cached info and triggers background refresh when info is expired", func() {
|
||||
now := time.Now()
|
||||
expiredTime := now.Add(-conf.Server.DevAlbumInfoTimeToLive * 2)
|
||||
expiredTime := now.Add(-conf.Server().DevAlbumInfoTimeToLive * 2)
|
||||
originalAlbum := &model.Album{
|
||||
ID: "al-expired",
|
||||
Name: "Expired Album",
|
||||
|
||||
10
core/external/provider_updateartistinfo_test.go
vendored
10
core/external/provider_updateartistinfo_test.go
vendored
@ -6,7 +6,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/core/external"
|
||||
"github.com/navidrome/navidrome/core/matcher"
|
||||
@ -32,8 +31,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.DevArtistInfoTimeToLive = 1 * time.Hour
|
||||
conf.Update(func(c *conf.Options) { c.DevArtistInfoTimeToLive = 1 * time.Hour })
|
||||
ctx = GinkgoT().Context()
|
||||
ds = new(tests.MockDataStore)
|
||||
ag = new(mockAgents)
|
||||
@ -155,7 +153,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
|
||||
ExternalUrl: "http://cached.url",
|
||||
Biography: "Cached Bio",
|
||||
LargeImageUrl: "http://cached_large.jpg",
|
||||
ExternalInfoUpdatedAt: new(now.Add(-conf.Server.DevArtistInfoTimeToLive / 2)),
|
||||
ExternalInfoUpdatedAt: new(now.Add(-conf.Server().DevArtistInfoTimeToLive / 2)),
|
||||
SimilarArtists: model.Artists{
|
||||
{ID: "ar-similar-present", Name: "Similar Present"},
|
||||
{ID: "ar-similar-absent", Name: "Similar Absent"},
|
||||
@ -188,7 +186,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
|
||||
|
||||
It("returns cached info and triggers background refresh when info is expired", func() {
|
||||
now := time.Now()
|
||||
expiredTime := now.Add(-conf.Server.DevArtistInfoTimeToLive * 2)
|
||||
expiredTime := now.Add(-conf.Server().DevArtistInfoTimeToLive * 2)
|
||||
originalArtist := &model.Artist{
|
||||
ID: "ar-expired",
|
||||
Name: "Expired Artist",
|
||||
@ -223,7 +221,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
|
||||
originalArtist := &model.Artist{
|
||||
ID: "ar-similar-test",
|
||||
Name: "Similar Test Artist",
|
||||
ExternalInfoUpdatedAt: new(now.Add(-conf.Server.DevArtistInfoTimeToLive / 2)),
|
||||
ExternalInfoUpdatedAt: new(now.Add(-conf.Server().DevArtistInfoTimeToLive / 2)),
|
||||
SimilarArtists: model.Artists{
|
||||
{ID: "ar-sim-present", Name: "Similar Present"},
|
||||
{ID: "", Name: "Similar Absent Raw"},
|
||||
|
||||
@ -32,7 +32,7 @@ type TranscodeOptions struct {
|
||||
Channels int // 0 = no constraint
|
||||
BitDepth int // 0 = no constraint; valid values: 16, 24, 32
|
||||
Offset int // seconds
|
||||
Duration float32 // seconds; 0 = unknown. Only used to repair a piped FLAC header.
|
||||
Duration float32 // seconds; 0 = unknown. Only used to repair a header ffmpeg piped out unfinished.
|
||||
}
|
||||
|
||||
// AudioProbeResult contains authoritative audio stream properties from ffprobe.
|
||||
@ -89,7 +89,7 @@ func (e *ffmpeg) Transcode(ctx context.Context, opts TranscodeOptions) (io.ReadC
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return patchFLACDuration(out, opts.Duration-float32(opts.Offset)), nil
|
||||
return patchPipedHeader(out, opts.Duration-float32(opts.Offset)), nil
|
||||
}
|
||||
|
||||
func (e *ffmpeg) ConvertAnimatedImage(ctx context.Context, reader io.Reader, maxSize int, quality int) (io.ReadCloser, error) {
|
||||
@ -603,8 +603,8 @@ func ffprobePath(ffmpegCmd string) string {
|
||||
|
||||
func ffmpegCmd() (string, error) {
|
||||
ffOnce.Do(func() {
|
||||
if conf.Server.FFmpegPath != "" {
|
||||
ffmpegPath = conf.Server.FFmpegPath
|
||||
if conf.Server().FFmpegPath != "" {
|
||||
ffmpegPath = conf.Server().FFmpegPath
|
||||
ffmpegPath, ffmpegErr = exec.LookPath(ffmpegPath)
|
||||
} else {
|
||||
ffmpegPath, ffmpegErr = exec.LookPath("ffmpeg")
|
||||
|
||||
@ -1,7 +1,9 @@
|
||||
package ffmpeg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
@ -712,6 +714,23 @@ var _ = Describe("ffmpeg", func() {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(readTotalSamples(out)).To(Equal(uint64(2 * 44100)))
|
||||
})
|
||||
|
||||
It("inserts an Info frame on a piped mp3 transcode", func() {
|
||||
stream, err := ff.Transcode(GinkgoT().Context(), TranscodeOptions{
|
||||
Command: "ffmpeg -i %s -map 0:a:0 -v 0 -b:a 128k -f mp3 -",
|
||||
Format: "mp3",
|
||||
FilePath: "tests/fixtures/test.flac",
|
||||
Duration: 1, // the fixture is exactly 1s at 44100Hz
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
defer stream.Close()
|
||||
|
||||
out, err := io.ReadAll(stream)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
at := bytes.Index(out, []byte("Info"))
|
||||
Expect(at).To(BeNumerically(">", 0))
|
||||
Expect(binary.BigEndian.Uint32(out[at+8:])).To(Equal(uint32(38)))
|
||||
})
|
||||
})
|
||||
|
||||
Context("stderr capture", func() {
|
||||
|
||||
@ -1,10 +1,7 @@
|
||||
package ffmpeg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
)
|
||||
|
||||
@ -13,43 +10,21 @@ const (
|
||||
flacMaxTotalSamples = 1<<36 - 1
|
||||
)
|
||||
|
||||
// patchFLACDuration fills in the STREAMINFO total_samples that ffmpeg leaves at 0
|
||||
// when writing to a pipe, since a decoder cannot seek a cached FLAC without it.
|
||||
func patchFLACDuration(r io.ReadCloser, duration float32) io.ReadCloser {
|
||||
if duration <= 0 {
|
||||
return r
|
||||
// flacPrefix fills in the STREAMINFO total_samples that ffmpeg leaves at 0 when
|
||||
// writing to a pipe, since a decoder cannot seek a cached FLAC without it.
|
||||
func (h *headerPatcher) flacPrefix(buf []byte) ([]byte, error) {
|
||||
buf, err := h.fill(buf, flacPrefixLen)
|
||||
if err != nil || len(buf) < flacPrefixLen {
|
||||
return buf, err
|
||||
}
|
||||
return &flacPatcher{ReadCloser: r, duration: duration}
|
||||
}
|
||||
|
||||
type flacPatcher struct {
|
||||
io.ReadCloser
|
||||
duration float32
|
||||
// Peeking here rather than in the constructor keeps Transcode from blocking
|
||||
// until ffmpeg has emitted its first bytes.
|
||||
stream io.Reader
|
||||
}
|
||||
|
||||
func (f *flacPatcher) Read(p []byte) (int, error) {
|
||||
if f.stream == nil {
|
||||
prefix := make([]byte, flacPrefixLen)
|
||||
n, err := io.ReadFull(f.ReadCloser, prefix)
|
||||
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return 0, err
|
||||
}
|
||||
prefix = prefix[:n]
|
||||
if err == nil {
|
||||
setFLACTotalSamples(prefix, f.duration)
|
||||
}
|
||||
f.stream = io.MultiReader(bytes.NewReader(prefix), f.ReadCloser)
|
||||
}
|
||||
return f.stream.Read(p)
|
||||
setFLACTotalSamples(buf, h.duration)
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// setFLACTotalSamples takes the rate from the header rather than the transcode
|
||||
// options, so a resampled (-ar) output still gets the right count.
|
||||
func setFLACTotalSamples(prefix []byte, duration float32) {
|
||||
if string(prefix[:4]) != "fLaC" || prefix[4]&0x7F != 0 {
|
||||
if prefix[4]&0x7F != 0 { // the first metadata block must be STREAMINFO
|
||||
return
|
||||
}
|
||||
// 20-bit rate | 3-bit channels | 5-bit depth | 36-bit total_samples
|
||||
|
||||
@ -2,8 +2,6 @@ package ffmpeg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -19,7 +17,7 @@ func readTotalSamples(b []byte) uint64 {
|
||||
return uint64(b[21]&0x0F)<<32 | uint64(b[22])<<24 | uint64(b[23])<<16 | uint64(b[24])<<8 | uint64(b[25])
|
||||
}
|
||||
|
||||
var _ = Describe("patchFLACDuration", func() {
|
||||
var _ = Describe("flacPrefix", func() {
|
||||
var fileFLAC []byte
|
||||
|
||||
// Zeroing total_samples reproduces what a piped transcode emits.
|
||||
@ -30,12 +28,6 @@ var _ = Describe("patchFLACDuration", func() {
|
||||
return b
|
||||
}
|
||||
|
||||
readAll := func(in []byte, duration float32) []byte {
|
||||
out, err := io.ReadAll(patchFLACDuration(io.NopCloser(bytes.NewReader(in)), duration))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
return out
|
||||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
var err error
|
||||
fileFLAC, err = os.ReadFile("tests/fixtures/test.flac")
|
||||
@ -44,7 +36,7 @@ var _ = Describe("patchFLACDuration", func() {
|
||||
})
|
||||
|
||||
It("fills in total_samples from the duration", func() {
|
||||
out := readAll(pipedFLAC(), 1.0)
|
||||
out := readPatched(pipedFLAC(), 1.0)
|
||||
Expect(readTotalSamples(out)).To(Equal(uint64(44100)))
|
||||
})
|
||||
|
||||
@ -54,7 +46,7 @@ var _ = Describe("patchFLACDuration", func() {
|
||||
in[18], in[19] = 0x0B, 0xB8
|
||||
in[20] &= 0x0F
|
||||
|
||||
out := readAll(in, 2.0)
|
||||
out := readPatched(in, 2.0)
|
||||
|
||||
Expect(readSampleRate(out)).To(Equal(48000))
|
||||
Expect(readTotalSamples(out)).To(Equal(uint64(96000)))
|
||||
@ -62,81 +54,43 @@ var _ = Describe("patchFLACDuration", func() {
|
||||
|
||||
It("rounds to the nearest sample rather than truncating", func() {
|
||||
// float32(0.7)*44100 is 30869.9995, so truncation would lose a sample.
|
||||
out := readAll(pipedFLAC(), 0.7)
|
||||
out := readPatched(pipedFLAC(), 0.7)
|
||||
Expect(readTotalSamples(out)).To(Equal(uint64(30870)))
|
||||
})
|
||||
|
||||
It("passes through when the duration overflows the 36-bit field", func() {
|
||||
in := pipedFLAC()
|
||||
Expect(readAll(in, 2e6)).To(Equal(in))
|
||||
Expect(readPatched(in, 2e6)).To(Equal(in))
|
||||
})
|
||||
|
||||
It("leaves everything after the header untouched", func() {
|
||||
in := pipedFLAC()
|
||||
out := readAll(in, 1.0)
|
||||
out := readPatched(in, 1.0)
|
||||
Expect(out).To(HaveLen(len(in)))
|
||||
Expect(out[26:]).To(Equal(in[26:]))
|
||||
Expect(out[:18]).To(Equal(in[:18]))
|
||||
})
|
||||
|
||||
It("leaves an already-populated total_samples alone", func() {
|
||||
out := readAll(fileFLAC, 99.0)
|
||||
out := readPatched(fileFLAC, 99.0)
|
||||
Expect(out).To(Equal(fileFLAC))
|
||||
})
|
||||
|
||||
It("passes through a stream that is not FLAC", func() {
|
||||
in := []byte("ID3\x04\x00\x00\x00\x00\x00\x00 not a flac stream at all, just bytes")
|
||||
Expect(readAll(in, 1.0)).To(Equal(in))
|
||||
})
|
||||
|
||||
It("passes through when the first metadata block is not STREAMINFO", func() {
|
||||
in := pipedFLAC()
|
||||
in[4] = 0x04 // VORBIS_COMMENT
|
||||
Expect(readAll(in, 1.0)).To(Equal(in))
|
||||
Expect(readPatched(in, 1.0)).To(Equal(in))
|
||||
})
|
||||
|
||||
It("passes through a stream shorter than the STREAMINFO fields it patches", func() {
|
||||
in := pipedFLAC()[:20]
|
||||
Expect(readAll(in, 1.0)).To(Equal(in))
|
||||
})
|
||||
|
||||
It("passes through an empty stream", func() {
|
||||
Expect(readAll(nil, 1.0)).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("passes through when the duration is zero or negative", func() {
|
||||
in := pipedFLAC()
|
||||
Expect(readAll(in, 0)).To(Equal(in))
|
||||
Expect(readAll(in, -5)).To(Equal(in))
|
||||
Expect(readPatched(in, 1.0)).To(Equal(in))
|
||||
})
|
||||
|
||||
It("passes through when the header declares no sample rate", func() {
|
||||
in := pipedFLAC()
|
||||
in[18], in[19] = 0, 0
|
||||
in[20] &= 0x0F
|
||||
Expect(readAll(in, 1.0)).To(Equal(in))
|
||||
})
|
||||
|
||||
It("propagates a read error from the underlying stream", func() {
|
||||
_, err := io.ReadAll(patchFLACDuration(io.NopCloser(io.MultiReader(
|
||||
bytes.NewReader(pipedFLAC()[:10]), &errReader{})), 1.0))
|
||||
Expect(err).To(MatchError("boom"))
|
||||
})
|
||||
|
||||
It("closes the underlying stream", func() {
|
||||
c := &closeSpy{Reader: bytes.NewReader(pipedFLAC())}
|
||||
Expect(patchFLACDuration(c, 1.0).Close()).To(Succeed())
|
||||
Expect(c.closed).To(BeTrue())
|
||||
Expect(readPatched(in, 1.0)).To(Equal(in))
|
||||
})
|
||||
})
|
||||
|
||||
type errReader struct{}
|
||||
|
||||
func (e *errReader) Read([]byte) (int, error) { return 0, errors.New("boom") }
|
||||
|
||||
type closeSpy struct {
|
||||
io.Reader
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (c *closeSpy) Close() error { c.closed = true; return nil }
|
||||
|
||||
142
core/ffmpeg/mp3_xing.go
Normal file
142
core/ffmpeg/mp3_xing.go
Normal file
@ -0,0 +1,142 @@
|
||||
package ffmpeg
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"math"
|
||||
"slices"
|
||||
|
||||
"github.com/navidrome/navidrome/utils/gg"
|
||||
)
|
||||
|
||||
const (
|
||||
mp3HeaderLen = 4
|
||||
mp3ID3Len = 10
|
||||
mp3InfoTagLen = 12 // tag, flags and frame count
|
||||
mp3MaxPrefix = 64 << 10 // ffmpeg cannot write an attached picture to a pipe, so the tag stays small
|
||||
)
|
||||
|
||||
// mp3Prefix inserts an Info frame before the first audio frame, returning the head
|
||||
// unchanged when it cannot make sense of what ffmpeg wrote.
|
||||
func (h *headerPatcher) mp3Prefix(buf []byte) ([]byte, error) {
|
||||
buf, err := h.fill(buf, mp3ID3Len)
|
||||
if err != nil || len(buf) < mp3ID3Len {
|
||||
return buf, err
|
||||
}
|
||||
start := 0
|
||||
if string(buf[:3]) == "ID3" {
|
||||
if start = id3TagLen(buf); start > mp3MaxPrefix {
|
||||
return buf, nil
|
||||
}
|
||||
}
|
||||
if buf, err = h.fill(buf, start+mp3HeaderLen); err != nil || len(buf) < start+mp3HeaderLen {
|
||||
return buf, err
|
||||
}
|
||||
frame, ok := parseMP3Header(buf[start:])
|
||||
if !ok {
|
||||
return buf, nil
|
||||
}
|
||||
if buf, err = h.fill(buf, start+frame.size); err != nil || len(buf) < start+frame.size {
|
||||
return buf, err
|
||||
}
|
||||
if isXingFrame(buf[start:], frame.tagOffset) {
|
||||
return buf, nil
|
||||
}
|
||||
xing, ok := xingFrame(buf[start:], h.duration)
|
||||
if !ok {
|
||||
return buf, nil
|
||||
}
|
||||
return slices.Insert(buf, start, xing...), nil
|
||||
}
|
||||
|
||||
func id3TagLen(header []byte) int {
|
||||
size := int(header[6]&0x7F)<<21 | int(header[7]&0x7F)<<14 | int(header[8]&0x7F)<<7 | int(header[9]&0x7F)
|
||||
if header[5]&0x10 != 0 { // footer present
|
||||
size += mp3ID3Len
|
||||
}
|
||||
return mp3ID3Len + size
|
||||
}
|
||||
|
||||
type mp3Frame struct {
|
||||
sampleRate int
|
||||
samples int // per frame
|
||||
size int // bytes, including the header
|
||||
tagOffset int // where a Xing tag sits in the incoming frame, which may carry a CRC
|
||||
}
|
||||
|
||||
var (
|
||||
mp3BitRates = [2][16]int{
|
||||
{0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0}, // MPEG 1
|
||||
{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0}, // MPEG 2 and 2.5
|
||||
}
|
||||
mp3SampleRates = [4][4]int{
|
||||
{11025, 12000, 8000, 0}, // MPEG 2.5
|
||||
{}, // reserved
|
||||
{22050, 24000, 16000, 0}, // MPEG 2
|
||||
{44100, 48000, 32000, 0}, // MPEG 1
|
||||
}
|
||||
)
|
||||
|
||||
func parseMP3Header(h []byte) (mp3Frame, bool) {
|
||||
version, layer := (h[1]>>3)&0x03, (h[1]>>1)&0x03
|
||||
if h[0] != 0xFF || h[1]&0xE0 != 0xE0 || version == 1 || layer != 1 {
|
||||
return mp3Frame{}, false // not the sync word of an MPEG Layer III frame
|
||||
}
|
||||
mpeg1 := version == 3
|
||||
sampleRate := mp3SampleRates[version][(h[2]>>2)&0x03]
|
||||
bitRate := 1000 * mp3BitRates[gg.If(mpeg1, 0, 1)][h[2]>>4]
|
||||
if sampleRate == 0 || bitRate == 0 {
|
||||
return mp3Frame{}, false
|
||||
}
|
||||
f := mp3Frame{sampleRate: sampleRate, samples: gg.If(mpeg1, 1152, 576)}
|
||||
var sideInfo int
|
||||
mono := (h[3]>>6)&0x03 == 3
|
||||
switch {
|
||||
case mpeg1 && mono:
|
||||
sideInfo = 17
|
||||
case mpeg1:
|
||||
sideInfo = 32
|
||||
case mono:
|
||||
sideInfo = 9
|
||||
default:
|
||||
sideInfo = 17
|
||||
}
|
||||
f.size = f.samples/8*bitRate/sampleRate + int((h[2]>>1)&0x01)
|
||||
f.tagOffset = mp3HeaderLen + sideInfo
|
||||
if h[1]&0x01 == 0 { // CRC follows the header
|
||||
f.tagOffset += 2
|
||||
}
|
||||
return f, true
|
||||
}
|
||||
|
||||
func isXingFrame(frame []byte, tagOffset int) bool {
|
||||
if len(frame) < tagOffset+4 {
|
||||
return false
|
||||
}
|
||||
tag := string(frame[tagOffset : tagOffset+4])
|
||||
return tag == "Xing" || tag == "Info"
|
||||
}
|
||||
|
||||
// xingFrame builds a silent Info frame declaring how many frames follow it. Its header is
|
||||
// the first frame's minus the CRC, with the bitrate raised until the frame fits the tag.
|
||||
func xingFrame(first []byte, duration float32) ([]byte, bool) {
|
||||
header := [mp3HeaderLen]byte(first)
|
||||
header[1] |= 0x01
|
||||
f, ok := parseMP3Header(header[:])
|
||||
for ok && f.size < f.tagOffset+mp3InfoTagLen {
|
||||
header[2] += 0x10 // next bitrate index; 15 is invalid, which ends the loop
|
||||
f, ok = parseMP3Header(header[:])
|
||||
}
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
frames := math.Round(float64(duration) * float64(f.sampleRate) / float64(f.samples))
|
||||
if frames < 1 || frames > math.MaxUint32 {
|
||||
return nil, false
|
||||
}
|
||||
frame := make([]byte, f.size)
|
||||
copy(frame, header[:])
|
||||
copy(frame[f.tagOffset:], "Info") // a Xing tag without a seek table marks the stream unseekable to some decoders
|
||||
binary.BigEndian.PutUint32(frame[f.tagOffset+4:], 1) // only the frame count is present
|
||||
binary.BigEndian.PutUint32(frame[f.tagOffset+8:], uint32(frames))
|
||||
return frame, true
|
||||
}
|
||||
141
core/ffmpeg/mp3_xing_test.go
Normal file
141
core/ffmpeg/mp3_xing_test.go
Normal file
@ -0,0 +1,141 @@
|
||||
package ffmpeg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"os"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
// Offsets of the Xing tag inside the first frame, for the two layouts the specs use.
|
||||
const (
|
||||
stereoTagOffset = 36 // 4 header + 32 side info
|
||||
monoTagOffset = 21 // 4 header + 17 side info
|
||||
fixtureID3Len = 39581 // where the first frame of tests/fixtures/test.mp3 starts
|
||||
fixtureFrameLen = 627 // its frame size, at 192kbps and 44100Hz
|
||||
)
|
||||
|
||||
var _ = Describe("mp3Prefix", func() {
|
||||
var pipedMP3 []byte
|
||||
|
||||
// The fixture is an ffmpeg pipe's output in every way that matters here: ID3 tag,
|
||||
// frames, no Xing.
|
||||
BeforeEach(func() {
|
||||
var err error
|
||||
pipedMP3, err = os.ReadFile("tests/fixtures/test.mp3")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(pipedMP3[fixtureID3Len : fixtureID3Len+2]).To(Equal([]byte{0xFF, 0xFB}))
|
||||
Expect(bytes.Contains(pipedMP3[:4096], []byte("Xing"))).To(BeFalse())
|
||||
Expect(bytes.Contains(pipedMP3[:4096], []byte("Info"))).To(BeFalse())
|
||||
})
|
||||
|
||||
// Reads the tag and frame count of the frame starting at frameStart.
|
||||
readXing := func(b []byte, frameStart, tagOffset int) (string, uint32) {
|
||||
at := frameStart + tagOffset
|
||||
return string(b[at : at+4]), binary.BigEndian.Uint32(b[at+8:])
|
||||
}
|
||||
|
||||
It("inserts an Info frame declaring the duration in frames", func() {
|
||||
out := readPatched(pipedMP3, 1.0)
|
||||
|
||||
tag, frames := readXing(out, fixtureID3Len, stereoTagOffset)
|
||||
Expect(tag).To(Equal("Info"))
|
||||
Expect(frames).To(Equal(uint32(38)), "1s at 44100Hz is 38 frames of 1152 samples")
|
||||
flags := binary.BigEndian.Uint32(out[fixtureID3Len+stereoTagOffset+4:])
|
||||
Expect(flags).To(Equal(uint32(1)), "only the frame count is present")
|
||||
})
|
||||
|
||||
It("leaves the ID3 tag and the audio frames untouched", func() {
|
||||
out := readPatched(pipedMP3, 1.0)
|
||||
|
||||
start := fixtureID3Len
|
||||
Expect(out).To(HaveLen(len(pipedMP3) + fixtureFrameLen))
|
||||
Expect(out[:start]).To(Equal(pipedMP3[:start]))
|
||||
Expect(out[start+fixtureFrameLen:]).To(Equal(pipedMP3[start:]))
|
||||
})
|
||||
|
||||
It("takes the sample rate from the frame header", func() {
|
||||
in := bytes.Clone(pipedMP3)
|
||||
start := fixtureID3Len
|
||||
in[start+2] = in[start+2]&^0x0C | 0x04 // sample rate index 1: 48000Hz
|
||||
|
||||
out := readPatched(in, 1.0)
|
||||
|
||||
_, frames := readXing(out, start, stereoTagOffset)
|
||||
Expect(frames).To(Equal(uint32(42))) // 48000/1152, rounded
|
||||
})
|
||||
|
||||
It("rounds the frame count to the nearest frame", func() {
|
||||
out := readPatched(pipedMP3, 0.99) // 37.9 frames
|
||||
_, frames := readXing(out, fixtureID3Len, stereoTagOffset)
|
||||
Expect(frames).To(Equal(uint32(38)))
|
||||
})
|
||||
|
||||
It("places the tag after the shorter side info of a mono stream", func() {
|
||||
in := monoMP3()
|
||||
|
||||
out := readPatched(in, 1.0)
|
||||
|
||||
tag, frames := readXing(out, 0, monoTagOffset)
|
||||
Expect(tag).To(Equal("Info"))
|
||||
Expect(frames).To(Equal(uint32(38)))
|
||||
})
|
||||
|
||||
It("raises the bitrate of the inserted frame when the first frame is too small for the tag", func() {
|
||||
// MPEG 2, 8kbps, 22050Hz, stereo: 26 bytes, as a VBR encode starting on silence emits.
|
||||
in := make([]byte, 26)
|
||||
copy(in, []byte{0xFF, 0xF3, 0x10, 0x00})
|
||||
|
||||
out := readPatched(in, 1.0)
|
||||
|
||||
Expect(out[2]>>4).To(Equal(byte(2)), "16kbps, the first bitrate whose frame fits the tag")
|
||||
tag, frames := readXing(out, 0, 21) // 4 header + 17 side info
|
||||
Expect(tag).To(Equal("Info"))
|
||||
Expect(frames).To(Equal(uint32(38))) // 1s at 22050Hz is 38 frames of 576 samples
|
||||
Expect(out[52:]).To(Equal(in)) // 52 bytes = frame size at 16kbps, 22050Hz
|
||||
})
|
||||
|
||||
It("inserts the frame at the start of a stream with no ID3 tag", func() {
|
||||
in := pipedMP3[fixtureID3Len:]
|
||||
|
||||
out := readPatched(in, 1.0)
|
||||
|
||||
tag, _ := readXing(out, 0, stereoTagOffset)
|
||||
Expect(tag).To(Equal("Info"))
|
||||
Expect(out[fixtureFrameLen:]).To(Equal(in))
|
||||
})
|
||||
|
||||
It("leaves a stream that already declares its duration alone", func() {
|
||||
patched := readPatched(pipedMP3, 1.0)
|
||||
Expect(readPatched(patched, 99.0)).To(Equal(patched))
|
||||
})
|
||||
|
||||
It("passes through a frame header with a reserved bitrate or sample rate", func() {
|
||||
in := monoMP3()
|
||||
in[2] |= 0xF0 // bitrate index 15 is invalid
|
||||
Expect(readPatched(in, 1.0)).To(Equal(in))
|
||||
|
||||
in = monoMP3()
|
||||
in[2] |= 0x0C // sample rate index 3 is reserved
|
||||
Expect(readPatched(in, 1.0)).To(Equal(in))
|
||||
})
|
||||
|
||||
It("passes through a stream too short to hold a frame header", func() {
|
||||
in := monoMP3()[:3]
|
||||
Expect(readPatched(in, 1.0)).To(Equal(in))
|
||||
})
|
||||
|
||||
It("passes through a stream whose ID3 tag never ends", func() {
|
||||
in := bytes.Clone(pipedMP3[:200])
|
||||
Expect(readPatched(in, 1.0)).To(Equal(in))
|
||||
})
|
||||
})
|
||||
|
||||
// monoMP3 is one silent MPEG1 Layer III frame, 128kbps, 44100Hz, mono.
|
||||
func monoMP3() []byte {
|
||||
b := make([]byte, 417)
|
||||
copy(b, []byte{0xFF, 0xFB, 0x90, 0xC0})
|
||||
return b
|
||||
}
|
||||
61
core/ffmpeg/piped_header.go
Normal file
61
core/ffmpeg/piped_header.go
Normal file
@ -0,0 +1,61 @@
|
||||
package ffmpeg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
// patchPipedHeader repairs the header ffmpeg cannot finish when its output is a pipe,
|
||||
// since it only learns the sample or frame count once it can no longer rewind.
|
||||
func patchPipedHeader(r io.ReadCloser, duration float32) io.ReadCloser {
|
||||
if duration <= 0 {
|
||||
return r
|
||||
}
|
||||
return &headerPatcher{ReadCloser: r, duration: duration}
|
||||
}
|
||||
|
||||
type headerPatcher struct {
|
||||
io.ReadCloser
|
||||
duration float32
|
||||
// Peeking here rather than in the constructor keeps Transcode from blocking
|
||||
// until ffmpeg has emitted its first bytes.
|
||||
stream io.Reader
|
||||
}
|
||||
|
||||
func (h *headerPatcher) Read(p []byte) (int, error) {
|
||||
if h.stream == nil {
|
||||
prefix, err := h.peek()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
h.stream = io.MultiReader(bytes.NewReader(prefix), h.ReadCloser)
|
||||
}
|
||||
return h.stream.Read(p)
|
||||
}
|
||||
|
||||
// peek dispatches on the magic bytes rather than on the requested format, which is a
|
||||
// free-text label on the transcoding profile and need not match what ffmpeg emits.
|
||||
func (h *headerPatcher) peek() ([]byte, error) {
|
||||
buf, err := h.fill(nil, 4)
|
||||
if err != nil || len(buf) < 4 {
|
||||
return buf, err
|
||||
}
|
||||
if string(buf) == "fLaC" {
|
||||
return h.flacPrefix(buf)
|
||||
}
|
||||
return h.mp3Prefix(buf)
|
||||
}
|
||||
|
||||
// fill grows buf to n bytes, stopping short when the stream ends first.
|
||||
func (h *headerPatcher) fill(buf []byte, n int) ([]byte, error) {
|
||||
if len(buf) >= n {
|
||||
return buf, nil
|
||||
}
|
||||
more := make([]byte, n-len(buf))
|
||||
read, err := io.ReadFull(h.ReadCloser, more)
|
||||
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return buf, err
|
||||
}
|
||||
return append(buf, more[:read]...), nil
|
||||
}
|
||||
58
core/ffmpeg/piped_header_test.go
Normal file
58
core/ffmpeg/piped_header_test.go
Normal file
@ -0,0 +1,58 @@
|
||||
package ffmpeg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"testing/iotest"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func readPatched(in []byte, duration float32) []byte {
|
||||
out, err := io.ReadAll(patchPipedHeader(io.NopCloser(bytes.NewReader(in)), duration))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
return out
|
||||
}
|
||||
|
||||
var _ = Describe("patchPipedHeader", func() {
|
||||
It("passes through when the duration is zero or negative", func() {
|
||||
in := monoMP3()
|
||||
Expect(readPatched(in, 0)).To(Equal(in))
|
||||
Expect(readPatched(in, -5)).To(Equal(in))
|
||||
})
|
||||
|
||||
It("passes through a stream that is neither FLAC nor mp3", func() {
|
||||
in := []byte("OggS\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00 and then some bytes")
|
||||
Expect(readPatched(in, 1.0)).To(Equal(in))
|
||||
})
|
||||
|
||||
It("passes through an ADTS stream, whose sync word looks like mp3's", func() {
|
||||
in := append([]byte{0xFF, 0xF1, 0x50, 0x80, 0x4D, 0x1F, 0xFC}, make([]byte, 600)...)
|
||||
Expect(readPatched(in, 1.0)).To(Equal(in))
|
||||
})
|
||||
|
||||
It("passes through an empty stream", func() {
|
||||
Expect(readPatched(nil, 1.0)).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("propagates a read error from the underlying stream", func() {
|
||||
r := patchPipedHeader(io.NopCloser(iotest.ErrReader(errors.New("ffmpeg died"))), 1.0)
|
||||
_, err := io.ReadAll(r)
|
||||
Expect(err).To(MatchError(ContainSubstring("ffmpeg died")))
|
||||
})
|
||||
|
||||
It("closes the underlying stream", func() {
|
||||
c := &closeSpy{Reader: bytes.NewReader(monoMP3())}
|
||||
Expect(patchPipedHeader(c, 1.0).Close()).To(Succeed())
|
||||
Expect(c.closed).To(BeTrue())
|
||||
})
|
||||
})
|
||||
|
||||
type closeSpy struct {
|
||||
io.Reader
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (c *closeSpy) Close() error { c.closed = true; return nil }
|
||||
@ -5,7 +5,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
@ -367,25 +366,14 @@ func (r *libraryRepositoryWrapper) validateLibraryPath(ctx context.Context, libr
|
||||
fsys, err := fileStore.FS()
|
||||
if err != nil {
|
||||
log.Warn(ctx, "Error validating library.path", "path", library.Path, err)
|
||||
return fmt.Errorf("resources.library.validation.pathInvalid")
|
||||
return errors.New(classifyLibraryPathError(err))
|
||||
}
|
||||
|
||||
// Check if root directory exists
|
||||
info, err := fs.Stat(fsys, ".")
|
||||
if err != nil {
|
||||
// Parse the error message to check for "not a directory"
|
||||
log.Warn(ctx, "Error stating library.path", "path", library.Path, err)
|
||||
errStr := err.Error()
|
||||
if strings.Contains(errStr, "not a directory") ||
|
||||
strings.Contains(errStr, "The directory name is invalid.") {
|
||||
return fmt.Errorf("resources.library.validation.pathNotDirectory")
|
||||
} else if os.IsNotExist(err) {
|
||||
return fmt.Errorf("resources.library.validation.pathNotFound")
|
||||
} else if os.IsPermission(err) {
|
||||
return fmt.Errorf("resources.library.validation.pathNotAccessible")
|
||||
} else {
|
||||
return fmt.Errorf("resources.library.validation.pathInvalid")
|
||||
}
|
||||
return errors.New(classifyLibraryPathError(err))
|
||||
}
|
||||
|
||||
if !info.IsDir() {
|
||||
@ -395,6 +383,22 @@ func (r *libraryRepositoryWrapper) validateLibraryPath(ctx context.Context, libr
|
||||
return nil
|
||||
}
|
||||
|
||||
// classifyLibraryPathError maps a path error to its i18n key. It uses errors.Is because storage FS() wraps with %w.
|
||||
// Not-a-directory is matched by text: syscall.ENOTDIR means ERROR_PATH_NOT_FOUND on Windows, and ERROR_DIRECTORY is not exported.
|
||||
func classifyLibraryPathError(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
return "resources.library.validation.pathNotFound"
|
||||
case errors.Is(err, fs.ErrPermission):
|
||||
return "resources.library.validation.pathNotAccessible"
|
||||
case strings.Contains(err.Error(), "not a directory") ||
|
||||
strings.Contains(err.Error(), "The directory name is invalid."):
|
||||
return "resources.library.validation.pathNotDirectory"
|
||||
default:
|
||||
return "resources.library.validation.pathInvalid"
|
||||
}
|
||||
}
|
||||
|
||||
func (s *libraryService) validateLibraryIDs(ctx context.Context, libraryIDs []int) error {
|
||||
if len(libraryIDs) == 0 {
|
||||
return nil
|
||||
|
||||
29
core/library_internal_test.go
Normal file
29
core/library_internal_test.go
Normal file
@ -0,0 +1,29 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("classifyLibraryPathError", func() {
|
||||
DescribeTable("maps a filesystem error to a validation message key",
|
||||
func(err error, expected string) {
|
||||
Expect(classifyLibraryPathError(err)).To(Equal(expected))
|
||||
},
|
||||
Entry("missing path", fs.ErrNotExist, "resources.library.validation.pathNotFound"),
|
||||
Entry("wrapped missing path", fmt.Errorf("stat /music: %w", fs.ErrNotExist), "resources.library.validation.pathNotFound"),
|
||||
Entry("permission denied", fs.ErrPermission, "resources.library.validation.pathNotAccessible"),
|
||||
Entry("wrapped permission denied", fmt.Errorf("open /music: %w", fs.ErrPermission), "resources.library.validation.pathNotAccessible"),
|
||||
Entry("file instead of a directory on Unix",
|
||||
&fs.PathError{Op: "open", Path: "/music/song.mp3", Err: errors.New("not a directory")},
|
||||
"resources.library.validation.pathNotDirectory"),
|
||||
Entry("file instead of a directory on Windows",
|
||||
&fs.PathError{Op: "open", Path: `C:\music\song.mp3`, Err: errors.New("The directory name is invalid.")},
|
||||
"resources.library.validation.pathNotDirectory"),
|
||||
Entry("any other error", errors.New("input/output error"), "resources.library.validation.pathInvalid"),
|
||||
)
|
||||
})
|
||||
@ -10,7 +10,6 @@ import (
|
||||
|
||||
"github.com/deluan/rest"
|
||||
_ "github.com/navidrome/navidrome/adapters/gotaglib" // Register taglib extractor
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core"
|
||||
_ "github.com/navidrome/navidrome/core/storage/local" // Register local storage
|
||||
"github.com/navidrome/navidrome/model"
|
||||
@ -35,7 +34,6 @@ var _ = Describe("Library Service", func() {
|
||||
var pluginManager *mockPluginUnloader
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
|
||||
ds = &tests.MockDataStore{}
|
||||
libraryRepo = &tests.MockLibraryRepo{}
|
||||
@ -375,7 +373,7 @@ var _ = Describe("Library Service", func() {
|
||||
Expect(err).To(HaveOccurred())
|
||||
var validationErr *rest.ValidationError
|
||||
Expect(errors.As(err, &validationErr)).To(BeTrue())
|
||||
Expect(validationErr.Errors["path"]).To(Equal("resources.library.validation.pathInvalid"))
|
||||
Expect(validationErr.Errors["path"]).To(Equal("resources.library.validation.pathNotFound"))
|
||||
})
|
||||
|
||||
It("fails when path is a file instead of directory", func() {
|
||||
@ -455,7 +453,7 @@ var _ = Describe("Library Service", func() {
|
||||
Expect(err).To(HaveOccurred())
|
||||
var validationErr *rest.ValidationError
|
||||
Expect(errors.As(err, &validationErr)).To(BeTrue())
|
||||
Expect(validationErr.Errors["path"]).To(Equal("resources.library.validation.pathInvalid"))
|
||||
Expect(validationErr.Errors["path"]).To(Equal("resources.library.validation.pathNotFound"))
|
||||
})
|
||||
|
||||
It("fails when updated path is a file instead of directory", func() {
|
||||
|
||||
@ -46,7 +46,7 @@ func NewLyrics(ds model.DataStore, pluginLoader PluginLoader) Lyrics {
|
||||
}
|
||||
|
||||
// GetLyrics returns lyrics for the given media file, trying sources in the
|
||||
// order specified by conf.Server.LyricsPriority.
|
||||
// order specified by conf.Server().LyricsPriority.
|
||||
func (l *lyricsService) GetLyrics(ctx context.Context, mf *model.MediaFile) (model.LyricList, error) {
|
||||
return l.getLyricsForCandidates(ctx, []*model.MediaFile{mf})
|
||||
}
|
||||
@ -87,7 +87,7 @@ func songsByArtistTitleWithLyricsFirst(artist, title string) model.QueryOptions
|
||||
}
|
||||
|
||||
func (l *lyricsService) getLyricsForCandidates(ctx context.Context, mediaFiles []*model.MediaFile) (model.LyricList, error) {
|
||||
for pattern := range strings.SplitSeq(conf.Server.LyricsPriority, ",") {
|
||||
for pattern := range strings.SplitSeq(conf.Server().LyricsPriority, ",") {
|
||||
pattern = strings.TrimSpace(pattern)
|
||||
if pattern == "" {
|
||||
continue
|
||||
|
||||
@ -4,6 +4,7 @@ import (
|
||||
"io/fs"
|
||||
"testing"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/core/storage/local"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
@ -20,6 +21,8 @@ func TestLyrics(t *testing.T) {
|
||||
RunSpecs(t, "Lyrics Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
// core/storage/local calls log.Fatal if the default scanner extractor is unregistered
|
||||
// when constructing any localStorage. Register a no-op so storage.For("file://...") works
|
||||
// in tests without importing the real extractor.
|
||||
|
||||
@ -8,7 +8,6 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core/lyrics"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
@ -151,7 +150,6 @@ var _ = Describe("Lyrics", func() {
|
||||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
|
||||
lyricsJson, _ := json.Marshal(embeddedLyrics)
|
||||
|
||||
@ -163,7 +161,7 @@ var _ = Describe("Lyrics", func() {
|
||||
})
|
||||
|
||||
DescribeTable("Lyrics Priority", func(priority string, expected model.LyricList) {
|
||||
conf.Server.LyricsPriority = priority
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = priority })
|
||||
svc := lyrics.NewLyrics(nil, nil)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).To(BeNil())
|
||||
@ -177,7 +175,7 @@ var _ = Describe("Lyrics", func() {
|
||||
Entry("ttml > elrc > lrc > srt > embedded", ".ttml,.elrc,.lrc,.srt,embedded", ttmlLyrics))
|
||||
|
||||
It("resolves source priority across duplicate media files", func() {
|
||||
conf.Server.LyricsPriority = ".ttml,embedded"
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = ".ttml,embedded" })
|
||||
embeddedJSON, err := json.Marshal(embeddedLyrics)
|
||||
Expect(err).To(BeNil())
|
||||
|
||||
@ -214,7 +212,7 @@ var _ = Describe("Lyrics", func() {
|
||||
}
|
||||
Expect(os.IsNotExist(err)).To(BeTrue())
|
||||
|
||||
conf.Server.LyricsPriority = ".LRC"
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = ".LRC" })
|
||||
Expect(os.WriteFile(filepath.Join(dir, "song.LRC"), []byte("[00:01.00]Upper suffix"), 0600)).To(Succeed())
|
||||
|
||||
svc := lyrics.NewLyrics(nil, nil)
|
||||
@ -240,7 +238,7 @@ var _ = Describe("Lyrics", func() {
|
||||
Expect(os.WriteFile(filepath.Join(dir, "song.yaml"), []byte("title: not lyricsfile\n"), 0600)).To(Succeed())
|
||||
Expect(os.WriteFile(filepath.Join(dir, "song.lrc"), []byte("[00:01.00]Fallback line"), 0600)).To(Succeed())
|
||||
|
||||
conf.Server.LyricsPriority = ".yaml,.lrc"
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = ".yaml,.lrc" })
|
||||
svc := lyrics.NewLyrics(nil, nil)
|
||||
list, err := svc.GetLyrics(ctx, &model.MediaFile{
|
||||
LibraryPath: dir,
|
||||
@ -284,7 +282,7 @@ var _ = Describe("Lyrics", func() {
|
||||
})
|
||||
|
||||
It("should fallback to embedded if an error happens when parsing file", func() {
|
||||
conf.Server.LyricsPriority = ".mp3,embedded"
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = ".mp3,embedded" })
|
||||
|
||||
svc := lyrics.NewLyrics(nil, nil)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
@ -293,7 +291,7 @@ var _ = Describe("Lyrics", func() {
|
||||
})
|
||||
|
||||
It("should return nothing if error happens when trying to parse file", func() {
|
||||
conf.Server.LyricsPriority = ".mp3"
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = ".mp3" })
|
||||
|
||||
svc := lyrics.NewLyrics(nil, nil)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
@ -311,7 +309,7 @@ var _ = Describe("Lyrics", func() {
|
||||
})
|
||||
|
||||
It("should return lyrics from a plugin", func() {
|
||||
conf.Server.LyricsPriority = "test-lyrics-plugin"
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = "test-lyrics-plugin" })
|
||||
mockLoader.lyrics = unsyncedLyrics
|
||||
svc := lyrics.NewLyrics(nil, mockLoader)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
@ -320,7 +318,7 @@ var _ = Describe("Lyrics", func() {
|
||||
})
|
||||
|
||||
It("should try plugin after embedded returns nothing", func() {
|
||||
conf.Server.LyricsPriority = "embedded,test-lyrics-plugin"
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = "embedded,test-lyrics-plugin" })
|
||||
mf.Lyrics = "" // No embedded lyrics
|
||||
mockLoader.lyrics = unsyncedLyrics
|
||||
svc := lyrics.NewLyrics(nil, mockLoader)
|
||||
@ -330,7 +328,7 @@ var _ = Describe("Lyrics", func() {
|
||||
})
|
||||
|
||||
It("should skip plugin if embedded has lyrics", func() {
|
||||
conf.Server.LyricsPriority = "embedded,test-lyrics-plugin"
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = "embedded,test-lyrics-plugin" })
|
||||
mockLoader.lyrics = unsyncedLyrics
|
||||
svc := lyrics.NewLyrics(nil, mockLoader)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
@ -339,7 +337,7 @@ var _ = Describe("Lyrics", func() {
|
||||
})
|
||||
|
||||
It("should skip unknown plugin names gracefully", func() {
|
||||
conf.Server.LyricsPriority = "nonexistent-plugin,embedded"
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = "nonexistent-plugin,embedded" })
|
||||
mockLoader.notFound = true
|
||||
svc := lyrics.NewLyrics(nil, mockLoader)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
@ -348,7 +346,7 @@ var _ = Describe("Lyrics", func() {
|
||||
})
|
||||
|
||||
It("should preserve plugin name case from config", func() {
|
||||
conf.Server.LyricsPriority = "MyLyricsPlugin"
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = "MyLyricsPlugin" })
|
||||
mockLoader.pluginName = "MyLyricsPlugin"
|
||||
mockLoader.lyrics = unsyncedLyrics
|
||||
svc := lyrics.NewLyrics(nil, mockLoader)
|
||||
@ -358,7 +356,7 @@ var _ = Describe("Lyrics", func() {
|
||||
})
|
||||
|
||||
It("should handle plugin error gracefully", func() {
|
||||
conf.Server.LyricsPriority = "test-lyrics-plugin,embedded"
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = "test-lyrics-plugin,embedded" })
|
||||
mockLoader.err = fmt.Errorf("plugin error")
|
||||
svc := lyrics.NewLyrics(nil, mockLoader)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
@ -373,8 +371,7 @@ var _ = Describe("Lyrics", func() {
|
||||
var ds *tests.MockDataStore
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.LyricsPriority = "embedded"
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = "embedded" })
|
||||
repo = &tests.MockMediaFileRepo{}
|
||||
ds = &tests.MockDataStore{MockedMediaFile: repo}
|
||||
svc = lyrics.NewLyrics(ds, nil)
|
||||
|
||||
@ -32,7 +32,7 @@
|
||||
// # Fuzzy Matching Details
|
||||
//
|
||||
// Title+artist matching uses Jaro-Winkler similarity, with a threshold
|
||||
// configurable via conf.Server.Matcher.FuzzyThreshold (default 85%). A library
|
||||
// configurable via conf.Server().Matcher.FuzzyThreshold (default 85%). A library
|
||||
// track must clear the title threshold to be considered. Candidates that clear
|
||||
// it are ranked by, in order:
|
||||
//
|
||||
@ -42,7 +42,7 @@
|
||||
// 3. Specificity level (0–5, based on metadata precision; higher is better)
|
||||
// 4. Artist overlap (how many of the song's artists the track credits; more
|
||||
// shared artists is better)
|
||||
// 5. Preferred-track flag (enabled by conf.Server.Matcher.PreferStarred;
|
||||
// 5. Preferred-track flag (enabled by conf.Server().Matcher.PreferStarred;
|
||||
// prioritizes tracks that are starred or rated >= 4, but only among
|
||||
// candidates of equal specificity and overlap)
|
||||
// 6. Album similarity (Jaro-Winkler, as the final tiebreaker)
|
||||
@ -111,7 +111,7 @@
|
||||
// {ID: "live", Title: "Untitled", Artist: "Interpol", Duration: 602} // 10:02
|
||||
// Result: studio for the first song, live for the second
|
||||
//
|
||||
// Preferred track — when conf.Server.Matcher.PreferStarred is enabled, a
|
||||
// Preferred track — when conf.Server().Matcher.PreferStarred is enabled, a
|
||||
// starred (or rating >= 4) track is preferred, but only when specificity and
|
||||
// artist overlap are equal. A more specific match always wins regardless of the
|
||||
// preferred flag:
|
||||
|
||||
@ -340,7 +340,7 @@ func (m *Matcher) matchByTitle(ctx context.Context, songs []agents.Song, result
|
||||
}
|
||||
|
||||
tracksByQuery := resolved.bucketTracks(tracks)
|
||||
threshold := float64(conf.Server.Matcher.FuzzyThreshold) / 100.0
|
||||
threshold := float64(conf.Server().Matcher.FuzzyThreshold) / 100.0
|
||||
for _, iq := range queries {
|
||||
sanitized := tracksByQuery[iq.index]
|
||||
if mf, found := m.findBestMatch(iq.query, sanitized, threshold); found {
|
||||
@ -571,7 +571,7 @@ func (m *Matcher) findBestMatch(q songQuery, candidates []scoredTrack, threshold
|
||||
bestScore := matchScore{titleSimilarity: -1}
|
||||
found := false
|
||||
|
||||
preferStarred := conf.Server.Matcher.PreferStarred
|
||||
preferStarred := conf.Server().Matcher.PreferStarred
|
||||
for _, c := range candidates {
|
||||
titleSim := similarityRatio(q.title, c.title)
|
||||
if titleSim < threshold {
|
||||
|
||||
@ -3,6 +3,7 @@ package matcher_test
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -15,3 +16,5 @@ func TestMatcher(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Matcher Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/core/matcher"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
@ -26,7 +25,6 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
mediaFileRepo = newMockMediaFileRepo()
|
||||
artistRepo = newMockArtistRepo()
|
||||
DeferCleanup(func() {
|
||||
@ -105,7 +103,7 @@ var _ = Describe("Matcher", func() {
|
||||
Describe("MatchSongs", func() {
|
||||
Context("matching by direct ID", func() {
|
||||
It("matches songs with an ID field to MediaFiles by ID", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 100
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 })
|
||||
songs := []agents.Song{
|
||||
{ID: "track-1", Name: "Some Song", Artists: []agents.Artist{{Name: "Some Artist"}}},
|
||||
}
|
||||
@ -123,7 +121,7 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
Context("matching by MBID", func() {
|
||||
It("matches songs with MBID to tracks with matching mbz_recording_id", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 100
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 })
|
||||
songs := []agents.Song{
|
||||
{Name: "Paranoid Android", MBID: "abc-123", Artists: []agents.Artist{{Name: "Radiohead"}}},
|
||||
}
|
||||
@ -142,7 +140,7 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
Context("matching by ISRC", func() {
|
||||
It("matches songs with ISRC to tracks with matching ISRC tag", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 100
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 })
|
||||
songs := []agents.Song{
|
||||
{Name: "Paranoid Android", ISRC: "GBAYE0000351", Artists: []agents.Artist{{Name: "Radiohead"}}},
|
||||
}
|
||||
@ -161,7 +159,7 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
Context("fuzzy title+artist matching", func() {
|
||||
It("matches songs by title and artist name", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 100
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 })
|
||||
songs := []agents.Song{
|
||||
{Name: "Enjoy the Silence", Artists: []agents.Artist{{Name: "Depeche Mode"}}},
|
||||
}
|
||||
@ -177,7 +175,7 @@ var _ = Describe("Matcher", func() {
|
||||
})
|
||||
|
||||
It("matches songs with fuzzy title similarity", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 85
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 85 })
|
||||
songs := []agents.Song{
|
||||
{Name: "Bohemian Rhapsody", Artists: []agents.Artist{{Name: "Queen"}}},
|
||||
}
|
||||
@ -193,7 +191,7 @@ var _ = Describe("Matcher", func() {
|
||||
})
|
||||
|
||||
It("does not match completely different titles", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 85
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 85 })
|
||||
songs := []agents.Song{
|
||||
{Name: "Yesterday", Artists: []agents.Artist{{Name: "The Beatles"}}},
|
||||
}
|
||||
@ -211,7 +209,7 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
Context("deduplication", func() {
|
||||
It("removes duplicates when different input songs match the same library track", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 85
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 85 })
|
||||
songs := []agents.Song{
|
||||
{Name: "Bohemian Rhapsody (Live)", Artists: []agents.Artist{{Name: "Queen"}}},
|
||||
{Name: "Bohemian Rhapsody (Original Mix)", Artists: []agents.Artist{{Name: "Queen"}}},
|
||||
@ -228,7 +226,7 @@ var _ = Describe("Matcher", func() {
|
||||
})
|
||||
|
||||
It("preserves duplicates when identical input songs match the same library track", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 85
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 85 })
|
||||
songs := []agents.Song{
|
||||
{Name: "Bohemian Rhapsody", Artists: []agents.Artist{{Name: "Queen"}}, Album: "A Night at the Opera"},
|
||||
{Name: "Bohemian Rhapsody", Artists: []agents.Artist{{Name: "Queen"}}, Album: "A Night at the Opera"},
|
||||
@ -248,7 +246,7 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
Context("priority ordering", func() {
|
||||
It("prefers ID match over MBID match", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 100
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 })
|
||||
// Song has both ID and MBID set. The matcher should resolve via ID
|
||||
// and short-circuit the MBID phase entirely, so no MBID fetch should
|
||||
// occur even though an mbz_recording_id exists in the input.
|
||||
@ -269,7 +267,7 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
Context("count limit", func() {
|
||||
It("returns at most 'count' results", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 100
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 })
|
||||
songs := []agents.Song{
|
||||
{Name: "Song A", Artists: []agents.Artist{{Name: "Artist"}}},
|
||||
{Name: "Song B", Artists: []agents.Artist{{Name: "Artist"}}},
|
||||
@ -469,7 +467,7 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
Context("multiple artists", func() {
|
||||
It("prefers the track that shares more of the song's artists", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 85
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 85 })
|
||||
songs := []agents.Song{
|
||||
{Name: "Life Is Good", Artists: []agents.Artist{{Name: "Drake"}, {Name: "Future"}}},
|
||||
}
|
||||
@ -498,7 +496,7 @@ var _ = Describe("Matcher", func() {
|
||||
})
|
||||
|
||||
It("matches a single-artist song against a track crediting several artists", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 85
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 85 })
|
||||
songs := []agents.Song{
|
||||
{Name: "Life Is Good", Artists: []agents.Artist{{Name: "Future"}}},
|
||||
}
|
||||
@ -518,7 +516,7 @@ var _ = Describe("Matcher", func() {
|
||||
})
|
||||
|
||||
It("matches by a directly-supplied Navidrome artist ID (fast-path)", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 85
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 85 })
|
||||
songs := []agents.Song{
|
||||
{Name: "Song A", Artists: []agents.Artist{{ID: "ar-x"}}},
|
||||
}
|
||||
@ -537,8 +535,10 @@ var _ = Describe("Matcher", func() {
|
||||
})
|
||||
|
||||
It("prefers a higher artist-overlap track over a starred lower-overlap track", func() {
|
||||
conf.Server.Matcher.PreferStarred = true
|
||||
conf.Server.Matcher.FuzzyThreshold = 85
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.Matcher.PreferStarred = true
|
||||
c.Matcher.FuzzyThreshold = 85
|
||||
})
|
||||
songs := []agents.Song{
|
||||
{Name: "Collab Hit", Artists: []agents.Artist{{Name: "Drake"}, {Name: "Future"}}},
|
||||
}
|
||||
@ -614,7 +614,7 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
Describe("specificity level matching", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 100
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 })
|
||||
})
|
||||
|
||||
It("matches by title + artist MBID + album MBID (highest priority)", func() {
|
||||
@ -785,7 +785,7 @@ var _ = Describe("Matcher", func() {
|
||||
Describe("fuzzy matching thresholds", func() {
|
||||
Context("with default threshold (85%)", func() {
|
||||
It("matches songs with remastered suffix", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 85
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 85 })
|
||||
|
||||
songs := []agents.Song{
|
||||
{Name: "Paranoid Android", Artists: []agents.Artist{{Name: "Radiohead"}}},
|
||||
@ -806,7 +806,7 @@ var _ = Describe("Matcher", func() {
|
||||
})
|
||||
|
||||
It("matches songs with live suffix", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 85
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 85 })
|
||||
|
||||
songs := []agents.Song{
|
||||
{Name: "Bohemian Rhapsody", Artists: []agents.Artist{{Name: "Queen"}}},
|
||||
@ -829,7 +829,7 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
Context("with threshold set to 100 (exact match only)", func() {
|
||||
It("only matches exact titles", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 100
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 })
|
||||
|
||||
songs := []agents.Song{
|
||||
{Name: "Paranoid Android", Artists: []agents.Artist{{Name: "Radiohead"}}},
|
||||
@ -851,7 +851,7 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
Context("with lower threshold (75%)", func() {
|
||||
It("matches more aggressively", func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 75
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 75 })
|
||||
|
||||
songs := []agents.Song{
|
||||
{Name: "Song", Artists: []agents.Artist{{Name: "Artist"}}},
|
||||
@ -875,8 +875,10 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
Describe("fuzzy album matching", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 85
|
||||
conf.Server.Matcher.PreferStarred = false
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.Matcher.FuzzyThreshold = 85
|
||||
c.Matcher.PreferStarred = false
|
||||
})
|
||||
})
|
||||
|
||||
It("matches album with (Remaster) suffix", func() {
|
||||
@ -946,7 +948,7 @@ var _ = Describe("Matcher", func() {
|
||||
})
|
||||
|
||||
It("prefers a more specific match over a starred track when PreferStarred is enabled", func() {
|
||||
conf.Server.Matcher.PreferStarred = true
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.PreferStarred = true })
|
||||
songs := []agents.Song{
|
||||
{Name: "Enjoy the Silence", Artists: []agents.Artist{{Name: "Depeche Mode"}}, Album: "Violator"},
|
||||
}
|
||||
@ -967,7 +969,7 @@ var _ = Describe("Matcher", func() {
|
||||
})
|
||||
|
||||
It("prefers a more specific match over a 4-star track when PreferStarred is enabled", func() {
|
||||
conf.Server.Matcher.PreferStarred = true
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.PreferStarred = true })
|
||||
songs := []agents.Song{
|
||||
{Name: "Enjoy the Silence", Artists: []agents.Artist{{Name: "Depeche Mode"}}, Album: "Violator"},
|
||||
}
|
||||
@ -988,7 +990,7 @@ var _ = Describe("Matcher", func() {
|
||||
})
|
||||
|
||||
It("prefers a starred track when specificity and overlap are equal", func() {
|
||||
conf.Server.Matcher.PreferStarred = true
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.PreferStarred = true })
|
||||
songs := []agents.Song{
|
||||
{Name: "Enjoy the Silence", Artists: []agents.Artist{{Name: "Depeche Mode"}}, Album: "Violator"},
|
||||
}
|
||||
@ -1012,7 +1014,7 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
Describe("duration matching", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 100
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 })
|
||||
})
|
||||
|
||||
It("prefers tracks with matching duration", func() {
|
||||
@ -1180,7 +1182,7 @@ var _ = Describe("Matcher", func() {
|
||||
|
||||
Describe("deduplication edge cases", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.Matcher.FuzzyThreshold = 85
|
||||
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 85 })
|
||||
})
|
||||
|
||||
It("handles mixed scenario with both identical and different input songs", func() {
|
||||
|
||||
@ -156,7 +156,7 @@ func getFSInfo(path string) *insights.FSInfo {
|
||||
|
||||
// installedPackage returns the official installer format used, as written by our own packagers.
|
||||
func installedPackage() string {
|
||||
data, _ := os.ReadFile(filepath.Join(conf.Server.DataFolder.String(), ".package"))
|
||||
data, _ := os.ReadFile(filepath.Join(conf.Server().DataFolder.String(), ".package"))
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
|
||||
@ -187,55 +187,55 @@ var staticData = sync.OnceValue(func() insights.Data {
|
||||
data.OS.Version, data.OS.Distro = getOSVersion()
|
||||
|
||||
// FS info
|
||||
data.FS.Music = getFSInfo(conf.Server.MusicFolder)
|
||||
data.FS.Data = getFSInfo(conf.Server.DataFolder.String())
|
||||
if conf.Server.CacheFolder.String() != "" {
|
||||
data.FS.Cache = getFSInfo(conf.Server.CacheFolder.String())
|
||||
data.FS.Music = getFSInfo(conf.Server().MusicFolder)
|
||||
data.FS.Data = getFSInfo(conf.Server().DataFolder.String())
|
||||
if conf.Server().CacheFolder.String() != "" {
|
||||
data.FS.Cache = getFSInfo(conf.Server().CacheFolder.String())
|
||||
}
|
||||
if conf.Server.Backup.Path.String() != "" {
|
||||
data.FS.Backup = getFSInfo(conf.Server.Backup.Path.String())
|
||||
if conf.Server().Backup.Path.String() != "" {
|
||||
data.FS.Backup = getFSInfo(conf.Server().Backup.Path.String())
|
||||
}
|
||||
|
||||
// Config info
|
||||
data.Config.LogLevel = conf.Server.LogLevel
|
||||
data.Config.LogFileConfigured = conf.Server.LogFile != ""
|
||||
data.Config.TLSConfigured = conf.Server.TLSEnabled()
|
||||
data.Config.DefaultBackgroundURLSet = conf.Server.UILoginBackgroundURL == consts.DefaultUILoginBackgroundURL
|
||||
data.Config.EnableArtworkPrecache = conf.Server.EnableArtworkPrecache
|
||||
data.Config.EnableArtworkUpload = conf.Server.EnableArtworkUpload
|
||||
data.Config.CoverArtQuality = conf.Server.CoverArtQuality
|
||||
data.Config.EnableWebPEncoding = conf.Server.EnableWebPEncoding
|
||||
data.Config.UICoverArtSize = conf.Server.UICoverArtSize
|
||||
data.Config.EnableCoverAnimation = conf.Server.EnableCoverAnimation
|
||||
data.Config.EnableNowPlaying = conf.Server.EnableNowPlaying
|
||||
data.Config.EnableDownloads = conf.Server.EnableDownloads
|
||||
data.Config.EnableSharing = conf.Server.EnableSharing
|
||||
data.Config.EnableStarRating = conf.Server.EnableStarRating
|
||||
data.Config.EnableLastFM = conf.Server.LastFM.Enabled && conf.Server.LastFM.ApiKey != "" && conf.Server.LastFM.Secret != ""
|
||||
data.Config.EnableListenBrainz = conf.Server.ListenBrainz.Enabled
|
||||
data.Config.EnableDeezer = conf.Server.Deezer.Enabled
|
||||
data.Config.EnableMediaFileCoverArt = conf.Server.EnableMediaFileCoverArt
|
||||
data.Config.EnableJukebox = conf.Server.Jukebox.Enabled
|
||||
data.Config.EnablePrometheus = conf.Server.Prometheus.Enabled
|
||||
data.Config.TranscodingCacheSize = conf.Server.TranscodingCacheSize
|
||||
data.Config.ImageCacheSize = conf.Server.ImageCacheSize
|
||||
data.Config.SessionTimeout = uint64(math.Trunc(conf.Server.SessionTimeout.Seconds()))
|
||||
data.Config.SearchFullString = conf.Server.Search.FullString
|
||||
data.Config.SearchBackend = conf.Server.Search.Backend
|
||||
data.Config.RecentlyAddedByModTime = conf.Server.RecentlyAddedByModTime
|
||||
data.Config.PreferSortTags = conf.Server.PreferSortTags
|
||||
data.Config.BackupSchedule = conf.Server.Backup.Schedule
|
||||
data.Config.BackupCount = conf.Server.Backup.Count
|
||||
data.Config.DevActivityPanel = conf.Server.DevActivityPanel
|
||||
data.Config.ScannerEnabled = conf.Server.Scanner.Enabled
|
||||
data.Config.ScannerExtractor = conf.Server.Scanner.Extractor
|
||||
data.Config.ScanSchedule = conf.Server.Scanner.Schedule
|
||||
data.Config.ScanWatcherWait = uint64(math.Trunc(conf.Server.Scanner.WatcherWait.Seconds()))
|
||||
data.Config.ScanOnStartup = conf.Server.Scanner.ScanOnStartup
|
||||
data.Config.EnableScheduledDBAnalyze = conf.Server.EnableScheduledDBAnalyze
|
||||
data.Config.ReverseProxyConfigured = conf.Server.ExtAuth.TrustedSources != ""
|
||||
data.Config.HasCustomPID = conf.Server.PID.Track != consts.DefaultTrackPID || conf.Server.PID.Album != consts.DefaultAlbumPID
|
||||
data.Config.HasCustomTags = len(conf.Server.Tags) > 0
|
||||
data.Config.LogLevel = conf.Server().LogLevel
|
||||
data.Config.LogFileConfigured = conf.Server().LogFile != ""
|
||||
data.Config.TLSConfigured = conf.Server().TLSEnabled()
|
||||
data.Config.DefaultBackgroundURLSet = conf.Server().UILoginBackgroundURL == consts.DefaultUILoginBackgroundURL
|
||||
data.Config.EnableArtworkPrecache = conf.Server().EnableArtworkPrecache
|
||||
data.Config.EnableArtworkUpload = conf.Server().EnableArtworkUpload
|
||||
data.Config.CoverArtQuality = conf.Server().CoverArtQuality
|
||||
data.Config.EnableWebPEncoding = conf.Server().EnableWebPEncoding
|
||||
data.Config.UICoverArtSize = conf.Server().UICoverArtSize
|
||||
data.Config.EnableCoverAnimation = conf.Server().EnableCoverAnimation
|
||||
data.Config.EnableNowPlaying = conf.Server().EnableNowPlaying
|
||||
data.Config.EnableDownloads = conf.Server().EnableDownloads
|
||||
data.Config.EnableSharing = conf.Server().EnableSharing
|
||||
data.Config.EnableStarRating = conf.Server().EnableStarRating
|
||||
data.Config.EnableLastFM = conf.Server().LastFM.Enabled && conf.Server().LastFM.ApiKey != "" && conf.Server().LastFM.Secret != ""
|
||||
data.Config.EnableListenBrainz = conf.Server().ListenBrainz.Enabled
|
||||
data.Config.EnableDeezer = conf.Server().Deezer.Enabled
|
||||
data.Config.EnableMediaFileCoverArt = conf.Server().EnableMediaFileCoverArt
|
||||
data.Config.EnableJukebox = conf.Server().Jukebox.Enabled
|
||||
data.Config.EnablePrometheus = conf.Server().Prometheus.Enabled
|
||||
data.Config.TranscodingCacheSize = conf.Server().TranscodingCacheSize
|
||||
data.Config.ImageCacheSize = conf.Server().ImageCacheSize
|
||||
data.Config.SessionTimeout = uint64(math.Trunc(conf.Server().SessionTimeout.Seconds()))
|
||||
data.Config.SearchFullString = conf.Server().Search.FullString
|
||||
data.Config.SearchBackend = conf.Server().Search.Backend
|
||||
data.Config.RecentlyAddedByModTime = conf.Server().RecentlyAddedByModTime
|
||||
data.Config.PreferSortTags = conf.Server().PreferSortTags
|
||||
data.Config.BackupSchedule = conf.Server().Backup.Schedule
|
||||
data.Config.BackupCount = conf.Server().Backup.Count
|
||||
data.Config.DevActivityPanel = conf.Server().DevActivityPanel
|
||||
data.Config.ScannerEnabled = conf.Server().Scanner.Enabled
|
||||
data.Config.ScannerExtractor = conf.Server().Scanner.Extractor
|
||||
data.Config.ScanSchedule = conf.Server().Scanner.Schedule
|
||||
data.Config.ScanWatcherWait = uint64(math.Trunc(conf.Server().Scanner.WatcherWait.Seconds()))
|
||||
data.Config.ScanOnStartup = conf.Server().Scanner.ScanOnStartup
|
||||
data.Config.EnableScheduledDBAnalyze = conf.Server().EnableScheduledDBAnalyze
|
||||
data.Config.ReverseProxyConfigured = conf.Server().ExtAuth.TrustedSources != ""
|
||||
data.Config.HasCustomPID = conf.Server().PID.Track != consts.DefaultTrackPID || conf.Server().PID.Album != consts.DefaultAlbumPID
|
||||
data.Config.HasCustomTags = len(conf.Server().Tags) > 0
|
||||
|
||||
return data
|
||||
})
|
||||
@ -296,12 +296,12 @@ func (c *insightsCollector) collect(ctx context.Context) []byte {
|
||||
}
|
||||
|
||||
// Collect plugins if permitted and enabled
|
||||
if conf.Server.DevEnablePluginsInsights && conf.Server.Plugins.Enabled {
|
||||
if conf.Server().DevEnablePluginsInsights && conf.Server().Plugins.Enabled {
|
||||
data.Plugins = c.collectPlugins(ctx)
|
||||
}
|
||||
|
||||
// Collect active players if permitted
|
||||
if conf.Server.DevEnablePlayerInsights {
|
||||
if conf.Server().DevEnablePlayerInsights {
|
||||
data.Library.ActivePlayers, err = c.ds.Player().CountByClient(ctx, model.QueryOptions{
|
||||
Filters: squirrel.Gt{"last_seen": time.Now().Add(-7 * 24 * time.Hour)},
|
||||
})
|
||||
|
||||
@ -5,15 +5,13 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("installedPackage", func() {
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.DataFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(GinkgoT().TempDir()) })
|
||||
})
|
||||
|
||||
It("returns empty when there's no .package file", func() {
|
||||
@ -65,6 +63,6 @@ var _ = Describe("hostingPlatform", func() {
|
||||
|
||||
func writePackageFile(content string) {
|
||||
GinkgoHelper()
|
||||
path := filepath.Join(conf.Server.DataFolder.String(), ".package")
|
||||
path := filepath.Join(conf.Server().DataFolder.String(), ".package")
|
||||
Expect(os.WriteFile(path, []byte(content), 0600)).To(Succeed())
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@ package metrics
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -15,3 +16,5 @@ func TestMetrics(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Metrics Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
@ -30,7 +30,7 @@ type metrics struct {
|
||||
}
|
||||
|
||||
func GetPrometheusInstance(ds model.DataStore) Metrics {
|
||||
if !conf.Server.Prometheus.Enabled {
|
||||
if !conf.Server().Prometheus.Enabled {
|
||||
return noopMetrics{}
|
||||
}
|
||||
|
||||
@ -91,9 +91,9 @@ func (m *metrics) RecordPluginRequest(_ context.Context, plugin, method string,
|
||||
func (m *metrics) GetHandler() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
if conf.Server.Prometheus.Password != "" {
|
||||
if conf.Server().Prometheus.Password != "" {
|
||||
r.Use(middleware.BasicAuth("metrics", map[string]string{
|
||||
consts.PrometheusAuthUser: conf.Server.Prometheus.Password,
|
||||
consts.PrometheusAuthUser: conf.Server().Prometheus.Password,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@ -75,9 +75,9 @@ func (j *Executor) wait() {
|
||||
// Path will always be an absolute path
|
||||
func createMPVCommand(deviceName string, filename string, socketName string) []string {
|
||||
// Parse the template structure using shell parsing to handle quoted arguments
|
||||
templateArgs, err := shellquote.Split(conf.Server.MPVCmdTemplate)
|
||||
templateArgs, err := shellquote.Split(conf.Server().MPVCmdTemplate)
|
||||
if err != nil {
|
||||
log.Error("Failed to parse MPV command template", "template", conf.Server.MPVCmdTemplate, err)
|
||||
log.Error("Failed to parse MPV command template", "template", conf.Server().MPVCmdTemplate, err)
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -105,8 +105,8 @@ func createMPVCommand(deviceName string, filename string, socketName string) []s
|
||||
// This is a 1:1 copy of the stuff in ffmpeg.go, need to be unified.
|
||||
func mpvCommand() (string, error) {
|
||||
mpvOnce.Do(func() {
|
||||
if conf.Server.MPVPath != "" {
|
||||
mpvPath = conf.Server.MPVPath
|
||||
if conf.Server().MPVPath != "" {
|
||||
mpvPath = conf.Server().MPVPath
|
||||
mpvPath, mpvErr = exec.LookPath(mpvPath)
|
||||
} else {
|
||||
mpvPath, mpvErr = exec.LookPath("mpv")
|
||||
|
||||
@ -3,6 +3,7 @@ package mpv
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -15,3 +16,5 @@ func TestMPV(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "MPV Suite")
|
||||
}
|
||||
|
||||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
@ -12,7 +12,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/conf/configtest"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/tests"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
@ -26,7 +25,6 @@ var _ = Describe("MPV", func() {
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
|
||||
// Reset MPV cache
|
||||
mpvOnce = sync.Once{}
|
||||
@ -43,13 +41,15 @@ var _ = Describe("MPV", func() {
|
||||
testScript = createMockMPVScript(tempDir)
|
||||
|
||||
// Configure test MPV path
|
||||
conf.Server.MPVPath = testScript
|
||||
conf.Update(func(c *conf.Options) { c.MPVPath = testScript })
|
||||
})
|
||||
|
||||
Describe("createMPVCommand", func() {
|
||||
Context("with default template", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.MPVCmdTemplate = "mpv --audio-device=%d --no-audio-display --pause %f --input-ipc-server=%s"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.MPVCmdTemplate = "mpv --audio-device=%d --no-audio-display --pause %f --input-ipc-server=%s"
|
||||
})
|
||||
})
|
||||
|
||||
It("creates correct command with simple paths", func() {
|
||||
@ -93,7 +93,9 @@ var _ = Describe("MPV", func() {
|
||||
Context("with snapcast template (issue #3619)", func() {
|
||||
BeforeEach(func() {
|
||||
// This is the template that fails with naive space splitting
|
||||
conf.Server.MPVCmdTemplate = "mpv --no-audio-display --pause %f --input-ipc-server=%s --audio-channels=stereo --audio-samplerate=48000 --audio-format=s16 --ao=pcm --ao-pcm-file=/audio/snapcast_fifo"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.MPVCmdTemplate = "mpv --no-audio-display --pause %f --input-ipc-server=%s --audio-channels=stereo --audio-samplerate=48000 --audio-format=s16 --ao=pcm --ao-pcm-file=/audio/snapcast_fifo"
|
||||
})
|
||||
})
|
||||
|
||||
It("creates correct command for snapcast integration", func() {
|
||||
@ -116,7 +118,9 @@ var _ = Describe("MPV", func() {
|
||||
Context("with wrapper script template", func() {
|
||||
BeforeEach(func() {
|
||||
// Test case that would break with naive splitting due to quoted arguments
|
||||
conf.Server.MPVCmdTemplate = `/tmp/mpv.sh --no-audio-display --pause %f --input-ipc-server=%s --audio-channels=stereo`
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.MPVCmdTemplate = `/tmp/mpv.sh --no-audio-display --pause %f --input-ipc-server=%s --audio-channels=stereo`
|
||||
})
|
||||
})
|
||||
|
||||
It("handles wrapper script paths", func() {
|
||||
@ -134,7 +138,9 @@ var _ = Describe("MPV", func() {
|
||||
|
||||
Context("with extra spaces in template", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.MPVCmdTemplate = "mpv --audio-device=%d --no-audio-display --pause %f --input-ipc-server=%s"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.MPVCmdTemplate = "mpv --audio-device=%d --no-audio-display --pause %f --input-ipc-server=%s"
|
||||
})
|
||||
})
|
||||
|
||||
It("handles extra spaces correctly", func() {
|
||||
@ -152,7 +158,9 @@ var _ = Describe("MPV", func() {
|
||||
Context("with paths containing spaces in template arguments", func() {
|
||||
BeforeEach(func() {
|
||||
// Template with spaces in the path arguments themselves
|
||||
conf.Server.MPVCmdTemplate = `mpv --no-audio-display --pause %f --ao-pcm-file="/audio/my folder/snapcast_fifo" --input-ipc-server=%s`
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.MPVCmdTemplate = `mpv --no-audio-display --pause %f --ao-pcm-file="/audio/my folder/snapcast_fifo" --input-ipc-server=%s`
|
||||
})
|
||||
})
|
||||
|
||||
It("handles spaces in quoted template argument paths", func() {
|
||||
@ -173,7 +181,9 @@ var _ = Describe("MPV", func() {
|
||||
Context("with malformed template", func() {
|
||||
BeforeEach(func() {
|
||||
// Template with unmatched quotes that will cause shell parsing to fail
|
||||
conf.Server.MPVCmdTemplate = `mpv --no-audio-display --pause %f --input-ipc-server=%s --ao-pcm-file="/unclosed/quote`
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.MPVCmdTemplate = `mpv --no-audio-display --pause %f --input-ipc-server=%s --ao-pcm-file="/unclosed/quote`
|
||||
})
|
||||
})
|
||||
|
||||
It("returns nil when shell parsing fails", func() {
|
||||
@ -184,7 +194,7 @@ var _ = Describe("MPV", func() {
|
||||
|
||||
Context("with empty template", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.MPVCmdTemplate = ""
|
||||
conf.Update(func(c *conf.Options) { c.MPVCmdTemplate = "" })
|
||||
})
|
||||
|
||||
It("returns empty slice for empty template", func() {
|
||||
@ -196,7 +206,9 @@ var _ = Describe("MPV", func() {
|
||||
|
||||
Describe("start", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.MPVCmdTemplate = "mpv --audio-device=%d --no-audio-display --pause %f --input-ipc-server=%s"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.MPVCmdTemplate = "mpv --audio-device=%d --no-audio-display --pause %f --input-ipc-server=%s"
|
||||
})
|
||||
})
|
||||
|
||||
It("executes MPV command and captures arguments correctly", func() {
|
||||
@ -252,7 +264,9 @@ var _ = Describe("MPV", func() {
|
||||
|
||||
Context("with complex snapcast configuration", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Server.MPVCmdTemplate = "mpv --no-audio-display --pause %f --input-ipc-server=%s --audio-channels=stereo --audio-samplerate=48000 --audio-format=s16 --ao=pcm --ao-pcm-file=/audio/snapcast_fifo"
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.MPVCmdTemplate = "mpv --no-audio-display --pause %f --input-ipc-server=%s --audio-channels=stereo --audio-samplerate=48000 --audio-format=s16 --ao=pcm --ao-pcm-file=/audio/snapcast_fifo"
|
||||
})
|
||||
})
|
||||
|
||||
It("passes all snapcast arguments correctly", func() {
|
||||
@ -318,7 +332,7 @@ var _ = Describe("MPV", func() {
|
||||
})
|
||||
|
||||
It("finds the configured MPV path", func() {
|
||||
conf.Server.MPVPath = testScript
|
||||
conf.Update(func(c *conf.Options) { c.MPVPath = testScript })
|
||||
path, err := mpvCommand()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(path).To(Equal(testScript))
|
||||
@ -329,8 +343,7 @@ var _ = Describe("MPV", func() {
|
||||
var testMediaFile model.MediaFile
|
||||
|
||||
BeforeEach(func() {
|
||||
DeferCleanup(configtest.SetupConfig())
|
||||
conf.Server.MPVPath = testScript
|
||||
conf.Update(func(c *conf.Options) { c.MPVPath = testScript })
|
||||
|
||||
// Create a test media file
|
||||
testMediaFile = model.MediaFile{
|
||||
@ -342,7 +355,9 @@ var _ = Describe("MPV", func() {
|
||||
Context("with malformed template", func() {
|
||||
BeforeEach(func() {
|
||||
// Template with unmatched quotes that will cause shell parsing to fail
|
||||
conf.Server.MPVCmdTemplate = `mpv --no-audio-display --pause %f --input-ipc-server=%s --ao-pcm-file="/unclosed/quote`
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.MPVCmdTemplate = `mpv --no-audio-display --pause %f --input-ipc-server=%s --ao-pcm-file="/unclosed/quote`
|
||||
})
|
||||
})
|
||||
|
||||
It("returns error when createMPVCommand fails", func() {
|
||||
|
||||
@ -38,7 +38,7 @@ func GetInstance(ds model.DataStore) PlaybackServer {
|
||||
func (ps *playbackServer) Run(ctx context.Context) error {
|
||||
ps.ctx = &ctx
|
||||
|
||||
devices, err := ps.initDeviceStatus(ctx, conf.Server.Jukebox.Devices, conf.Server.Jukebox.Default)
|
||||
devices, err := ps.initDeviceStatus(ctx, conf.Server().Jukebox.Devices, conf.Server().Jukebox.Default)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user