diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 3bc539132..53ce9fe77 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -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$'` diff --git a/adapters/deezer/deezer.go b/adapters/deezer/deezer.go index d3570a29f..c64e2b1e6 100644 --- a/adapters/deezer/deezer.go +++ b/adapters/deezer/deezer.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) } }) diff --git a/adapters/deezer/deezer_suite_test.go b/adapters/deezer/deezer_suite_test.go index a42282da7..d7cfdb230 100644 --- a/adapters/deezer/deezer_suite_test.go +++ b/adapters/deezer/deezer_suite_test.go @@ -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() diff --git a/adapters/deezer/deezer_test.go b/adapters/deezer/deezer_test.go index 82d02c244..92c5bb5f6 100644 --- a/adapters/deezer/deezer_test.go +++ b/adapters/deezer/deezer_test.go @@ -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), diff --git a/adapters/lastfm/agent.go b/adapters/lastfm/agent.go index dbd73c30d..2ed5e3c74 100644 --- a/adapters/lastfm/agent.go +++ b/adapters/lastfm/agent.go @@ -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 diff --git a/adapters/lastfm/agent_test.go b/adapters/lastfm/agent_test.go index 0f68bd46b..ddfe520a9 100644 --- a/adapters/lastfm/agent_test.go +++ b/adapters/lastfm/agent_test.go @@ -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() { diff --git a/adapters/lastfm/auth_router.go b/adapters/lastfm/auth_router.go index ec1bb9290..3dc9c30b3 100644 --- a/adapters/lastfm/auth_router.go +++ b/adapters/lastfm/auth_router.go @@ -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() diff --git a/adapters/lastfm/lastfm_suite_test.go b/adapters/lastfm/lastfm_suite_test.go index d80923403..35e57535c 100644 --- a/adapters/lastfm/lastfm_suite_test.go +++ b/adapters/lastfm/lastfm_suite_test.go @@ -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() diff --git a/adapters/listenbrainz/agent.go b/adapters/listenbrainz/agent.go index a59a5393f..ac2c94187 100644 --- a/adapters/listenbrainz/agent.go +++ b/adapters/listenbrainz/agent.go @@ -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 diff --git a/adapters/listenbrainz/auth_router.go b/adapters/listenbrainz/auth_router.go index 1ff1a1495..38c87d41d 100644 --- a/adapters/listenbrainz/auth_router.go +++ b/adapters/listenbrainz/auth_router.go @@ -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 } diff --git a/adapters/listenbrainz/client.go b/adapters/listenbrainz/client.go index aae4fb51d..92473cc91 100644 --- a/adapters/listenbrainz/client.go +++ b/adapters/listenbrainz/client.go @@ -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) diff --git a/adapters/listenbrainz/client_test.go b/adapters/listenbrainz/client_test.go index ec0b0ac11..bb1bfabe3 100644 --- a/adapters/listenbrainz/client_test.go +++ b/adapters/listenbrainz/client_test.go @@ -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} diff --git a/adapters/listenbrainz/listenbrainz_suite_test.go b/adapters/listenbrainz/listenbrainz_suite_test.go index 64abbe46f..4d1b8f710 100644 --- a/adapters/listenbrainz/listenbrainz_suite_test.go +++ b/adapters/listenbrainz/listenbrainz_suite_test.go @@ -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() diff --git a/cmd/artwork.go b/cmd/artwork.go index 72685678e..1381b8db3 100644 --- a/cmd/artwork.go +++ b/cmd/artwork.go @@ -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: diff --git a/cmd/artwork_test.go b/cmd/artwork_test.go index df0ea0665..01b17e109 100644 --- a/cmd/artwork_test.go +++ b/cmd/artwork_test.go @@ -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()) }) }) diff --git a/cmd/backup.go b/cmd/backup.go index 6b3a94221..c91f0294c 100644 --- a/cmd/backup.go +++ b/cmd/backup.go @@ -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) diff --git a/cmd/cmd_suite_test.go b/cmd/cmd_suite_test.go index f2ddf6a9c..8deef25e6 100644 --- a/cmd/cmd_suite_test.go +++ b/cmd/cmd_suite_test.go @@ -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() diff --git a/cmd/inspect_test.go b/cmd/inspect_test.go index 728dc8770..eb35266b0 100644 --- a/cmd/inspect_test.go +++ b/cmd/inspect_test.go @@ -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()) diff --git a/cmd/plugin.go b/cmd/plugin.go index 7b8a9a393..a40a171e3 100644 --- a/cmd/plugin.go +++ b/cmd/plugin.go @@ -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)") } } diff --git a/cmd/root.go b/cmd/root.go index e39c55365..3a2a29e6d 100644 --- a/cmd/root.go +++ b/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 } diff --git a/cmd/root_test.go b/cmd/root_test.go index 423cd2a8f..0724fff6d 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -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} }) diff --git a/cmd/svc.go b/cmd/svc.go index 4e8b1fd85..b55b6c9d2 100644 --- a/cmd/svc.go +++ b/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 { diff --git a/cmd/utils.go b/cmd/utils.go index f35a31fb1..6f9a4f7de 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -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 } diff --git a/conf/configtest/configtest.go b/conf/configtest/configtest.go index cd0ac41ed..7712f4d59 100644 --- a/conf/configtest/configtest.go +++ b/conf/configtest/configtest.go @@ -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()) + } + }) } diff --git a/conf/configtest/configtest_suite_test.go b/conf/configtest/configtest_suite_test.go new file mode 100644 index 000000000..acf2ca1cc --- /dev/null +++ b/conf/configtest/configtest_suite_test.go @@ -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() diff --git a/conf/configtest/configtest_test.go b/conf/configtest/configtest_test.go new file mode 100644 index 000000000..7e3259837 --- /dev/null +++ b/conf/configtest/configtest_test.go @@ -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")) + }) + }) +}) diff --git a/conf/configuration.go b/conf/configuration.go index efa9cbf9a..676252c47 100644 --- a/conf/configuration.go +++ b/conf/configuration.go @@ -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() { diff --git a/conf/configuration_test.go b/conf/configuration_test.go index 8c4c8ab86..024949c6b 100644 --- a/conf/configuration_test.go +++ b/conf/configuration_test.go @@ -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()) }) }) diff --git a/conf/export_test.go b/conf/export_test.go index d1e1a6f99..dbea63cb5 100644 --- a/conf/export_test.go +++ b/conf/export_test.go @@ -1,7 +1,7 @@ package conf func ResetConf() { - Server = &configOptions{} + current.Store(&Options{}) } var SetViperDefaults = setViperDefaults diff --git a/conf/server.go b/conf/server.go new file mode 100644 index 000000000..106871826 --- /dev/null +++ b/conf/server.go @@ -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) + } +} diff --git a/conf/server_test.go b/conf/server_test.go new file mode 100644 index 000000000..1a782b2a8 --- /dev/null +++ b/conf/server_test.go @@ -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)) + }) +}) diff --git a/core/agents/agents.go b/core/agents/agents.go index 8ae3124ef..2d1ed95a4 100644 --- a/core/agents/agents.go +++ b/core/agents/agents.go @@ -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) diff --git a/core/agents/agents_plugin_test.go b/core/agents/agents_plugin_test.go index b2791c00e..62700d1be 100644 --- a/core/agents/agents_plugin_test.go +++ b/core/agents/agents_plugin_test.go @@ -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") diff --git a/core/agents/agents_suite_test.go b/core/agents/agents_suite_test.go index 54b3f093c..78551fc5f 100644 --- a/core/agents/agents_suite_test.go +++ b/core/agents/agents_suite_test.go @@ -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() diff --git a/core/agents/agents_test.go b/core/agents/agents_test.go index 6163c7f3c..73d1d702f 100644 --- a/core/agents/agents_test.go +++ b/core/agents/agents_test.go @@ -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()) }) diff --git a/core/archiver_test.go b/core/archiver_test.go index 178d1b6b9..fbb4f87e2 100644 --- a/core/archiver_test.go +++ b/core/archiver_test.go @@ -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"}}}, diff --git a/core/artwork/agent_images.go b/core/artwork/agent_images.go index 985abacd7..fb2f71a62 100644 --- a/core/artwork/agent_images.go +++ b/core/artwork/agent_images.go @@ -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) diff --git a/core/artwork/agent_images_test.go b/core/artwork/agent_images_test.go index d0c2429b0..320f37ebf 100644 --- a/core/artwork/agent_images_test.go +++ b/core/artwork/agent_images_test.go @@ -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) diff --git a/core/artwork/artwork.go b/core/artwork/artwork.go index 2a9ebe771..424dc8b0f 100644 --- a/core/artwork/artwork.go +++ b/core/artwork/artwork.go @@ -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) { diff --git a/core/artwork/artwork_suite_test.go b/core/artwork/artwork_suite_test.go index 921a77b89..4106a5d38 100644 --- a/core/artwork/artwork_suite_test.go +++ b/core/artwork/artwork_suite_test.go @@ -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 diff --git a/core/artwork/artwork_test.go b/core/artwork/artwork_test.go index 2e8ed070e..60856ece5 100644 --- a/core/artwork/artwork_test.go +++ b/core/artwork/artwork_test.go @@ -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, diff --git a/core/artwork/benchmark_pipeline_test.go b/core/artwork/benchmark_pipeline_test.go index 23d5954df..a59c9235b 100644 --- a/core/artwork/benchmark_pipeline_test.go +++ b/core/artwork/benchmark_pipeline_test.go @@ -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 diff --git a/core/artwork/e2e/acquire_serve_test.go b/core/artwork/e2e/acquire_serve_test.go index 8cfa54113..7569a585b 100644 --- a/core/artwork/e2e/acquire_serve_test.go +++ b/core/artwork/e2e/acquire_serve_test.go @@ -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}}) diff --git a/core/artwork/e2e/album_test.go b/core/artwork/e2e/album_test.go index 7b5e7b4a3..a66a996c0 100644 --- a/core/artwork/e2e/album_test.go +++ b/core/artwork/e2e/album_test.go @@ -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"), diff --git a/core/artwork/e2e/artist_test.go b/core/artwork/e2e/artist_test.go index 38c28a9b2..0bf7c9ac3 100644 --- a/core/artwork/e2e/artist_test.go +++ b/core/artwork/e2e/artist_test.go @@ -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"}), diff --git a/core/artwork/e2e/disc_test.go b/core/artwork/e2e/disc_test.go index 5fdd5f27b..d4001ba6e 100644 --- a/core/artwork/e2e/disc_test.go +++ b/core/artwork/e2e/disc_test.go @@ -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"), diff --git a/core/artwork/e2e/e2e_suite_test.go b/core/artwork/e2e/e2e_suite_test.go index d03e22228..fdeba3000 100644 --- a/core/artwork/e2e/e2e_suite_test.go +++ b/core/artwork/e2e/e2e_suite_test.go @@ -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" diff --git a/core/artwork/e2e/mediafile_test.go b/core/artwork/e2e/mediafile_test.go index 3ddb9dc48..30441fbe5 100644 --- a/core/artwork/e2e/mediafile_test.go +++ b/core/artwork/e2e/mediafile_test.go @@ -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"))) diff --git a/core/artwork/e2e/playlist_test.go b/core/artwork/e2e/playlist_test.go index 0d862b20e..489f60db1 100644 --- a/core/artwork/e2e/playlist_test.go +++ b/core/artwork/e2e/playlist_test.go @@ -82,7 +82,7 @@ var _ = Describe("Playlist artwork resolution", func() { // / // └── 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}) diff --git a/core/artwork/e2e/resolution_harness_test.go b/core/artwork/e2e/resolution_harness_test.go index fbd89925e..f976e210b 100644 --- a/core/artwork/e2e/resolution_harness_test.go +++ b/core/artwork/e2e/resolution_harness_test.go @@ -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) diff --git a/core/artwork/gate.go b/core/artwork/gate.go index aa2ad8f2f..c58abe67e 100644 --- a/core/artwork/gate.go +++ b/core/artwork/gate.go @@ -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) diff --git a/core/artwork/housekeeping.go b/core/artwork/housekeeping.go index 5ec701541..0db542dd8 100644 --- a/core/artwork/housekeeping.go +++ b/core/artwork/housekeeping.go @@ -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)}, } } diff --git a/core/artwork/housekeeping_test.go b/core/artwork/housekeeping_test.go index 0f501d0b1..45d313357 100644 --- a/core/artwork/housekeeping_test.go +++ b/core/artwork/housekeeping_test.go @@ -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"}, diff --git a/core/artwork/image_cache.go b/core/artwork/image_cache.go index b1970d21d..3973e936a 100644 --- a/core/artwork/image_cache.go +++ b/core/artwork/image_cache.go @@ -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) }), diff --git a/core/artwork/image_store.go b/core/artwork/image_store.go index 2ded3e636..5398fa533 100644 --- a/core/artwork/image_store.go +++ b/core/artwork/image_store.go @@ -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. diff --git a/core/artwork/processor.go b/core/artwork/processor.go index 78e625e94..17e88413e 100644 --- a/core/artwork/processor.go +++ b/core/artwork/processor.go @@ -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 diff --git a/core/artwork/processor_test.go b/core/artwork/processor_test.go index 8eec97cde..9b9ab3578 100644 --- a/core/artwork/processor_test.go +++ b/core/artwork/processor_test.go @@ -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("rate limited")) })) @@ -359,7 +357,7 @@ var _ = Describe("processor.acquire", func() { }) It("found-external: persists source as external: 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))) }) }) diff --git a/core/artwork/resize.go b/core/artwork/resize.go index 9b3ff46e5..78c4a664a 100644 --- a/core/artwork/resize.go +++ b/core/artwork/resize.go @@ -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) } diff --git a/core/artwork/resolve.go b/core/artwork/resolve.go index fb07332fe..cd58514d4 100644 --- a/core/artwork/resolve.go +++ b/core/artwork/resolve.go @@ -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 } diff --git a/core/artwork/resolve_test.go b/core/artwork/resolve_test.go index 2a36531bb..d8051025b 100644 --- a/core/artwork/resolve_test.go +++ b/core/artwork/resolve_test.go @@ -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()) diff --git a/core/artwork/trace_test.go b/core/artwork/trace_test.go index a16347457..d33a9b1fd 100644 --- a/core/artwork/trace_test.go +++ b/core/artwork/trace_test.go @@ -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") diff --git a/core/artwork/uploader.go b/core/artwork/uploader.go index 76526af3c..6fa85e0f3 100644 --- a/core/artwork/uploader.go +++ b/core/artwork/uploader.go @@ -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 { diff --git a/core/artwork/uploader_test.go b/core/artwork/uploader_test.go index b1420c935..994fa1abe 100644 --- a/core/artwork/uploader_test.go +++ b/core/artwork/uploader_test.go @@ -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))) }) }) diff --git a/core/artwork/worker.go b/core/artwork/worker.go index 4be99f92e..ff5d99e6e 100644 --- a/core/artwork/worker.go +++ b/core/artwork/worker.go @@ -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]. diff --git a/core/artwork/worker_soak_test.go b/core/artwork/worker_soak_test.go index 9be95cf2a..321040fe9 100644 --- a/core/artwork/worker_soak_test.go +++ b/core/artwork/worker_soak_test.go @@ -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{ diff --git a/core/artwork/worker_test.go b/core/artwork/worker_test.go index 80ca68bc3..83367ca05 100644 --- a/core/artwork/worker_test.go +++ b/core/artwork/worker_test.go @@ -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) }) diff --git a/core/auth/auth.go b/core/auth/auth.go index 1d521451a..b5cc38940 100644 --- a/core/auth/auth.go +++ b/core/auth/auth.go @@ -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)) diff --git a/core/auth/auth_test.go b/core/auth/auth_test.go index 05da7ec65..974242686 100644 --- a/core/auth/auth_test.go +++ b/core/auth/auth_test.go @@ -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() { diff --git a/core/core_suite_test.go b/core/core_suite_test.go index afa5fd910..2ecf2cace 100644 --- a/core/core_suite_test.go +++ b/core/core_suite_test.go @@ -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() diff --git a/core/external/extdata_suite_test.go b/core/external/extdata_suite_test.go index f059e76b3..21d5745ba 100644 --- a/core/external/extdata_suite_test.go +++ b/core/external/extdata_suite_test.go @@ -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() diff --git a/core/external/provider.go b/core/external/provider.go index 185725259..7214df333 100644 --- a/core/external/provider.go +++ b/core/external/provider.go @@ -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) } diff --git a/core/external/provider_topsongs_test.go b/core/external/provider_topsongs_test.go index 5d35ba914..6d1f190ea 100644 --- a/core/external/provider_topsongs_test.go +++ b/core/external/provider_topsongs_test.go @@ -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() diff --git a/core/external/provider_updatealbuminfo_test.go b/core/external/provider_updatealbuminfo_test.go index d2fd4364e..87243ad23 100644 --- a/core/external/provider_updatealbuminfo_test.go +++ b/core/external/provider_updatealbuminfo_test.go @@ -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", diff --git a/core/external/provider_updateartistinfo_test.go b/core/external/provider_updateartistinfo_test.go index 5e2087d35..b85e9862e 100644 --- a/core/external/provider_updateartistinfo_test.go +++ b/core/external/provider_updateartistinfo_test.go @@ -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"}, diff --git a/core/ffmpeg/ffmpeg.go b/core/ffmpeg/ffmpeg.go index af59178af..ce7c3a6c4 100644 --- a/core/ffmpeg/ffmpeg.go +++ b/core/ffmpeg/ffmpeg.go @@ -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") diff --git a/core/ffmpeg/ffmpeg_test.go b/core/ffmpeg/ffmpeg_test.go index 46684fe14..bc517da78 100644 --- a/core/ffmpeg/ffmpeg_test.go +++ b/core/ffmpeg/ffmpeg_test.go @@ -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() { diff --git a/core/ffmpeg/flac_streaminfo.go b/core/ffmpeg/flac_streaminfo.go index 878c28718..f4e70f3a9 100644 --- a/core/ffmpeg/flac_streaminfo.go +++ b/core/ffmpeg/flac_streaminfo.go @@ -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 diff --git a/core/ffmpeg/flac_streaminfo_test.go b/core/ffmpeg/flac_streaminfo_test.go index 6bf3503d7..7abc69564 100644 --- a/core/ffmpeg/flac_streaminfo_test.go +++ b/core/ffmpeg/flac_streaminfo_test.go @@ -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 } diff --git a/core/ffmpeg/mp3_xing.go b/core/ffmpeg/mp3_xing.go new file mode 100644 index 000000000..a5303c853 --- /dev/null +++ b/core/ffmpeg/mp3_xing.go @@ -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 +} diff --git a/core/ffmpeg/mp3_xing_test.go b/core/ffmpeg/mp3_xing_test.go new file mode 100644 index 000000000..c8d9e4213 --- /dev/null +++ b/core/ffmpeg/mp3_xing_test.go @@ -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 +} diff --git a/core/ffmpeg/piped_header.go b/core/ffmpeg/piped_header.go new file mode 100644 index 000000000..71f9ee754 --- /dev/null +++ b/core/ffmpeg/piped_header.go @@ -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 +} diff --git a/core/ffmpeg/piped_header_test.go b/core/ffmpeg/piped_header_test.go new file mode 100644 index 000000000..ce8436b93 --- /dev/null +++ b/core/ffmpeg/piped_header_test.go @@ -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 } diff --git a/core/library.go b/core/library.go index f1153da26..9f145f577 100644 --- a/core/library.go +++ b/core/library.go @@ -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 diff --git a/core/library_internal_test.go b/core/library_internal_test.go new file mode 100644 index 000000000..a2e88a06d --- /dev/null +++ b/core/library_internal_test.go @@ -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"), + ) +}) diff --git a/core/library_test.go b/core/library_test.go index e6ebb1974..a9355f882 100644 --- a/core/library_test.go +++ b/core/library_test.go @@ -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() { diff --git a/core/lyrics/lyrics.go b/core/lyrics/lyrics.go index d3e8d72b8..46a93314e 100644 --- a/core/lyrics/lyrics.go +++ b/core/lyrics/lyrics.go @@ -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 diff --git a/core/lyrics/lyrics_suite_test.go b/core/lyrics/lyrics_suite_test.go index c9fdcbae8..baf961ad1 100644 --- a/core/lyrics/lyrics_suite_test.go +++ b/core/lyrics/lyrics_suite_test.go @@ -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. diff --git a/core/lyrics/lyrics_test.go b/core/lyrics/lyrics_test.go index b00bcd576..b029d3351 100644 --- a/core/lyrics/lyrics_test.go +++ b/core/lyrics/lyrics_test.go @@ -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) diff --git a/core/matcher/doc.go b/core/matcher/doc.go index 1024bc274..5e4492b37 100644 --- a/core/matcher/doc.go +++ b/core/matcher/doc.go @@ -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: diff --git a/core/matcher/matcher.go b/core/matcher/matcher.go index 3eb4db152..5cc74ca25 100644 --- a/core/matcher/matcher.go +++ b/core/matcher/matcher.go @@ -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 { diff --git a/core/matcher/matcher_suite_test.go b/core/matcher/matcher_suite_test.go index 44877a3c8..ff50557ad 100644 --- a/core/matcher/matcher_suite_test.go +++ b/core/matcher/matcher_suite_test.go @@ -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() diff --git a/core/matcher/matcher_test.go b/core/matcher/matcher_test.go index 0f5389ca5..d3d6259ea 100644 --- a/core/matcher/matcher_test.go +++ b/core/matcher/matcher_test.go @@ -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() { diff --git a/core/metrics/insights.go b/core/metrics/insights.go index 1d2ff5df4..07f6f154a 100644 --- a/core/metrics/insights.go +++ b/core/metrics/insights.go @@ -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)}, }) diff --git a/core/metrics/insights_internal_test.go b/core/metrics/insights_internal_test.go index 74c8ce236..6babab282 100644 --- a/core/metrics/insights_internal_test.go +++ b/core/metrics/insights_internal_test.go @@ -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()) } diff --git a/core/metrics/metrics_suite_test.go b/core/metrics/metrics_suite_test.go index bae622e90..9677576c1 100644 --- a/core/metrics/metrics_suite_test.go +++ b/core/metrics/metrics_suite_test.go @@ -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() diff --git a/core/metrics/prometheus.go b/core/metrics/prometheus.go index c85706560..c8ab23b2a 100644 --- a/core/metrics/prometheus.go +++ b/core/metrics/prometheus.go @@ -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, })) } diff --git a/core/playback/mpv/mpv.go b/core/playback/mpv/mpv.go index 6696eca2a..2732edd38 100644 --- a/core/playback/mpv/mpv.go +++ b/core/playback/mpv/mpv.go @@ -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") diff --git a/core/playback/mpv/mpv_suite_test.go b/core/playback/mpv/mpv_suite_test.go index f8f827620..23b337c50 100644 --- a/core/playback/mpv/mpv_suite_test.go +++ b/core/playback/mpv/mpv_suite_test.go @@ -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() diff --git a/core/playback/mpv/mpv_test.go b/core/playback/mpv/mpv_test.go index 6754b39ac..31afb29de 100644 --- a/core/playback/mpv/mpv_test.go +++ b/core/playback/mpv/mpv_test.go @@ -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() { diff --git a/core/playback/playbackserver.go b/core/playback/playbackserver.go index 48e3bcfaf..43052dea6 100644 --- a/core/playback/playbackserver.go +++ b/core/playback/playbackserver.go @@ -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 } diff --git a/core/players.go b/core/players.go index 6fe86fd70..fd00a8e73 100644 --- a/core/players.go +++ b/core/players.go @@ -53,7 +53,7 @@ func (p *players) Register(ctx context.Context, playerID, client, userAgent, ip UserId: user.ID, Client: client, ScrobbleEnabled: true, - ReportRealPath: conf.Server.Subsonic.DefaultReportRealPath, + ReportRealPath: conf.Server().Subsonic.DefaultReportRealPath, } log.Info(ctx, "Registering new player", "id", plr.ID, "client", client, "username", username, "type", userAgent) } diff --git a/core/playlists/import.go b/core/playlists/import.go index b5991b095..4dda11a45 100644 --- a/core/playlists/import.go +++ b/core/playlists/import.go @@ -218,7 +218,7 @@ func (s *playlists) updatePlaylist(ctx context.Context, newPls *model.Playlist, newPls.OwnerID = owner.ID // For NSP files, Public may already be set from the file; for M3U, use server default if !newPls.IsSmartPlaylist() { - newPls.Public = conf.Server.DefaultPlaylistPublicVisibility + newPls.Public = conf.Server().DefaultPlaylistPublicVisibility } } return s.ds.Playlist().Put(ctx, newPls) diff --git a/core/playlists/import_test.go b/core/playlists/import_test.go index 25960f0fe..824cafc45 100644 --- a/core/playlists/import_test.go +++ b/core/playlists/import_test.go @@ -10,7 +10,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core/playlists" "github.com/navidrome/navidrome/model" @@ -44,7 +43,6 @@ var _ = Describe("Playlists - Import", func() { Describe("ImportFromFolder", func() { var folder *model.Folder BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) ds.MockedMediaFile = &mockedMediaFileRepo{} libPath, _ := os.Getwd() @@ -101,7 +99,7 @@ var _ = Describe("Playlists - Import", func() { }) It("parses #EXTALBUMARTURL with HTTP URL", func() { - conf.Server.EnableM3UExternalAlbumArt = true + conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true }) pls, err := ps.ImportFromFolder(ctx, folder, "pls-with-art-url.m3u") Expect(err).ToNot(HaveOccurred()) @@ -255,7 +253,7 @@ var _ = Describe("Playlists - Import", func() { }) It("ignores HTTP #EXTALBUMARTURL when EnableM3UExternalAlbumArt is false", func() { - conf.Server.EnableM3UExternalAlbumArt = false + conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = false }) tmpDir := GinkgoT().TempDir() m3u := "#EXTALBUMARTURL:https://example.com/cover.jpg\ntest.mp3\n" @@ -273,7 +271,7 @@ var _ = Describe("Playlists - Import", func() { }) It("updates ExternalImageURL on re-scan even when UploadedImage is set", func() { - conf.Server.EnableM3UExternalAlbumArt = true + conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true }) tmpDir := GinkgoT().TempDir() mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) @@ -411,7 +409,7 @@ var _ = Describe("Playlists - Import", func() { Expect(pls.Public).To(BeFalse()) }) It("uses server default when public field is absent", func() { - conf.Server.DefaultPlaylistPublicVisibility = true + conf.Update(func(c *conf.Options) { c.DefaultPlaylistPublicVisibility = true }) pls, err := ps.ImportFromFolder(ctx, folder, "recently_played.nsp") Expect(err).ToNot(HaveOccurred()) @@ -770,7 +768,6 @@ var _ = Describe("Playlists - Import", func() { Describe("ImportFile", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3", "test.ogg"}} }) @@ -1012,7 +1009,7 @@ var _ = Describe("Playlists - Import", func() { }) It("parses #EXTALBUMARTURL with HTTP URL via ImportM3U", func() { - conf.Server.EnableM3UExternalAlbumArt = true + conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true }) repo.data = []string{"tests/test.mp3"} m3u := "#EXTALBUMARTURL:https://example.com/cover.jpg\n/music/tests/test.mp3\n" @@ -1121,7 +1118,6 @@ var _ = Describe("Playlists - Import", func() { var folder model.Folder BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) folder = model.Folder{ LibraryPath: "/music", Path: "playlists/abc", @@ -1130,28 +1126,28 @@ var _ = Describe("Playlists - Import", func() { }) It("returns true if PlaylistsPath is empty", func() { - conf.Server.PlaylistsPath = "" + conf.Update(func(c *conf.Options) { c.PlaylistsPath = "" }) Expect(playlists.InPath(folder)).To(BeTrue()) }) It("returns true if PlaylistsPath is any (**/**)", func() { - conf.Server.PlaylistsPath = "**/**" + conf.Update(func(c *conf.Options) { c.PlaylistsPath = "**/**" }) Expect(playlists.InPath(folder)).To(BeTrue()) }) It("returns true if folder is in PlaylistsPath", func() { tests.SkipOnWindows("path separator bug (#TBD-path-sep-playlists)") - conf.Server.PlaylistsPath = "other/**:playlists/**" + conf.Update(func(c *conf.Options) { c.PlaylistsPath = "other/**:playlists/**" }) Expect(playlists.InPath(folder)).To(BeTrue()) }) It("returns false if folder is not in PlaylistsPath", func() { - conf.Server.PlaylistsPath = "other" + conf.Update(func(c *conf.Options) { c.PlaylistsPath = "other" }) Expect(playlists.InPath(folder)).To(BeFalse()) }) It("returns true if for a playlist in root of MusicFolder if PlaylistsPath is '.'", func() { - conf.Server.PlaylistsPath = "." + conf.Update(func(c *conf.Options) { c.PlaylistsPath = "." }) Expect(playlists.InPath(folder)).To(BeFalse()) folder2 := model.Folder{ diff --git a/core/playlists/parse_m3u.go b/core/playlists/parse_m3u.go index ab95b8850..cddae14a2 100644 --- a/core/playlists/parse_m3u.go +++ b/core/playlists/parse_m3u.go @@ -242,7 +242,7 @@ func resolveImageURL(value string, folder *model.Folder, matcher *model.LibraryM // HTTP(S) URLs — store as-is, but only if external album art is enabled if strings.HasPrefix(value, "http://") || strings.HasPrefix(value, "https://") { - if !conf.Server.EnableM3UExternalAlbumArt { + if !conf.Server().EnableM3UExternalAlbumArt { return "" } return value diff --git a/core/playlists/parse_nsp.go b/core/playlists/parse_nsp.go index a5b8b7c02..716f962a8 100644 --- a/core/playlists/parse_nsp.go +++ b/core/playlists/parse_nsp.go @@ -75,7 +75,7 @@ func (s *playlists) parseNSP(_ context.Context, pls *model.Playlist, reader io.R if nsp.Public != nil { pls.Public = *nsp.Public } else { - pls.Public = conf.Server.DefaultPlaylistPublicVisibility + pls.Public = conf.Server().DefaultPlaylistPublicVisibility } return nil } diff --git a/core/playlists/parse_nsp_test.go b/core/playlists/parse_nsp_test.go index d6d69866f..cc3230cc8 100644 --- a/core/playlists/parse_nsp_test.go +++ b/core/playlists/parse_nsp_test.go @@ -7,7 +7,6 @@ import ( "strings" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/criteria" . "github.com/onsi/ginkgo/v2" @@ -75,8 +74,7 @@ var _ = Describe("parseNSP", func() { }) It("uses server default when public field is absent", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultPlaylistPublicVisibility = true + conf.Update(func(c *conf.Options) { c.DefaultPlaylistPublicVisibility = true }) nsp := `{"all": [{"is": {"loved": true}}]}` pls := &model.Playlist{} @@ -86,8 +84,7 @@ var _ = Describe("parseNSP", func() { }) It("honors explicit public: false over server default", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultPlaylistPublicVisibility = true + conf.Update(func(c *conf.Options) { c.DefaultPlaylistPublicVisibility = true }) nsp := `{"public": false, "all": [{"is": {"loved": true}}]}` pls := &model.Playlist{} diff --git a/core/playlists/playlists.go b/core/playlists/playlists.go index c9bc03b97..76addbc70 100644 --- a/core/playlists/playlists.go +++ b/core/playlists/playlists.go @@ -74,11 +74,11 @@ func NewPlaylists(ds model.DataStore, imgUpload ImageUploadService) Playlists { } func InPath(folder model.Folder) bool { - if conf.Server.PlaylistsPath == "" { + if conf.Server().PlaylistsPath == "" { return true } rel, _ := filepath.Rel(folder.LibraryPath, folder.AbsolutePath()) - for path := range strings.SplitSeq(conf.Server.PlaylistsPath, string(filepath.ListSeparator)) { + for path := range strings.SplitSeq(conf.Server().PlaylistsPath, string(filepath.ListSeparator)) { if match, _ := doublestar.Match(path, rel); match { return true } diff --git a/core/playlists/playlists_suite_test.go b/core/playlists/playlists_suite_test.go index b57248490..cc057780d 100644 --- a/core/playlists/playlists_suite_test.go +++ b/core/playlists/playlists_suite_test.go @@ -3,6 +3,7 @@ package playlists_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 TestPlaylists(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Playlists Suite") } + +var _ = configtest.RestoreAfterEachSpec() diff --git a/core/playlists/playlists_test.go b/core/playlists/playlists_test.go index ec44de3bc..e110a23fc 100644 --- a/core/playlists/playlists_test.go +++ b/core/playlists/playlists_test.go @@ -7,7 +7,6 @@ import ( "strings" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core/playlists" "github.com/navidrome/navidrome/model" @@ -393,9 +392,8 @@ var _ = Describe("Playlists", func() { var tmpDir string BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) tmpDir = GinkgoT().TempDir() - conf.Server.DataFolder = conf.NewDir(tmpDir) + conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) }) mockPlsRepo.Data = map[string]*model.Playlist{ "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"}, @@ -457,9 +455,8 @@ var _ = Describe("Playlists", func() { var tmpDir string BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) tmpDir = GinkgoT().TempDir() - conf.Server.DataFolder = conf.NewDir(tmpDir) + conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) }) // Create a real image file on disk imgDir := filepath.Join(tmpDir, "artwork", "playlist") diff --git a/core/publicurl/publicurl.go b/core/publicurl/publicurl.go index 345606324..b7c58aefa 100644 --- a/core/publicurl/publicurl.go +++ b/core/publicurl/publicurl.go @@ -33,10 +33,10 @@ func ImageURL(ctx context.Context, artID model.ArtworkID, size int) string { // It uses ShareURL from config if available, otherwise falls back to the address the // client used to reach the server, recorded in the context. func PublicURL(ctx context.Context, u string, params url.Values) string { - if conf.Server.ShareURL == "" { + if conf.Server().ShareURL == "" { return AbsoluteURL(ctx, u, params) } - shareUrl, err := url.Parse(conf.Server.ShareURL) + shareUrl, err := url.Parse(conf.Server().ShareURL) if err != nil { return AbsoluteURL(ctx, u, params) } @@ -65,17 +65,17 @@ func AbsoluteURL(ctx context.Context, u string, params url.Values) string { return "" } if strings.HasPrefix(u, "/") { - buildUrl.Path = path.Join(conf.Server.BasePath, buildUrl.Path) - if conf.Server.BaseHost != "" { - buildUrl.Scheme = cmp.Or(conf.Server.BaseScheme, "http") - buildUrl.Host = conf.Server.BaseHost + buildUrl.Path = path.Join(conf.Server().BasePath, buildUrl.Path) + if conf.Server().BaseHost != "" { + buildUrl.Scheme = cmp.Or(conf.Server().BaseScheme, "http") + buildUrl.Host = conf.Server().BaseHost } else if scheme, host, ok := request.ServerAddressFrom(ctx); ok { buildUrl.Scheme = scheme buildUrl.Host = host } else { log.Debug(ctx, "Building a public URL with no public address available; set ShareURL to make it reachable", "url", u) - buildUrl.Scheme = gg.If(conf.Server.TLSEnabled(), "https", "http") - buildUrl.Host = "localhost:" + strconv.Itoa(conf.Server.Port) + buildUrl.Scheme = gg.If(conf.Server().TLSEnabled(), "https", "http") + buildUrl.Host = "localhost:" + strconv.Itoa(conf.Server().Port) } } if len(params) > 0 { diff --git a/core/publicurl/publicurl_test.go b/core/publicurl/publicurl_test.go index 0f8ea806c..1d01686a4 100644 --- a/core/publicurl/publicurl_test.go +++ b/core/publicurl/publicurl_test.go @@ -25,15 +25,14 @@ func TestPublicURL(t *testing.T) { RunSpecs(t, "Public URL Suite") } +var _ = configtest.RestoreAfterEachSpec() + var _ = Describe("Public URL Utilities", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) Describe("PublicURL", func() { When("ShareURL is set", func() { BeforeEach(func() { - conf.Server.ShareURL = "https://share.example.com" + conf.Update(func(c *conf.Options) { c.ShareURL = "https://share.example.com" }) }) It("uses ShareURL as the base", func() { @@ -52,7 +51,7 @@ var _ = Describe("Public URL Utilities", func() { When("ShareURL includes a path", func() { BeforeEach(func() { - conf.Server.ShareURL = "https://example.com/navi" + conf.Update(func(c *conf.Options) { c.ShareURL = "https://example.com/navi" }) }) It("prepends the ShareURL path to the resource", func() { @@ -67,7 +66,7 @@ var _ = Describe("Public URL Utilities", func() { }) It("handles trailing slash in ShareURL path", func() { - conf.Server.ShareURL = "https://example.com/navi/" + conf.Update(func(c *conf.Options) { c.ShareURL = "https://example.com/navi/" }) result := publicurl.PublicURL(context.Background(), "/share/img/hash", nil) Expect(result).To(Equal("https://example.com/navi/share/img/hash")) }) @@ -75,7 +74,7 @@ var _ = Describe("Public URL Utilities", func() { When("ShareURL is not set", func() { BeforeEach(func() { - conf.Server.ShareURL = "" + conf.Update(func(c *conf.Options) { c.ShareURL = "" }) }) It("falls back to AbsoluteURL with request", func() { @@ -85,7 +84,7 @@ var _ = Describe("Public URL Utilities", func() { }) It("falls back to localhost on the configured port without request", func() { - conf.Server.Port = 4533 + conf.Update(func(c *conf.Options) { c.Port = 4533 }) result := publicurl.PublicURL(context.Background(), "/path/to/resource", nil) Expect(result).To(Equal("http://localhost:4533/path/to/resource")) }) @@ -95,9 +94,11 @@ var _ = Describe("Public URL Utilities", func() { Describe("AbsoluteURL", func() { When("BaseHost is set", func() { BeforeEach(func() { - conf.Server.BaseHost = "configured.example.com" - conf.Server.BaseScheme = "https" - conf.Server.BasePath = "" + conf.Update(func(c *conf.Options) { + c.BaseHost = "configured.example.com" + c.BaseScheme = "https" + c.BasePath = "" + }) }) It("uses BaseHost and BaseScheme", func() { @@ -106,7 +107,7 @@ var _ = Describe("Public URL Utilities", func() { }) It("defaults to http scheme if BaseScheme is empty", func() { - conf.Server.BaseScheme = "" + conf.Update(func(c *conf.Options) { c.BaseScheme = "" }) result := publicurl.AbsoluteURL(context.Background(), "/path/to/resource", nil) Expect(result).To(Equal("http://configured.example.com/path/to/resource")) }) @@ -114,8 +115,10 @@ var _ = Describe("Public URL Utilities", func() { When("BaseHost is not set", func() { BeforeEach(func() { - conf.Server.BaseHost = "" - conf.Server.BasePath = "" + conf.Update(func(c *conf.Options) { + c.BaseHost = "" + c.BasePath = "" + }) }) It("extracts host from request", func() { @@ -125,22 +128,26 @@ var _ = Describe("Public URL Utilities", func() { }) It("falls back to localhost on the configured port without request", func() { - conf.Server.Port = 8080 + conf.Update(func(c *conf.Options) { c.Port = 8080 }) result := publicurl.AbsoluteURL(context.Background(), "/path/to/resource", nil) Expect(result).To(Equal("http://localhost:8080/path/to/resource")) }) It("uses https in the fallback when TLS is configured", func() { - conf.Server.Port = 4533 - conf.Server.TLSCert = "cert.pem" - conf.Server.TLSKey = "key.pem" + conf.Update(func(c *conf.Options) { + c.Port = 4533 + c.TLSCert = "cert.pem" + c.TLSKey = "key.pem" + }) result := publicurl.AbsoluteURL(context.Background(), "/path/to/resource", nil) Expect(result).To(Equal("https://localhost:4533/path/to/resource")) }) It("stays on http when only the certificate is configured", func() { - conf.Server.Port = 4533 - conf.Server.TLSCert = "cert.pem" + conf.Update(func(c *conf.Options) { + c.Port = 4533 + c.TLSCert = "cert.pem" + }) result := publicurl.AbsoluteURL(context.Background(), "/path/to/resource", nil) Expect(result).To(Equal("http://localhost:4533/path/to/resource")) }) @@ -148,9 +155,11 @@ var _ = Describe("Public URL Utilities", func() { When("BasePath is set", func() { BeforeEach(func() { - conf.Server.BasePath = "/navidrome" - conf.Server.BaseHost = "example.com" - conf.Server.BaseScheme = "https" + conf.Update(func(c *conf.Options) { + c.BasePath = "/navidrome" + c.BaseHost = "example.com" + c.BaseScheme = "https" + }) }) It("prepends BasePath to the URL", func() { @@ -165,8 +174,10 @@ var _ = Describe("Public URL Utilities", func() { }) It("includes query parameters", func() { - conf.Server.BaseHost = "example.com" - conf.Server.BaseScheme = "https" + conf.Update(func(c *conf.Options) { + c.BaseHost = "example.com" + c.BaseScheme = "https" + }) params := url.Values{"key": []string{"value"}} result := publicurl.AbsoluteURL(context.Background(), "/path", params) Expect(result).To(Equal("https://example.com/path?key=value")) @@ -175,7 +186,7 @@ var _ = Describe("Public URL Utilities", func() { Describe("ImageURL", func() { BeforeEach(func() { - conf.Server.ShareURL = "https://share.example.com" + conf.Update(func(c *conf.Options) { c.ShareURL = "https://share.example.com" }) // Initialize JWT auth for token generation auth.PublicTokenAuth = jwtauth.New("HS256", []byte("test secret"), nil) }) @@ -216,7 +227,7 @@ var _ = Describe("Public URL Utilities", func() { }) It("prefers ShareURL over the address in the context", func() { - conf.Server.ShareURL = "https://share.example.com" + conf.Update(func(c *conf.Options) { c.ShareURL = "https://share.example.com" }) ctx := request.WithServerAddress(context.Background(), "https", "music.example.com") result := publicurl.ImageURL(ctx, artID, 0) @@ -224,7 +235,7 @@ var _ = Describe("Public URL Utilities", func() { }) It("falls back to localhost on the configured port when no address is available", func() { - conf.Server.Port = 4533 + conf.Update(func(c *conf.Options) { c.Port = 4533 }) result := publicurl.ImageURL(context.Background(), artID, 0) Expect(result).To(HavePrefix("http://localhost:4533/share/img/")) }) diff --git a/core/quickconnect/quickconnect.go b/core/quickconnect/quickconnect.go index 9b69bc904..322c46592 100644 --- a/core/quickconnect/quickconnect.go +++ b/core/quickconnect/quickconnect.go @@ -85,7 +85,7 @@ func newStore() *quickConnect { // Enabled reports whether users can approve codes from the web UI, which needs the Jellyfin API. func Enabled() bool { - return conf.Server.Jellyfin.Enabled && conf.Server.Jellyfin.QuickConnect + return conf.Server().Jellyfin.Enabled && conf.Server().Jellyfin.QuickConnect } func (qc *quickConnect) Initiate(device Device) (Request, error) { diff --git a/core/scrobbler/play_tracker.go b/core/scrobbler/play_tracker.go index 541a8e92b..71d75f415 100644 --- a/core/scrobbler/play_tracker.go +++ b/core/scrobbler/play_tracker.go @@ -141,7 +141,7 @@ func newPlayTracker(ds model.DataStore, broker events.Broker, pluginManager Plug prSignal: make(chan struct{}, 1), prWorkerDone: make(chan struct{}), } - enableNowPlaying := conf.Server.EnableNowPlaying + enableNowPlaying := conf.Server().EnableNowPlaying m.OnExpiration(func(_ string, info PlaybackSession) { log.Debug("PlaybackSession expired", "clientId", info.PlayerId, "mediaId", info.MediaFile.ID, "state", info.State, "username", info.Username, "userId", info.UserId) @@ -363,22 +363,29 @@ func (p *playTracker) ReportPlayback(ctx context.Context, params ReportPlaybackP case StateStopped: var loadedMF *model.MediaFile haveVerdict := false - if !params.IgnoreScrobble && player.ScrobbleEnabled { + if !params.IgnoreScrobble { mf, err := p.ds.MediaFile().GetWithParticipants(ctx, params.MediaId) if err != nil { - return err - } - loadedMF = mf - filtered = p.isFilteredOut(ctx, mf) - haveVerdict = true - trackDurationMs := int64(mf.Duration * 1000) - threshold := min(trackDurationMs*50/100, 240_000) - if params.PositionMs >= threshold { - err = p.incPlay(ctx, mf, now) - if err != nil { - log.Warn(ctx, "Error updating play counts", "id", mf.ID, "track", mf.Title, "user", user.UserName, err) + // If the track is not found, do not treat it as a fatal error. + // Log it and move on so that the session can still be closed + log.Warn(ctx, "Cannot find track for scrobbling", "id", params.MediaId, "user", user.UserName, err) + } else { + loadedMF = mf + filtered = p.isFilteredOut(ctx, mf) + haveVerdict = true + trackDurationMs := int64(mf.Duration * 1000) + threshold := min(trackDurationMs*50/100, 240_000) + if params.PositionMs >= threshold { + // To be consistent with Submit (/rest/scrobble?submission=true), play should be incremented even if + // scrobbling is disabled + err = p.incPlay(ctx, mf, now) + if err != nil { + log.Warn(ctx, "Error updating play counts", "id", mf.ID, "track", mf.Title, "user", user.UserName, err) + } + if player.ScrobbleEnabled { + p.dispatchScrobble(ctx, mf, now, filtered) + } } - p.dispatchScrobble(ctx, mf, now, filtered) } } p.sessionsMu.Lock() @@ -422,7 +429,7 @@ func (p *playTracker) ReportPlayback(ctx context.Context, params ReportPlaybackP p.enqueuePlaybackReport(ctx, stoppedInfo, filtered) } - if conf.Server.EnableNowPlaying { + if conf.Server().EnableNowPlaying { p.broker.SendBroadcastMessage(ctx, &events.NowPlayingCount{Count: p.playMap.Len()}) } @@ -518,7 +525,7 @@ func (p *playTracker) incPlay(ctx context.Context, track *model.MediaFile, times return err } } - if conf.Server.EnableScrobbleHistory { + if conf.Server().EnableScrobbleHistory { return tx.Scrobble().RecordScrobble(ctx, track.ID, timestamp) } return nil diff --git a/core/scrobbler/play_tracker_test.go b/core/scrobbler/play_tracker_test.go index 045827811..a2e4d7c4a 100644 --- a/core/scrobbler/play_tracker_test.go +++ b/core/scrobbler/play_tracker_test.go @@ -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" @@ -90,7 +89,6 @@ var _ = Describe("PlayTracker", func() { var fake *fakeScrobbler BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) ctx = GinkgoT().Context() ctx = request.WithUser(ctx, model.User{ID: "u-1", Libraries: model.Libraries{{ID: 1}}}) ctx = request.WithPlayer(ctx, model.Player{ScrobbleEnabled: true}) @@ -229,7 +227,7 @@ var _ = Describe("PlayTracker", func() { }) It("does not send event when disabled", func() { - conf.Server.EnableNowPlaying = false + conf.Update(func(c *conf.Options) { c.EnableNowPlaying = false }) tracker = newPlayTracker(ds, eventBroker, nil) info := PlaybackSession{MediaFile: track, Start: time.Now(), Username: "user"} _ = tracker.playMap.AddWithTTL("player-2", info, 10*time.Millisecond) @@ -315,12 +313,15 @@ var _ = Describe("PlayTracker", func() { Expect(fake.ScrobbleCalled.Load()).To(BeFalse()) }) - It("does not send track to agent if player is not enabled to send scrobbles", func() { + It("does not send track to agent if player is not enabled to send scrobbles (but should still track internally)", func() { ctx = request.WithPlayer(ctx, model.Player{ScrobbleEnabled: false}) err := tracker.Submit(ctx, []Submission{{TrackID: "123", Timestamp: time.Now()}}) Expect(err).ToNot(HaveOccurred()) + Expect(track.PlayCount).To(Equal(int64(1))) + Expect(album.PlayCount).To(Equal(int64(1))) + Expect(fake.ScrobbleCalled.Load()).To(BeFalse()) }) @@ -351,7 +352,7 @@ var _ = Describe("PlayTracker", func() { Context("Scrobble History", func() { It("records scrobble in repository", func() { - conf.Server.EnableScrobbleHistory = true + conf.Update(func(c *conf.Options) { c.EnableScrobbleHistory = true }) ctx = request.WithUser(ctx, model.User{ID: "u-1", UserName: "user-1"}) ts := time.Now() @@ -368,7 +369,7 @@ var _ = Describe("PlayTracker", func() { }) It("does not record scrobble when history is disabled", func() { - conf.Server.EnableScrobbleHistory = false + conf.Update(func(c *conf.Options) { c.EnableScrobbleHistory = false }) ctx = request.WithUser(ctx, model.User{ID: "u-1", UserName: "user-1"}) ts := time.Now() @@ -721,7 +722,7 @@ var _ = Describe("PlayTracker", func() { }) It("does NOT broadcast when EnableNowPlaying is false", func() { - conf.Server.EnableNowPlaying = false + conf.Update(func(c *conf.Options) { c.EnableNowPlaying = false }) tracker = newPlayTracker(ds, eventBroker, nil) tracker.builtinScrobblers["fake"] = fake @@ -811,7 +812,8 @@ var _ = Describe("PlayTracker", func() { MediaId: "123", PositionMs: 90000, State: "stopped", PlaybackRate: 1.0, ClientId: defaultClientId, }) Expect(err).ToNot(HaveOccurred()) - Expect(track.PlayCount).To(Equal(int64(0))) + Expect(track.PlayCount).To(Equal(int64(1))) + Consistently(func() bool { return fake.ScrobbleCalled.Load() }).Should(BeFalse()) }) It("scrobbles twice for two separate sessions of same song", func() { diff --git a/core/scrobbler/scrobbler_suite_test.go b/core/scrobbler/scrobbler_suite_test.go index 9ec3ba127..039581e8f 100644 --- a/core/scrobbler/scrobbler_suite_test.go +++ b/core/scrobbler/scrobbler_suite_test.go @@ -3,6 +3,7 @@ package scrobbler 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, "Scrobbler Test Suite") } + +var _ = configtest.RestoreAfterEachSpec() diff --git a/core/share.go b/core/share.go index 33c8996ef..3dd78c027 100644 --- a/core/share.go +++ b/core/share.go @@ -92,7 +92,7 @@ func (r *shareRepositoryWrapper) Save(ctx context.Context, s *model.Share) (stri } s.ID = id if V(s.ExpiresAt).IsZero() { - s.ExpiresAt = new(time.Now().Add(conf.Server.DefaultShareExpiration)) + s.ExpiresAt = new(time.Now().Add(conf.Server().DefaultShareExpiration)) } s.ResourceType, err = r.resourceType(ctx, s.ResourceIDs) diff --git a/core/storage/local/local.go b/core/storage/local/local.go index e2ce00a1b..0d60b73ae 100644 --- a/core/storage/local/local.go +++ b/core/storage/local/local.go @@ -28,10 +28,10 @@ type localStorage struct { } func newLocalStorage(u url.URL) storage.Storage { - newExtractor, ok := extractors[conf.Server.Scanner.Extractor] + newExtractor, ok := extractors[conf.Server().Scanner.Extractor] if !ok || newExtractor == nil { - if conf.Server.Scanner.Extractor != consts.DefaultScannerExtractor { - log.Warn("Extractor not found, using default", "extractor", conf.Server.Scanner.Extractor, "default", consts.DefaultScannerExtractor) + if conf.Server().Scanner.Extractor != consts.DefaultScannerExtractor { + log.Warn("Extractor not found, using default", "extractor", conf.Server().Scanner.Extractor, "default", consts.DefaultScannerExtractor) } newExtractor = extractors[consts.DefaultScannerExtractor] if newExtractor == nil { diff --git a/core/storage/local/local_suite_test.go b/core/storage/local/local_suite_test.go index 5934cde5d..23332fc02 100644 --- a/core/storage/local/local_suite_test.go +++ b/core/storage/local/local_suite_test.go @@ -3,6 +3,7 @@ package local 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 TestLocal(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Local Storage Suite") } + +var _ = configtest.RestoreAfterEachSpec() diff --git a/core/storage/local/local_test.go b/core/storage/local/local_test.go index 3ed6d6fd9..159250841 100644 --- a/core/storage/local/local_test.go +++ b/core/storage/local/local_test.go @@ -11,7 +11,6 @@ import ( "github.com/djherbis/times" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/storage" "github.com/navidrome/navidrome/model/metadata" @@ -24,7 +23,6 @@ var _ = Describe("LocalStorage", func() { var testExtractor *mockTestExtractor BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) // Create a temporary directory for testing var err error @@ -42,7 +40,7 @@ var _ = Describe("LocalStorage", func() { RegisterExtractor("test", func(fs.FS, string) Extractor { return testExtractor }) - conf.Server.Scanner.Extractor = "test" + conf.Update(func(c *conf.Options) { c.Scanner.Extractor = "test" }) }) Describe("newLocalStorage", func() { @@ -157,7 +155,7 @@ var _ = Describe("LocalStorage", func() { }) It("falls back to the default extractor instead of crashing", func() { - conf.Server.Scanner.Extractor = "nonexistent-extractor" + conf.Update(func(c *conf.Options) { c.Scanner.Extractor = "nonexistent-extractor" }) u, err := storage.LocalPathToURL(tempDir) Expect(err).ToNot(HaveOccurred()) diff --git a/core/storage/local/watcher_test.go b/core/storage/local/watcher_test.go index 37387c76a..d9e71c274 100644 --- a/core/storage/local/watcher_test.go +++ b/core/storage/local/watcher_test.go @@ -24,7 +24,7 @@ var _ = XDescribe("Watcher", func() { tmpFolder = GinkgoT().TempDir() local.RegisterExtractor("noop", func(fs fs.FS, path string) local.Extractor { return noopExtractor{} }) - conf.Server.Scanner.Extractor = "noop" + conf.Update(func(c *conf.Options) { c.Scanner.Extractor = "noop" }) ls, err := storage.For(tmpFolder) Expect(err).ToNot(HaveOccurred()) @@ -141,7 +141,7 @@ func (s noopExtractor) Version() string var _ = Describe("Watcher.Start", func() { It("returns an error instead of hanging when the path cannot be watched", func() { local.RegisterExtractor("noop", func(fs fs.FS, path string) local.Extractor { return noopExtractor{} }) - conf.Server.Scanner.Extractor = "noop" + conf.Update(func(c *conf.Options) { c.Scanner.Extractor = "noop" }) ls, err := storage.For(filepath.Join(GinkgoT().TempDir(), "does-not-exist")) Expect(err).ToNot(HaveOccurred()) lsw := ls.(storage.Watcher) diff --git a/core/stream/codec.go b/core/stream/codec.go index 56d163324..64b10343f 100644 --- a/core/stream/codec.go +++ b/core/stream/codec.go @@ -32,9 +32,10 @@ func isLosslessFormat(format string) bool { return false } -// normalizeSourceSampleRate adjusts the source sample rate for codecs that store -// it differently than PCM. Currently handles DSD (÷8): +// normalizeSourceSampleRate adjusts a sample rate read from tags for codecs that +// store it differently than PCM. Currently handles DSD (÷8): // DSD64=2822400→352800, DSD128=5644800→705600, etc. +// ffprobe already reports DSD at this rate, so probe data needs no adjustment. // For other codecs, returns the rate unchanged. func normalizeSourceSampleRate(sampleRate int, codec string) int { if strings.EqualFold(codec, "dsd") && sampleRate > 0 { @@ -43,14 +44,28 @@ func normalizeSourceSampleRate(sampleRate int, codec string) int { return sampleRate } +// dsdMaxPCMSampleRate caps DSD transcoded to lossless PCM. It divides every +// 44.1kHz-based DSD rate exactly, DSD carries mostly its own shaped noise above +// it, and many clients cannot play 352.8kHz PCM. +const dsdMaxPCMSampleRate = 88200 + +// targetSampleRate returns the sample rate for a transcoded stream before codec +// and client limits are applied, with DSD capped when capDSD is set. +func targetSampleRate(srcSampleRate int, srcCodec string, capDSD bool) int { + if capDSD && strings.EqualFold(srcCodec, "dsd") { + return min(srcSampleRate, dsdMaxPCMSampleRate) + } + return srcSampleRate +} + // targetBitDepth returns the bit depth for a transcoded stream: 0 for lossy // targets (they have no PCM bit depth), otherwise the source depth, with DSD -// adjusted to the 24-bit PCM that ffmpeg produces. +// (1 bit in tags, 8 in ffprobe) adjusted to the 24-bit PCM that ffmpeg produces. func targetBitDepth(srcBitDepth int, srcCodec string, targetIsLossless bool) int { if !targetIsLossless { return 0 } - if strings.EqualFold(srcCodec, "dsd") && srcBitDepth == 1 { + if strings.EqualFold(srcCodec, "dsd") { return 24 } return srcBitDepth diff --git a/core/stream/decider.go b/core/stream/decider.go index 38839cdf0..a98588838 100644 --- a/core/stream/decider.go +++ b/core/stream/decider.go @@ -143,7 +143,7 @@ func buildSourceStream(mf *model.MediaFile, probe *ffmpeg.AudioProbeResult) Deta } else { sd.Codec = mf.AudioCodec() sd.Bitrate = mf.BitRate - sd.SampleRate = mf.SampleRate + sd.SampleRate = normalizeSourceSampleRate(mf.SampleRate, sd.Codec) sd.BitDepth = gg.V(mf.BitDepth) sd.Channels = mf.Channels } @@ -224,11 +224,9 @@ func (s *deciderService) checkDirectPlayProfile(src *Details, profile *DirectPla } // Check codec-specific limitations - for _, codecProfile := range clientInfo.CodecProfiles { - if strings.EqualFold(codecProfile.Type, CodecProfileTypeAudio) && matchesCodec(src.Codec, []string{codecProfile.Name}) { - if reason := checkLimitations(src, codecProfile.Limitations); reason != "" { - return reason - } + for codecProfile := range audioCodecProfiles(clientInfo, src.Codec) { + if reason := checkLimitations(src, codecProfile.Limitations); reason != "" { + return reason } } @@ -265,17 +263,20 @@ func (s *deciderService) computeTranscodedStream(ctx context.Context, src *Detai return nil, "" } + targetCodec := strings.ToLower(profile.AudioCodec) + if targetCodec == "" { + targetCodec = targetFormat + } + capDSD := targetIsLossless && !hasUpperBoundLimitation(clientInfo, targetCodec, LimitationAudioSamplerate) + ts := &Details{ Container: responseContainer, - Codec: strings.ToLower(profile.AudioCodec), - SampleRate: normalizeSourceSampleRate(src.SampleRate, src.Codec), + Codec: targetCodec, + SampleRate: targetSampleRate(src.SampleRate, src.Codec, capDSD), Channels: src.Channels, BitDepth: targetBitDepth(src.BitDepth, src.Codec, targetIsLossless), IsLossless: targetIsLossless, } - if ts.Codec == "" { - ts.Codec = targetFormat - } // Apply codec-intrinsic sample rate adjustments before codec profile limitations if fixedRate := codecFixedOutputSampleRate(ts.Codec); fixedRate > 0 { @@ -400,13 +401,7 @@ func (s *deciderService) computeBitrate(ctx context.Context, src *Details, targe // Returns false if the profile should be rejected. func (s *deciderService) applyCodecLimitations(ctx context.Context, sourceBitrate int, targetFormat string, targetIsLossless bool, clientInfo *ClientInfo, ts *Details) bool { targetCodec := ts.Codec - for _, codecProfile := range clientInfo.CodecProfiles { - if !strings.EqualFold(codecProfile.Type, CodecProfileTypeAudio) { - continue - } - if !matchesCodec(targetCodec, []string{codecProfile.Name}) { - continue - } + for codecProfile := range audioCodecProfiles(clientInfo, targetCodec) { for _, lim := range codecProfile.Limitations { result := applyLimitation(sourceBitrate, &lim, ts) if strings.EqualFold(lim.Name, LimitationAudioBitrate) && targetIsLossless && result == adjustAdjusted { @@ -432,7 +427,7 @@ func (s *deciderService) ensureProbed(ctx context.Context, mf *model.MediaFile) if mf.ProbeData != "" { return nil, nil } - if !conf.Server.DevEnableMediaFileProbe { + if !conf.Server().DevEnableMediaFileProbe { return nil, nil } diff --git a/core/stream/decider_test.go b/core/stream/decider_test.go index 01fef1249..e5de9154d 100644 --- a/core/stream/decider_test.go +++ b/core/stream/decider_test.go @@ -6,7 +6,6 @@ import ( "fmt" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/ffmpeg" "github.com/navidrome/navidrome/model" @@ -719,7 +718,7 @@ var _ = Describe("Decider", func() { Context("DSD sample rate conversion", func() { It("converts DSD sample rate to PCM-equivalent in decision", func() { - mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: new(1)}) + mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 352800, BitDepth: new(8)}) ci := &ClientInfo{ MaxTranscodingAudioBitrate: 320, TranscodingProfiles: []Profile{ @@ -730,7 +729,7 @@ var _ = Describe("Decider", func() { Expect(err).ToNot(HaveOccurred()) Expect(decision.CanTranscode).To(BeTrue()) Expect(decision.TargetFormat).To(Equal("mp3")) - // DSD64 2822400 / 8 = 352800, capped by MP3 max of 48000 + // DSD64 probes as 352800, capped by MP3 max of 48000 Expect(decision.TranscodeStream.SampleRate).To(Equal(48000)) Expect(decision.TargetSampleRate).To(Equal(48000)) // MP3 is lossy: no bit depth on the transcoded stream @@ -738,54 +737,79 @@ var _ = Describe("Decider", func() { Expect(decision.TargetBitDepth).To(BeZero()) }) - It("converts DSD sample rate for FLAC target without codec limit", func() { - mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: new(1)}) - ci := &ClientInfo{ - TranscodingProfiles: []Profile{ - {Container: "flac", AudioCodec: "flac", Protocol: ProtocolHTTP}, + sampleRateLimit := func(codec, comparison string, values ...string) CodecProfile { + return CodecProfile{ + Type: CodecProfileTypeAudio, + Name: codec, + Limitations: []Limitation{ + {Name: LimitationAudioSamplerate, Comparison: comparison, Values: values, Required: true}, }, } - decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) - Expect(err).ToNot(HaveOccurred()) - Expect(decision.CanTranscode).To(BeTrue()) - Expect(decision.TargetFormat).To(Equal("flac")) - // DSD64 2822400 / 8 = 352800, FLAC has no hard max - Expect(decision.TranscodeStream.SampleRate).To(Equal(352800)) - Expect(decision.TargetSampleRate).To(Equal(352800)) - // DSD 1-bit → 24-bit PCM - Expect(decision.TranscodeStream.BitDepth).To(Equal(24)) - Expect(decision.TargetBitDepth).To(Equal(24)) - }) + } - It("applies codec profile limit to DSD-converted FLAC sample rate", func() { - mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: new(1)}) + DescribeTable("DSD to FLAC sample rate", + func(srcSampleRate int, codecProfiles []CodecProfile, expectedRate int) { + mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: srcSampleRate, BitDepth: new(8)}) + ci := &ClientInfo{ + TranscodingProfiles: []Profile{ + {Container: "flac", AudioCodec: "flac", Protocol: ProtocolHTTP}, + }, + CodecProfiles: codecProfiles, + } + decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) + Expect(err).ToNot(HaveOccurred()) + Expect(decision.CanTranscode).To(BeTrue()) + Expect(decision.TargetFormat).To(Equal("flac")) + Expect(decision.TranscodeStream.SampleRate).To(Equal(expectedRate)) + Expect(decision.TargetSampleRate).To(Equal(expectedRate)) + Expect(decision.TranscodeStream.BitDepth).To(Equal(24)) + Expect(decision.TargetBitDepth).To(Equal(24)) + }, + Entry("caps DSD64 at 88.2kHz when the client declares no limit", 352800, nil, 88200), + Entry("caps DSD128 at 88.2kHz when the client declares no limit", 705600, nil, 88200), + Entry("uses a declared upper limit instead of the cap", 352800, + []CodecProfile{sampleRateLimit("flac", ComparisonLessThanEqual, "192000")}, 192000), + Entry("picks the closest rate from a declared list", 352800, + []CodecProfile{sampleRateLimit("flac", ComparisonEquals, "96000", "192000")}, 192000), + Entry("applies a declared limit below the cap", 352800, + []CodecProfile{sampleRateLimit("flac", ComparisonLessThanEqual, "48000")}, 48000), + Entry("keeps the cap when the declared limit is a lower bound", 352800, + []CodecProfile{sampleRateLimit("flac", ComparisonGreaterThanEqual, "44100")}, 88200), + Entry("keeps the cap when the declared limit excludes a rate", 352800, + []CodecProfile{sampleRateLimit("flac", ComparisonNotEquals, "48000")}, 88200), + Entry("keeps the cap when the declared limit has no values", 352800, + []CodecProfile{sampleRateLimit("flac", ComparisonLessThanEqual)}, 88200), + Entry("keeps the cap when the declared limit has no numeric values", 352800, + []CodecProfile{sampleRateLimit("flac", ComparisonLessThanEqual, "high")}, 88200), + Entry("keeps the cap when the declared rate limit is for another codec", 352800, + []CodecProfile{ + sampleRateLimit("mp3", ComparisonLessThanEqual, "192000"), + {Type: CodecProfileTypeAudio, Name: "flac", Limitations: []Limitation{ + {Name: LimitationAudioChannels, Comparison: ComparisonLessThanEqual, Values: []string{"2"}, Required: true}, + }}, + }, 88200), + ) + + It("normalizes DSD sample rate from tags when there is no probe data", func() { + conf.Update(func(c *conf.Options) { c.DevEnableMediaFileProbe = false }) + + mf := &model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: new(1)} ci := &ClientInfo{ TranscodingProfiles: []Profile{ {Container: "flac", AudioCodec: "flac", Protocol: ProtocolHTTP}, }, - CodecProfiles: []CodecProfile{ - { - Type: CodecProfileTypeAudio, - Name: "flac", - Limitations: []Limitation{ - {Name: LimitationAudioSamplerate, Comparison: ComparisonLessThanEqual, Values: []string{"48000"}, Required: true}, - }, - }, - }, } decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) Expect(err).ToNot(HaveOccurred()) Expect(decision.CanTranscode).To(BeTrue()) - // DSD64 2822400 / 8 = 352800, capped by codec profile limit of 48000 - Expect(decision.TranscodeStream.SampleRate).To(Equal(48000)) - Expect(decision.TargetSampleRate).To(Equal(48000)) - // DSD 1-bit → 24-bit PCM - Expect(decision.TranscodeStream.BitDepth).To(Equal(24)) + // Tags store the 1-bit DSD64 rate, ffprobe reports 352800 + Expect(decision.SourceStream.SampleRate).To(Equal(352800)) + Expect(decision.TargetSampleRate).To(Equal(88200)) Expect(decision.TargetBitDepth).To(Equal(24)) }) It("applies audioBitdepth limitation to DSD-converted bit depth", func() { - mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: new(1)}) + mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 352800, BitDepth: new(8)}) ci := &ClientInfo{ TranscodingProfiles: []Profile{ {Container: "flac", AudioCodec: "flac", Protocol: ProtocolHTTP}, @@ -803,7 +827,7 @@ var _ = Describe("Decider", func() { decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) Expect(err).ToNot(HaveOccurred()) Expect(decision.CanTranscode).To(BeTrue()) - // DSD 1-bit → 24-bit PCM, then capped by codec profile limit to 16-bit + // DSD → 24-bit PCM, then capped by codec profile limit to 16-bit Expect(decision.TranscodeStream.BitDepth).To(Equal(16)) Expect(decision.TargetBitDepth).To(Equal(16)) }) @@ -1021,7 +1045,7 @@ var _ = Describe("Decider", func() { Context("AAC max sample rate", func() { It("caps sample rate at 96000 for AAC", func() { - mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 2822400, BitDepth: new(1)}) + mf := withProbe(&model.MediaFile{ID: "1", Suffix: "dsf", Codec: "DSD", BitRate: 5644, Channels: 2, SampleRate: 352800, BitDepth: new(8)}) ci := &ClientInfo{ MaxTranscodingAudioBitrate: 320, TranscodingProfiles: []Profile{ @@ -1031,7 +1055,7 @@ var _ = Describe("Decider", func() { decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) Expect(err).ToNot(HaveOccurred()) Expect(decision.CanTranscode).To(BeTrue()) - // DSD64 2822400 / 8 = 352800, capped by AAC max of 96000 + // DSD64 probes as 352800, capped by AAC max of 96000 Expect(decision.TranscodeStream.SampleRate).To(Equal(96000)) }) }) @@ -1277,8 +1301,7 @@ var _ = Describe("Decider", func() { }) It("skips ffprobe when DevEnableMediaFileProbe is false", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DevEnableMediaFileProbe = false + conf.Update(func(c *conf.Options) { c.DevEnableMediaFileProbe = false }) mf := &model.MediaFile{ID: "probe-4", Suffix: "mp3"} // Set a result — if ffprobe were called, ProbeData would be populated diff --git a/core/stream/legacy_client.go b/core/stream/legacy_client.go index 5b732c3e2..d528eff04 100644 --- a/core/stream/legacy_client.go +++ b/core/stream/legacy_client.go @@ -20,12 +20,12 @@ func buildLegacyClientInfo(mf *model.MediaFile, reqFormat string, reqBitRate int switch { case reqFormat != "": targetFormat = reqFormat - case reqBitRate > 0 && reqBitRate < mf.BitRate && conf.Server.DefaultDownsamplingFormat != "": - targetFormat = conf.Server.DefaultDownsamplingFormat - case playerMaxBitRate > 0 && playerMaxBitRate < mf.BitRate && conf.Server.DefaultDownsamplingFormat != "": + case reqBitRate > 0 && reqBitRate < mf.BitRate && conf.Server().DefaultDownsamplingFormat != "": + targetFormat = conf.Server().DefaultDownsamplingFormat + case playerMaxBitRate > 0 && playerMaxBitRate < mf.BitRate && conf.Server().DefaultDownsamplingFormat != "": // Server-side player MaxBitRate alone forces downsampling, even when the // client sent no format/bitrate params (issue #5583, legacy /stream path). - targetFormat = conf.Server.DefaultDownsamplingFormat + targetFormat = conf.Server().DefaultDownsamplingFormat } if targetFormat != "" { @@ -79,7 +79,7 @@ func (s *deciderService) ResolveRequest(ctx context.Context, mf *model.MediaFile // No compatible profile for the requested format — retry with DefaultDownsamplingFormat // TODO: validate DefaultDownsamplingFormat at startup to warn about unsupported values - fallbackFormat := conf.Server.DefaultDownsamplingFormat + fallbackFormat := conf.Server().DefaultDownsamplingFormat if reqFormat != "" && fallbackFormat != "" && !strings.EqualFold(reqFormat, fallbackFormat) { log.Warn(ctx, "Requested format not available, falling back to default downsampling format", "requestedFormat", reqFormat, "fallbackFormat", fallbackFormat, "id", mf.ID) diff --git a/core/stream/legacy_client_test.go b/core/stream/legacy_client_test.go index ad3417faf..c525041e9 100644 --- a/core/stream/legacy_client_test.go +++ b/core/stream/legacy_client_test.go @@ -4,7 +4,6 @@ import ( "context" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -74,8 +73,7 @@ var _ = Describe("buildLegacyClientInfo", func() { }) It("uses default downsampling format for bitrate-only downsampling", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultDownsamplingFormat = "opus" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "opus" }) ci := buildLegacyClientInfo(mf, "", 128, 0) @@ -102,8 +100,7 @@ var _ = Describe("buildLegacyClientInfo", func() { }) It("uses default downsampling format when player MaxBitRate is below source and no format/bitrate", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultDownsamplingFormat = "opus" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "opus" }) ci := buildLegacyClientInfo(mf, "", 0, 256) @@ -115,8 +112,7 @@ var _ = Describe("buildLegacyClientInfo", func() { }) It("does not downsample when player MaxBitRate is >= source bitrate", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultDownsamplingFormat = "opus" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "opus" }) ci := buildLegacyClientInfo(mf, "", 0, 960) @@ -126,8 +122,7 @@ var _ = Describe("buildLegacyClientInfo", func() { }) It("does not downsample when DefaultDownsamplingFormat is empty even with player cap", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultDownsamplingFormat = "" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "" }) ci := buildLegacyClientInfo(mf, "", 0, 256) @@ -137,8 +132,7 @@ var _ = Describe("buildLegacyClientInfo", func() { }) It("prefers explicit request format over player cap", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultDownsamplingFormat = "opus" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "opus" }) ci := buildLegacyClientInfo(mf, "mp3", 0, 256) @@ -211,8 +205,7 @@ var _ = Describe("ResolveRequest", func() { }) It("downsamples when only bitrate is specified below source", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultDownsamplingFormat = "opus" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "opus" }) mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: new(16)}) @@ -336,8 +329,7 @@ var _ = Describe("ResolveRequest", func() { }) It("downsamples using DefaultDownsamplingFormat when only player MaxBitRate is set (no format/bitrate)", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultDownsamplingFormat = "opus" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "opus" }) mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: new(16)}) playerCtx := request.WithPlayer(ctx, model.Player{MaxBitRate: 256}) @@ -350,8 +342,7 @@ var _ = Describe("ResolveRequest", func() { }) It("serves raw when only player MaxBitRate is set but no DefaultDownsamplingFormat", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultDownsamplingFormat = "" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "" }) mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: new(16)}) playerCtx := request.WithPlayer(ctx, model.Player{MaxBitRate: 256}) @@ -365,8 +356,7 @@ var _ = Describe("ResolveRequest", func() { Context("fallback for unknown format", func() { It("falls back to DefaultDownsamplingFormat", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultDownsamplingFormat = "opus" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "opus" }) mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100}) @@ -377,8 +367,7 @@ var _ = Describe("ResolveRequest", func() { }) It("falls back to raw when DefaultDownsamplingFormat is empty", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultDownsamplingFormat = "" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "" }) mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100}) @@ -389,8 +378,7 @@ var _ = Describe("ResolveRequest", func() { }) It("falls back to raw when DefaultDownsamplingFormat is also invalid", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultDownsamplingFormat = "xyz" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "xyz" }) mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100}) @@ -401,8 +389,7 @@ var _ = Describe("ResolveRequest", func() { }) It("preserves bitrate when falling back to DefaultDownsamplingFormat", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultDownsamplingFormat = "opus" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "opus" }) mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: new(16)}) diff --git a/core/stream/limitations.go b/core/stream/limitations.go index ab70d6c07..32763e9f9 100644 --- a/core/stream/limitations.go +++ b/core/stream/limitations.go @@ -1,6 +1,8 @@ package stream import ( + "iter" + "slices" "strconv" "strings" ) @@ -48,6 +50,47 @@ func checkLimitations(src *Details, limitations []Limitation) string { return "" } +func audioCodecProfiles(clientInfo *ClientInfo, codec string) iter.Seq[CodecProfile] { + return func(yield func(CodecProfile) bool) { + for _, cp := range clientInfo.CodecProfiles { + if strings.EqualFold(cp.Type, CodecProfileTypeAudio) && matchesCodec(codec, []string{cp.Name}) { + if !yield(cp) { + return + } + } + } + } +} + +func hasUpperBoundLimitation(clientInfo *ClientInfo, codec, name string) bool { + for cp := range audioCodecProfiles(clientInfo, codec) { + if slices.ContainsFunc(cp.Limitations, func(lim Limitation) bool { + return strings.EqualFold(lim.Name, name) && len(upperBounds(lim.Comparison, lim.Values)) > 0 + }) { + return true + } + } + return false +} + +// upperBounds returns the values a limitation can lower a number to, none for >=, != or non-numeric limits. +func upperBounds(comparison string, values []string) []int { + switch comparison { + case ComparisonLessThanEqual: + values = values[:min(len(values), 1)] + case ComparisonEquals: + default: + return nil + } + var bounds []int + for _, s := range values { + if v, ok := parseInt(s); ok { + bounds = append(bounds, v) + } + } + return bounds +} + // applyLimitation adjusts a transcoded stream parameter to satisfy the limitation. // Returns the adjustment result. func applyLimitation(sourceBitrate int, lim *Limitation, ts *Details) adjustResult { @@ -81,14 +124,11 @@ func applyIntLimitation(comparison string, values []string, current int, setter switch comparison { case ComparisonLessThanEqual: - limit, ok := parseInt(values[0]) - if !ok { + bounds := upperBounds(comparison, values) + if len(bounds) == 0 || current <= bounds[0] { return adjustNone } - if current <= limit { - return adjustNone - } - setter(limit) + setter(bounds[0]) return adjustAdjusted case ComparisonGreaterThanEqual: limit, ok := parseInt(values[0]) @@ -101,21 +141,17 @@ func applyIntLimitation(comparison string, values []string, current int, setter // Cannot upscale return adjustCannotFit case ComparisonEquals: - // Check if current value matches any allowed value - for _, v := range values { - if limit, ok := parseInt(v); ok && current == limit { - return adjustNone - } + bounds := upperBounds(comparison, values) + if slices.Contains(bounds, current) { + return adjustNone } // Find the closest allowed value below current (don't upscale) var closest int found := false - for _, v := range values { - if limit, ok := parseInt(v); ok && limit < current { - if !found || limit > closest { - closest = limit - found = true - } + for _, limit := range bounds { + if limit < current && (!found || limit > closest) { + closest = limit + found = true } } if found { diff --git a/core/stream/media_streamer.go b/core/stream/media_streamer.go index c250b0c4e..8de09a4e1 100644 --- a/core/stream/media_streamer.go +++ b/core/stream/media_streamer.go @@ -33,7 +33,7 @@ func NewMediaStreamer(ds model.DataStore, t ffmpeg.FFmpeg, cache TranscodingCach ds: ds, transcoder: t, cache: cache, - limiter: NewTranscodeLimiter(conf.Server.Transcoding.MaxConcurrent, conf.Server.Transcoding.MaxConcurrentPerUser), + limiter: NewTranscodeLimiter(conf.Server().Transcoding.MaxConcurrent, conf.Server().Transcoding.MaxConcurrentPerUser), } } @@ -80,7 +80,7 @@ func (ms *mediaStreamer) NewStream(ctx context.Context, mf *model.MediaFile, req format = "raw" bitRate = 0 } - s := &Stream{ctx: ctx, mf: mf, format: format, bitRate: bitRate} + s := &Stream{ctx: ctx, mf: mf, format: format, bitRate: bitRate, offset: req.Offset} filePath := mf.AbsolutePath() if format == "raw" { @@ -137,6 +137,7 @@ type Stream struct { mf *model.MediaFile bitRate int format string + offset int io.ReadCloser io.Seeker } @@ -146,16 +147,24 @@ func (s *Stream) Duration() float32 { return s.mf.Duration } func (s *Stream) ContentType() string { return mime.TypeByExtension("." + s.format) } func (s *Stream) Name() string { return s.mf.Title + "." + s.format } func (s *Stream) ModTime() time.Time { return s.mf.UpdatedAt } -func (s *Stream) EstimatedContentLength() int { - return int(s.mf.Duration * float32(s.bitRate) / 8 * 1024) + +// EstimatedContentLength returns the expected size of the transcoded output, from the part of the track +// after the requested offset. It returns 0 when the track has no duration left to estimate from. +func (s *Stream) EstimatedContentLength() int64 { + remaining := max(float64(s.mf.Duration)-float64(max(s.offset, 0)), 0) + return int64(remaining * float64(s.bitRate) * 1000 / 8) } // Serve writes the stream to the HTTP response. For seekable streams it uses http.ServeContent // (supporting range requests). For non-seekable streams it writes directly and logs any errors. -// Returns the number of bytes written and an error only when it fails with 0 bytes written +// Returns the number of bytes written, or -1 when it does not count them (http.ServeContent and HEAD +// requests), and an error only when it fails with 0 bytes written // (meaning the HTTP 200 status has not been flushed yet and the caller can still send an error response). // Once bytes are on the wire it panics with http.ErrAbortHandler instead, aborting the response. // Empty output (0 bytes, no error) is logged but not treated as an error. +// With estimateContentLength=true, a non-seekable stream declares an estimated Content-Length. With +// DevMatchEstimatedContentLength, the body is also cut or zero-padded to match it, so clients never +// see a body that disagrees with the header. func (s *Stream) Serve(ctx context.Context, w http.ResponseWriter, r *http.Request) (int64, error) { if s.Seekable() { http.ServeContent(w, r, s.Name(), s.ModTime(), s) @@ -165,19 +174,31 @@ func (s *Stream) Serve(ctx context.Context, w http.ResponseWriter, r *http.Reque w.Header().Set("Accept-Ranges", "none") w.Header().Set("Content-Type", s.ContentType()) + // limit > 0 only when the body must match the declared Content-Length. + var limit int64 if req.Params(r).BoolOr("estimateContentLength", false) { - length := strconv.Itoa(s.EstimatedContentLength()) - log.Trace(ctx, "Estimated content-length", "contentLength", length) - w.Header().Set("Content-Length", length) + length := s.EstimatedContentLength() + if conf.Server().DevMatchEstimatedContentLength { + limit = length + } + if length > 0 { + log.Trace(ctx, "Estimated content-length", "contentLength", length) + w.Header().Set("Content-Length", strconv.FormatInt(length, 10)) + } } if r.Method == http.MethodHead { go func() { _, _ = io.Copy(io.Discard, s) }() - return 0, nil + return -1, nil + } + + var src io.Reader = s + if limit > 0 { + src = io.LimitReader(s, limit) } id := s.mf.ID - c, err := io.Copy(w, s) + c, err := io.Copy(w, src) if err != nil { log.Error(ctx, "Error sending transcoded file", "id", id, err) if c == 0 { @@ -188,15 +209,41 @@ func (s *Stream) Serve(ctx context.Context, w http.ResponseWriter, r *http.Reque panic(http.ErrAbortHandler) } if c == 0 { + // Nothing is sent yet, so drop the estimate instead of padding a body that holds no audio. + w.Header().Del("Content-Length") log.Error(ctx, "Transcoding returned empty output, ffmpeg may have failed. "+ "Check that ffmpeg supports the requested codec. Enable Trace logging for ffmpeg stderr details", "id", id, "format", s.ContentType()) - } else { - log.Trace(ctx, "Success sending transcoded file", "id", id, "size", c) + return 0, nil } + switch { + case c < limit: + padding, err := io.CopyN(w, zeroReader{}, limit-c) + if err != nil { + log.Debug(ctx, "Error padding transcoded file to the estimated length", "id", id, err) + } + c += padding + case limit > 0: + // The body is complete. Send it now, then read the rest, so a transcode tied to this request + // can finish and complete its cache entry. That only holds while the client keeps the + // connection open: a hang-up cancels the request, and cutBytes is then a lower bound. + _ = http.NewResponseController(w).Flush() + if cut, _ := io.Copy(io.Discard, s); cut > 0 { + log.Warn(ctx, "Transcoded output is longer than the estimated length, the end of the file was cut", + "id", id, "estimatedLength", limit, "cutBytes", cut) + } + } + log.Trace(ctx, "Success sending transcoded file", "id", id, "size", c) return c, nil } +type zeroReader struct{} + +func (zeroReader) Read(p []byte) (int, error) { + clear(p) + return len(p), nil +} + // NewStream creates a non-seekable Stream from the given components. func NewStream(mf *model.MediaFile, format string, bitRate int, r io.ReadCloser) *Stream { return &Stream{ @@ -221,7 +268,7 @@ func GetTranscodingCache() TranscodingCache { } func NewTranscodingCache() TranscodingCache { - return cache.NewFileCache("Transcoding", conf.Server.TranscodingCacheSize, + return cache.NewFileCache("Transcoding", conf.Server().TranscodingCacheSize, consts.TranscodingCacheDir, consts.DefaultTranscodingCacheMaxItems, func(ctx context.Context, arg cache.Item) (io.Reader, error) { job := arg.(*streamJob) @@ -235,8 +282,8 @@ func NewTranscodingCache() TranscodingCache { if err != nil { log.Warn(ctx, "Refusing transcode: concurrent transcode limit reached", "id", job.mf.ID, "user", userName(ctx), - "maxConcurrent", conf.Server.Transcoding.MaxConcurrent, - "maxPerUser", conf.Server.Transcoding.MaxConcurrentPerUser) + "maxConcurrent", conf.Server().Transcoding.MaxConcurrent, + "maxPerUser", conf.Server().Transcoding.MaxConcurrentPerUser) return nil, err } @@ -253,7 +300,7 @@ func NewTranscodingCache() TranscodingCache { // governed by Transcoding.EnableCancellation so unchanged configs // keep their previous observable behavior. var transcodingCtx context.Context - if job.ms.limiter.Enabled() || conf.Server.Transcoding.EnableCancellation { + if job.ms.limiter.Enabled() || conf.Server().Transcoding.EnableCancellation { transcodingCtx = ctx } else { transcodingCtx = request.AddValues(context.Background(), ctx) diff --git a/core/stream/media_streamer_test.go b/core/stream/media_streamer_test.go index 5a4bcd480..46ff62021 100644 --- a/core/stream/media_streamer_test.go +++ b/core/stream/media_streamer_test.go @@ -8,13 +8,13 @@ import ( "net/http" "net/http/httptest" "os" + "strconv" "testing/iotest" "time" "github.com/go-chi/chi/v5/middleware" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/stream" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" @@ -31,10 +31,11 @@ var _ = Describe("MediaStreamer", func() { ctx := log.NewContext(context.TODO()) BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) cacheDir, _ := os.MkdirTemp("", "file_caches") - conf.Server.CacheFolder = conf.NewDir(cacheDir) - conf.Server.TranscodingCacheSize = "100MB" + conf.Update(func(c *conf.Options) { + c.CacheFolder = conf.NewDir(cacheDir) + c.TranscodingCacheSize = "100MB" + }) ds = &tests.MockDataStore{MockedTranscoding: &tests.MockTranscodingRepo{}} ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ {ID: "123", Path: "tests/fixtures/test.mp3", Suffix: "mp3", BitRate: 128, Duration: 257.0}, @@ -44,7 +45,7 @@ var _ = Describe("MediaStreamer", func() { streamer = stream.NewMediaStreamer(ds, ffmpeg, testCache) }) AfterEach(func() { - _ = os.RemoveAll(conf.Server.CacheFolder.String()) + _ = os.RemoveAll(conf.Server().CacheFolder.String()) }) Context("NewStream", func() { @@ -79,8 +80,10 @@ var _ = Describe("MediaStreamer", func() { blockingFFmpeg := tests.NewMockFFmpeg("") blockingFFmpeg.Reader = pr - conf.Server.Transcoding.MaxConcurrent = 1 - conf.Server.Transcoding.MaxConcurrentPerUser = 0 + conf.Update(func(c *conf.Options) { + c.Transcoding.MaxConcurrent = 1 + c.Transcoding.MaxConcurrentPerUser = 0 + }) tightCache := stream.NewTranscodingCache() Eventually(func() bool { return tightCache.Available(context.TODO()) }, 10*time.Second).Should(BeTrue()) tightStreamer := stream.NewMediaStreamer(ds, blockingFFmpeg, tightCache) @@ -96,8 +99,10 @@ var _ = Describe("MediaStreamer", func() { }) It("releases the slot once the stream is closed", func() { - conf.Server.Transcoding.MaxConcurrent = 1 - conf.Server.Transcoding.MaxConcurrentPerUser = 0 + conf.Update(func(c *conf.Options) { + c.Transcoding.MaxConcurrent = 1 + c.Transcoding.MaxConcurrentPerUser = 0 + }) tightCache := stream.NewTranscodingCache() Eventually(func() bool { return tightCache.Available(context.TODO()) }, 10*time.Second).Should(BeTrue()) tightStreamer := stream.NewMediaStreamer(ds, ffmpeg, tightCache) @@ -116,8 +121,10 @@ var _ = Describe("MediaStreamer", func() { }) It("does not consume a slot for raw streams", func() { - conf.Server.Transcoding.MaxConcurrent = 1 - conf.Server.Transcoding.MaxConcurrentPerUser = 0 + conf.Update(func(c *conf.Options) { + c.Transcoding.MaxConcurrent = 1 + c.Transcoding.MaxConcurrentPerUser = 0 + }) tightCache := stream.NewTranscodingCache() Eventually(func() bool { return tightCache.Available(context.TODO()) }, 10*time.Second).Should(BeTrue()) tightStreamer := stream.NewMediaStreamer(ds, ffmpeg, tightCache) @@ -183,6 +190,119 @@ var _ = Describe("MediaStreamer", func() { _, err = io.ReadAll(resp.Body) Expect(err).To(HaveOccurred()) }) + + Context("with estimateContentLength=true", func() { + // 10s at 128kbps, where a kbps is 1000 bits per second. + const estimate = 10 * 128 * 1000 / 8 + + BeforeEach(func() { + mf.Duration = 10 + }) + + newStream := func(src []byte) *stream.Stream { + return stream.NewStream(mf, "mp3", 128, io.NopCloser(bytes.NewReader(src))) + } + serve := func(s *stream.Stream) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodGet, "/?estimateContentLength=true", nil) + _, err := s.Serve(ctx, w, r) + Expect(err).ToNot(HaveOccurred()) + return w + } + declaredLength := func(w *httptest.ResponseRecorder) int { + declared, err := strconv.Atoi(w.Header().Get("Content-Length")) + Expect(err).ToNot(HaveOccurred(), "Content-Length must be declared") + return declared + } + + It("pads output shorter than the estimate with zeros up to the declared length", func() { + src := bytes.Repeat([]byte("a"), 1000) + w := serve(newStream(src)) + + declared, body := declaredLength(w), w.Body.Bytes() + Expect(body).To(HaveLen(declared)) + Expect(body[:len(src)]).To(Equal(src)) + Expect(body[len(src):]).To(Equal(make([]byte, declared-len(src)))) + }) + + It("truncates output longer than the estimate at the declared length", func() { + src := bytes.Repeat([]byte("a"), 2*estimate) + w := serve(newStream(src)) + + declared := declaredLength(w) + Expect(declared).To(BeNumerically("<", len(src))) + Expect(w.Body.Bytes()).To(Equal(src[:declared])) + }) + + It("reads the rest of output longer than the estimate, so a transcode tied to the request can finish", func() { + src := bytes.NewReader(bytes.Repeat([]byte("a"), 2*estimate)) + serve(stream.NewStream(mf, "mp3", 128, io.NopCloser(src))) + + Expect(src.Len()).To(BeZero()) + }) + + It("declares duration times bitrate, with no headroom", func() { + w := serve(newStream(bytes.Repeat([]byte("a"), 1000))) + + Expect(declaredLength(w)).To(Equal(estimate)) + }) + + It("estimates only the part of the track after the requested offset", func() { + full, err := streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 128}) + Expect(err).ToNot(HaveOccurred()) + DeferCleanup(full.Close) + half, err := streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 128, Offset: 5}) + Expect(err).ToNot(HaveOccurred()) + DeferCleanup(half.Close) + + Expect(half.EstimatedContentLength()).To(BeNumerically("~", full.EstimatedContentLength()/2, 1)) + }) + + It("estimates the whole track for a negative offset, as the transcode starts from the beginning", func() { + s, err := streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 128, Offset: -1000000000}) + Expect(err).ToNot(HaveOccurred()) + DeferCleanup(s.Close) + + Expect(s.EstimatedContentLength()).To(Equal(int64(estimate))) + }) + + It("does not declare a Content-Length when the track has no duration", func() { + mf.Duration = 0 + src := []byte("some audio") + w := serve(newStream(src)) + + Expect(w.Header().Values("Content-Length")).To(BeEmpty()) + Expect(w.Body.Bytes()).To(Equal(src)) + }) + + It("drops the declared length when the transcoder produces no output", func() { + w := serve(newStream(nil)) + + Expect(w.Header().Values("Content-Length")).To(BeEmpty()) + Expect(w.Body.Len()).To(BeZero()) + }) + + Context("with DevMatchEstimatedContentLength=false", func() { + BeforeEach(func() { + conf.Update(func(c *conf.Options) { c.DevMatchEstimatedContentLength = false }) + }) + + It("declares the estimate and sends shorter output as is, without padding", func() { + src := bytes.Repeat([]byte("a"), 1000) + w := serve(newStream(src)) + + Expect(declaredLength(w)).To(Equal(estimate)) + Expect(w.Body.Bytes()).To(Equal(src)) + }) + + It("does not cut output longer than the estimate", func() { + src := bytes.Repeat([]byte("a"), 2*estimate) + w := serve(newStream(src)) + + Expect(w.Body.Bytes()).To(Equal(src)) + }) + }) + }) }) }) diff --git a/core/stream/stream_suite_test.go b/core/stream/stream_suite_test.go index 36e9e7f43..db6c774de 100644 --- a/core/stream/stream_suite_test.go +++ b/core/stream/stream_suite_test.go @@ -3,6 +3,7 @@ package stream 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 TestStream(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Stream Suite") } + +var _ = configtest.RestoreAfterEachSpec() diff --git a/db/backup.go b/db/backup.go index 8c99f2a25..6bc849072 100644 --- a/db/backup.go +++ b/db/backup.go @@ -28,7 +28,7 @@ const backupSuffixLayout = "2006.01.02_15.04.05" func backupPath(t time.Time) string { return filepath.Join( - conf.Server.Backup.Path.MustPath(), + conf.Server().Backup.Path.MustPath(), fmt.Sprintf("%s_%s.db", backupPrefix, t.Format(backupSuffixLayout)), ) } @@ -177,7 +177,7 @@ func Restore(ctx context.Context, path string, integrityCheck bool) error { } func Prune(ctx context.Context) (int, error) { - backupDir, err := conf.Server.Backup.Path.Path() + backupDir, err := conf.Server().Backup.Path.Path() if err != nil { return 0, fmt.Errorf("backup directory not available: %w", err) } @@ -200,7 +200,7 @@ func Prune(ctx context.Context) (int, error) { } } - if len(backupTimes) <= conf.Server.Backup.Count { + if len(backupTimes) <= conf.Server().Backup.Count { return 0, nil } @@ -211,7 +211,7 @@ func Prune(ctx context.Context) (int, error) { pruneCount := 0 var errs []error - for _, timeToPrune := range backupTimes[conf.Server.Backup.Count:] { + for _, timeToPrune := range backupTimes[conf.Server().Backup.Count:] { log.Debug(ctx, "Pruning backup", "time", timeToPrune) path := backupPath(timeToPrune) err = os.Remove(path) diff --git a/db/backup_test.go b/db/backup_test.go index 6dacdad04..75b6de992 100644 --- a/db/backup_test.go +++ b/db/backup_test.go @@ -9,7 +9,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" . "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/utils/singleton" @@ -74,11 +73,10 @@ var _ = Describe("database backups", func() { } BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) tempFolder, err := os.MkdirTemp("", "navidrome_backup") Expect(err).ToNot(HaveOccurred()) - conf.Server.Backup.Path = conf.NewDir(tempFolder) + conf.Update(func(c *conf.Options) { c.Backup.Path = conf.NewDir(tempFolder) }) DeferCleanup(func() { _ = os.RemoveAll(tempFolder) @@ -102,12 +100,12 @@ var _ = Describe("database backups", func() { }) DescribeTable("prune", func(count, expected int) { - conf.Server.Backup.Count = count + conf.Update(func(c *conf.Options) { c.Backup.Count = count }) pruneCount, err := Prune(ctx) Expect(err).ToNot(HaveOccurred()) for idx, time := range timesDecreasingChronologically { _, err := os.Stat(BackupPath(time)) - shouldExist := idx < conf.Server.Backup.Count + shouldExist := idx < conf.Server().Backup.Count if shouldExist { Expect(err).ToNot(HaveOccurred()) } else { @@ -129,7 +127,7 @@ var _ = Describe("database backups", func() { _ = file.Close() } - conf.Server.Backup.Count = len(timesDecreasingChronologically) + conf.Update(func(c *conf.Options) { c.Backup.Count = len(timesDecreasingChronologically) }) pruneCount, err := Prune(ctx) Expect(err).ToNot(HaveOccurred()) Expect(pruneCount).To(BeZero()) @@ -141,16 +139,16 @@ var _ = Describe("database backups", func() { BeforeAll(func() { ctx = context.Background() - DeferCleanup(configtest.SetupConfig()) + DeferCleanup(conf.SnapshotConfig()) - conf.Server.DbPath = "file::memory:?cache=shared&_foreign_keys=on" + conf.Update(func(c *conf.Options) { c.DbPath = "file::memory:?cache=shared&_foreign_keys=on" }) DeferCleanup(Init(ctx)) }) BeforeEach(func() { tempFolder, err := os.MkdirTemp("", "navidrome_backup") Expect(err).ToNot(HaveOccurred()) - conf.Server.Backup.Path = conf.NewDir(tempFolder) + conf.Update(func(c *conf.Options) { c.Backup.Path = conf.NewDir(tempFolder) }) DeferCleanup(func() { _ = os.RemoveAll(tempFolder) @@ -187,12 +185,12 @@ var _ = Describe("database backups", func() { BeforeAll(func() { ctx = context.Background() - DeferCleanup(configtest.SetupConfig()) + DeferCleanup(conf.SnapshotConfig()) var err error tempFolder, err = os.MkdirTemp("", "navidrome_restore") Expect(err).ToNot(HaveOccurred()) - conf.Server.Backup.Path = conf.NewDir(tempFolder) + conf.Update(func(c *conf.Options) { c.Backup.Path = conf.NewDir(tempFolder) }) DeferCleanup(func() { Close(ctx) _ = os.RemoveAll(tempFolder) @@ -200,7 +198,9 @@ var _ = Describe("database backups", func() { // Mimic the production DSN (consts.DefaultDbPath): a file database in WAL mode. dbFilePath = filepath.Join(tempFolder, "navidrome.db") - conf.Server.DbPath = dbFilePath + "?_busy_timeout=15000&_journal_mode=WAL&_foreign_keys=on&synchronous=normal" + conf.Update(func(c *conf.Options) { + c.DbPath = dbFilePath + "?_busy_timeout=15000&_journal_mode=WAL&_foreign_keys=on&synchronous=normal" + }) // The previous container's cleanup closed the shared *sql.DB without // dropping the singleton; force a fresh connection for this container. singleton.DeleteInstance[*sql.DB]() diff --git a/db/db.go b/db/db.go index 66e48cede..5442b125c 100644 --- a/db/db.go +++ b/db/db.go @@ -20,7 +20,7 @@ import ( ) // NaturalCollation sorts embedded numbers by value. It is registered on every -// connection, but only referenced when conf.Server.EnableNaturalSorting is on. +// connection, but only referenced when conf.Server().EnableNaturalSorting is on. const NaturalCollation = "NATSORT" var ( @@ -50,12 +50,12 @@ func Db() *sql.DB { }, }) }) - Path = conf.Server.DbPath + Path = conf.Server().DbPath if Path == ":memory:" { Path = "file::memory:?cache=shared&_foreign_keys=on" - conf.Server.DbPath = Path + conf.Update(func(c *conf.Options) { c.DbPath = Path }) } else { - conf.Server.DataFolder.MustPath() + conf.Server().DataFolder.MustPath() } log.Debug("Opening DataBase", "dbPath", Path, "driver", Driver) db, err := sql.Open(Driver, Path) diff --git a/db/db_test.go b/db/db_test.go index e3a52e1fb..7abf1b839 100644 --- a/db/db_test.go +++ b/db/db_test.go @@ -9,6 +9,7 @@ import ( "github.com/mattn/go-sqlite3" + "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/tests" @@ -23,6 +24,8 @@ func TestDB(t *testing.T) { RunSpecs(t, "DB Suite") } +var _ = configtest.RestoreAfterEachSpec() + var _ = DescribeTable("IsBusy", func(err error, expected bool) { Expect(db.IsBusy(err)).To(Equal(expected)) diff --git a/db/migrations/20240511220020_add_library_table.go b/db/migrations/20240511220020_add_library_table.go index d7b4aa5c2..7b19a3a58 100644 --- a/db/migrations/20240511220020_add_library_table.go +++ b/db/migrations/20240511220020_add_library_table.go @@ -30,7 +30,7 @@ func upAddLibraryTable(ctx context.Context, tx *sql.Tx) error { _, err = tx.ExecContext(ctx, ` insert into library(id, name, path) values(1, 'Music Library', ?); delete from property where id like 'LastScan-%'; -`, conf.Server.MusicFolder) +`, conf.Server().MusicFolder) if err != nil { return err } diff --git a/db/migrations/20260720015443_uniform_canonical_ids.go b/db/migrations/20260720015443_uniform_canonical_ids.go index 346f22050..b7faa5238 100644 --- a/db/migrations/20260720015443_uniform_canonical_ids.go +++ b/db/migrations/20260720015443_uniform_canonical_ids.go @@ -107,7 +107,7 @@ func upUniformCanonicalIds(ctx context.Context, tx *sql.Tx) error { } // Legacy PID specs embed old-shaped album/track ids into composite pids; a full rescan // rewrites every pid with the new encoding so path-based move matching stays consistent. - if strings.Contains(conf.Server.PID.Track, "legacy") || strings.Contains(conf.Server.PID.Album, "legacy") { + if strings.Contains(conf.Server().PID.Track, "legacy") || strings.Contains(conf.Server().PID.Album, "legacy") { if err := forceFullRescan(ctx, tx); err != nil { return err } diff --git a/db/migrations/migrations_suite_test.go b/db/migrations/migrations_suite_test.go index bb08ad8aa..425ffe4a8 100644 --- a/db/migrations/migrations_suite_test.go +++ b/db/migrations/migrations_suite_test.go @@ -3,6 +3,7 @@ package migrations import ( "testing" + "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -14,3 +15,5 @@ func TestMigrations(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Migrations Suite") } + +var _ = configtest.RestoreAfterEachSpec() diff --git a/db/migrations/uniform_canonical_ids_test.go b/db/migrations/uniform_canonical_ids_test.go index ced75cb7e..a00f9adfe 100644 --- a/db/migrations/uniform_canonical_ids_test.go +++ b/db/migrations/uniform_canonical_ids_test.go @@ -198,9 +198,7 @@ var _ = Describe("upUniformCanonicalIds", func() { Context("with a legacy PID configuration", func() { BeforeEach(func() { - prev := conf.Server.PID.Album - conf.Server.PID.Album = "album_legacy" - DeferCleanup(func() { conf.Server.PID.Album = prev }) + conf.Update(func(c *conf.Options) { c.PID.Album = "album_legacy" }) }) It("forces a full rescan so composite pids are rewritten", func() { diff --git a/model/album.go b/model/album.go index a43195419..2ce023e02 100644 --- a/model/album.go +++ b/model/album.go @@ -77,7 +77,7 @@ func (a Album) CoverArtID() ArtworkID { } func (a Album) FullName() string { - if v := a.Tags.First(TagAlbumVersion); conf.Server.Subsonic.AppendAlbumVersion && v != "" { + if v := a.Tags.First(TagAlbumVersion); conf.Server().Subsonic.AppendAlbumVersion && v != "" { return appendSuffix(a.Name, v) } return a.Name diff --git a/model/album_test.go b/model/album_test.go index ad2ca1cb6..547253127 100644 --- a/model/album_test.go +++ b/model/album_test.go @@ -4,19 +4,15 @@ import ( "encoding/json" "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" ) var _ = Describe("Album", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) DescribeTable("FullName", func(enabled bool, tags Tags, expected string) { - conf.Server.Subsonic.AppendAlbumVersion = enabled + conf.Update(func(c *conf.Options) { c.Subsonic.AppendAlbumVersion = enabled }) a := Album{Name: "Album", Tags: tags} Expect(a.FullName()).To(Equal(expected)) }, diff --git a/model/artist_test.go b/model/artist_test.go index db897d3d5..e3d5472ea 100644 --- a/model/artist_test.go +++ b/model/artist_test.go @@ -4,7 +4,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" @@ -13,8 +12,7 @@ import ( var _ = Describe("Artist", func() { Describe("UploadedImagePath", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DataFolder = conf.NewDir("/data") + conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir("/data") }) }) It("returns empty string when no image uploaded", func() { diff --git a/model/criteria/criteria.go b/model/criteria/criteria.go index e6db3b481..72abe5b1a 100644 --- a/model/criteria/criteria.go +++ b/model/criteria/criteria.go @@ -23,7 +23,7 @@ type Criteria struct { Limit int LimitPercent int Offset int - RefreshDelay time.Duration // 0 = use conf.Server.SmartPlaylistRefreshDelay + RefreshDelay time.Duration // 0 = use conf.Server().SmartPlaylistRefreshDelay } // EffectiveLimit resolves the effective limit for a query. If a fixed Limit is diff --git a/model/criteria/criteria_test.go b/model/criteria/criteria_test.go index de5124568..5a8ebaa5c 100644 --- a/model/criteria/criteria_test.go +++ b/model/criteria/criteria_test.go @@ -423,4 +423,16 @@ var _ = Describe("Criteria", func() { gomega.Expect(ids).To(gomega.Equal([]string{sharedID})) }) }) + + DescribeTable("empty nested groups", + func(input, expected string) { + var c Criteria + gomega.Expect(json.Unmarshal([]byte(input), &c)).To(gomega.Succeed()) + out, err := json.Marshal(c) + gomega.Expect(err).ToNot(gomega.HaveOccurred()) + gomega.Expect(string(out)).To(gomega.Equal(expected)) + }, + Entry("keeps a nested empty group", `{"all":[{"all":[]}]}`, `{"all":[{"all":[]}]}`), + Entry("keeps a nested empty any group", `{"all":[{"any":[]}]}`, `{"all":[{"any":[]}]}`), + ) }) diff --git a/model/criteria/json.go b/model/criteria/json.go index d0f453524..87f768298 100644 --- a/model/criteria/json.go +++ b/model/criteria/json.go @@ -174,14 +174,8 @@ func marshalExpression(name string, value map[string]any) ([]byte, error) { } func marshalConjunction(name string, conj []Expression) ([]byte, error) { - aux := struct { - All []Expression `json:"all,omitempty"` - Any []Expression `json:"any,omitempty"` - }{} - if name == "any" { - aux.Any = conj - } else { - aux.All = conj + if conj == nil { + conj = []Expression{} } - return json.Marshal(aux) + return json.Marshal(map[string][]Expression{name: conj}) } diff --git a/model/datastore.go b/model/datastore.go index 1175d212d..eb16e8836 100644 --- a/model/datastore.go +++ b/model/datastore.go @@ -13,6 +13,9 @@ type QueryOptions struct { Offset int Filters squirrel.Sqlizer Seed string // for random sorting + // SortOrders is one "asc"/"desc" per Sort key, kept on every column its mapping expands into. + // Empty means Order applies to every key; a key past the end reuses the first entry. + SortOrders []string } type DataStore interface { diff --git a/model/image.go b/model/image.go index 30307fcea..aa588a2e3 100644 --- a/model/image.go +++ b/model/image.go @@ -13,5 +13,5 @@ func UploadedImagePath(entityType, filename string) string { if filename == "" { return "" } - return filepath.Join(conf.Server.DataFolder.String(), consts.ArtworkFolder, entityType, filename) + return filepath.Join(conf.Server().DataFolder.String(), consts.ArtworkFolder, entityType, filename) } diff --git a/model/library.go b/model/library.go index e80d22c89..3e5dd76fd 100644 --- a/model/library.go +++ b/model/library.go @@ -46,8 +46,8 @@ type PIDConfig struct { // the global config. func (l Library) EffectivePID() PIDConfig { return PIDConfig{ - Track: cmp.Or(l.PIDTrack, conf.Server.PID.Track), - Album: cmp.Or(l.PIDAlbum, conf.Server.PID.Album), + Track: cmp.Or(l.PIDTrack, conf.Server().PID.Track), + Album: cmp.Or(l.PIDAlbum, conf.Server().PID.Album), } } diff --git a/model/library_test.go b/model/library_test.go index 4e799e13f..04a9b7bfe 100644 --- a/model/library_test.go +++ b/model/library_test.go @@ -5,7 +5,6 @@ import ( "time" "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" @@ -13,9 +12,10 @@ import ( var _ = Describe("Library PID config", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.PID.Album = "global_album" - conf.Server.PID.Track = "global_track" + conf.Update(func(c *conf.Options) { + c.PID.Album = "global_album" + c.PID.Track = "global_track" + }) }) Describe("EffectivePID", func() { diff --git a/model/mediafile.go b/model/mediafile.go index 0c56b4825..75692d35f 100644 --- a/model/mediafile.go +++ b/model/mediafile.go @@ -107,14 +107,14 @@ type MediaFile struct { } func (mf MediaFile) FullTitle() string { - if s := mf.Tags.First(TagSubtitle); conf.Server.Subsonic.AppendSubtitle && s != "" { + if s := mf.Tags.First(TagSubtitle); conf.Server().Subsonic.AppendSubtitle && s != "" { return appendSuffix(mf.Title, s) } return mf.Title } func (mf MediaFile) FullAlbumName() string { - if v := mf.Tags.First(TagAlbumVersion); conf.Server.Subsonic.AppendAlbumVersion && v != "" { + if v := mf.Tags.First(TagAlbumVersion); conf.Server().Subsonic.AppendAlbumVersion && v != "" { return appendSuffix(mf.Album, v) } return mf.Album @@ -136,7 +136,7 @@ func (mf MediaFile) ContentType() string { func (mf MediaFile) CoverArtID() ArtworkID { // If it has a cover art, return it (if feature is disabled, skip) - if mf.HasCoverArt && conf.Server.EnableMediaFileCoverArt { + if mf.HasCoverArt && conf.Server().EnableMediaFileCoverArt { return artworkIDFromMediaFile(mf) } // Otherwise fallback to disc (if available) or album cover diff --git a/model/mediafile_test.go b/model/mediafile_test.go index 9ca3489bb..97af63d50 100644 --- a/model/mediafile_test.go +++ b/model/mediafile_test.go @@ -4,7 +4,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" @@ -520,12 +519,11 @@ var _ = Describe("MediaFiles", func() { var _ = Describe("MediaFile", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableMediaFileCoverArt = true + conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true }) }) DescribeTable("FullTitle", func(enabled bool, tags Tags, expected string) { - conf.Server.Subsonic.AppendSubtitle = enabled + conf.Update(func(c *conf.Options) { c.Subsonic.AppendSubtitle = enabled }) mf := MediaFile{Title: "Song", Tags: tags} Expect(mf.FullTitle()).To(Equal(expected)) }, @@ -543,7 +541,7 @@ var _ = Describe("MediaFile", func() { ) DescribeTable("FullAlbumName", func(enabled bool, tags Tags, expected string) { - conf.Server.Subsonic.AppendAlbumVersion = enabled + conf.Update(func(c *conf.Options) { c.Subsonic.AppendAlbumVersion = enabled }) mf := MediaFile{Album: "Album", Tags: tags} Expect(mf.FullAlbumName()).To(Equal(expected)) }, @@ -574,14 +572,14 @@ var _ = Describe("MediaFile", func() { Expect(id.ID).To(Equal(mf.AlbumID)) }) It("returns disc art id if EnableMediaFileCoverArt is disabled and DiscNumber > 0", func() { - conf.Server.EnableMediaFileCoverArt = false + conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false }) mf := MediaFile{ID: "111", AlbumID: "1", HasCoverArt: true, DiscNumber: 3} id := mf.CoverArtID() Expect(id.Kind).To(Equal(KindDiscArtwork)) Expect(id.ID).To(Equal("1:3")) }) It("returns its album id if EnableMediaFileCoverArt is disabled and DiscNumber is 0", func() { - conf.Server.EnableMediaFileCoverArt = false + conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false }) mf := MediaFile{ID: "111", AlbumID: "1", HasCoverArt: true} id := mf.CoverArtID() Expect(id.Kind).To(Equal(KindAlbumArtwork)) diff --git a/model/metadata/legacy_ids.go b/model/metadata/legacy_ids.go index 7156c4f50..97c741d3d 100644 --- a/model/metadata/legacy_ids.go +++ b/model/metadata/legacy_ids.go @@ -27,7 +27,7 @@ func legacyTrackID(mf model.MediaFile, prependLibId bool) string { func legacyAlbumID(mf model.MediaFile, md Metadata, prependLibId bool) string { _, _, releaseDate := md.mapDates() albumPath := strings.ToLower(fmt.Sprintf("%s\\%s", legacyMapAlbumArtistName(md), legacyMapAlbumName(md))) - if !conf.Server.Scanner.GroupAlbumReleases { + if !conf.Server().Scanner.GroupAlbumReleases { if len(releaseDate) != 0 { albumPath = fmt.Sprintf("%s\\%s", albumPath, releaseDate) } diff --git a/model/metadata/map_participants.go b/model/metadata/map_participants.go index 35f112a92..a813a6fac 100644 --- a/model/metadata/map_participants.go +++ b/model/metadata/map_participants.go @@ -217,8 +217,8 @@ func (md Metadata) getArtistValues(single, multi model.TagName) []string { func (md Metadata) mapDisplayName(singularTagName, pluralTagName model.TagName) string { return cmp.Or( - strings.Join(md.tags[singularTagName], conf.Server.Scanner.ArtistJoiner), - strings.Join(md.tags[pluralTagName], conf.Server.Scanner.ArtistJoiner), + strings.Join(md.tags[singularTagName], conf.Server().Scanner.ArtistJoiner), + strings.Join(md.tags[pluralTagName], conf.Server().Scanner.ArtistJoiner), ) } diff --git a/model/metadata/map_participants_test.go b/model/metadata/map_participants_test.go index db652fb8b..769e985f6 100644 --- a/model/metadata/map_participants_test.go +++ b/model/metadata/map_participants_test.go @@ -5,7 +5,6 @@ import ( "github.com/google/uuid" "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/model/metadata" @@ -837,13 +836,10 @@ var _ = Describe("Participants", func() { }) Describe("Artist split exceptions", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) It("does not split a whitelisted artist name on the default separators", func() { // " feat. " is a default artists separator (mappings.yaml) - conf.Server.Scanner.ArtistSplitExceptions = []string{"Someone feat. Else"} + conf.Update(func(c *conf.Options) { c.Scanner.ArtistSplitExceptions = []string{"Someone feat. Else"} }) mf = toMediaFile(model.RawTags{ "ARTIST": {"Artist Name feat. Someone feat. Else"}, }) @@ -856,7 +852,7 @@ var _ = Describe("Participants", func() { It("does not split a whitelisted name in role tags", func() { // "/" is a default roles separator (mappings.yaml) - conf.Server.Scanner.ArtistSplitExceptions = []string{"AC/DC"} + conf.Update(func(c *conf.Options) { c.Scanner.ArtistSplitExceptions = []string{"AC/DC"} }) mf = toMediaFile(model.RawTags{ "COMPOSER": {"AC/DC/John Doe"}, }) @@ -868,7 +864,7 @@ var _ = Describe("Participants", func() { }) It("splits normally when the exception does not match", func() { - conf.Server.Scanner.ArtistSplitExceptions = []string{"Iron and Wine"} + conf.Update(func(c *conf.Options) { c.Scanner.ArtistSplitExceptions = []string{"Iron and Wine"} }) mf = toMediaFile(model.RawTags{ "ARTIST": {"Artist Name feat. Someone Else"}, }) @@ -880,7 +876,7 @@ var _ = Describe("Participants", func() { }) It("does not split a whitelisted name in performer tags", func() { - conf.Server.Scanner.ArtistSplitExceptions = []string{"AC/DC"} + conf.Update(func(c *conf.Options) { c.Scanner.ArtistSplitExceptions = []string{"AC/DC"} }) mf = toMediaFile(model.RawTags{ "PERFORMER:GUITAR": {"AC/DC/Brian Johnson"}, }) diff --git a/model/metadata/metadata_suite_test.go b/model/metadata/metadata_suite_test.go index fc299c7e9..0473e17d7 100644 --- a/model/metadata/metadata_suite_test.go +++ b/model/metadata/metadata_suite_test.go @@ -7,6 +7,7 @@ import ( "github.com/djherbis/times" _ "github.com/mattn/go-sqlite3" + "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" @@ -20,6 +21,8 @@ func TestMetadata(t *testing.T) { RunSpecs(t, "Metadata Suite") } +var _ = configtest.RestoreAfterEachSpec() + type testFileInfo struct { fs.FileInfo } diff --git a/model/model_suite_test.go b/model/model_suite_test.go index 39184edc1..53d33d36c 100644 --- a/model/model_suite_test.go +++ b/model/model_suite_test.go @@ -4,6 +4,7 @@ import ( "testing" _ "github.com/mattn/go-sqlite3" + "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" @@ -16,3 +17,5 @@ func TestModel(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Model Suite") } + +var _ = configtest.RestoreAfterEachSpec() diff --git a/model/playlist.go b/model/playlist.go index d2ed97682..497659ba2 100644 --- a/model/playlist.go +++ b/model/playlist.go @@ -59,7 +59,7 @@ func (pls Playlist) RefreshDelay() time.Duration { if pls.IsSmartPlaylist() && pls.Rules.RefreshDelay > 0 { return pls.Rules.RefreshDelay } - return conf.Server.SmartPlaylistRefreshDelay + return conf.Server().SmartPlaylistRefreshDelay } func (pls Playlist) MediaFiles() MediaFiles { diff --git a/model/playlist_test.go b/model/playlist_test.go index 7ffb69b63..3ae57ff10 100644 --- a/model/playlist_test.go +++ b/model/playlist_test.go @@ -5,7 +5,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/criteria" "github.com/navidrome/navidrome/tests" @@ -52,8 +51,7 @@ var _ = Describe("Playlist", func() { Describe("RefreshDelay", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.SmartPlaylistRefreshDelay = 5 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = 5 * time.Second }) }) It("returns the global config value when rules have no refreshDelay", func() { diff --git a/model/radio_test.go b/model/radio_test.go index 6ae74c3f4..cf01f6ed5 100644 --- a/model/radio_test.go +++ b/model/radio_test.go @@ -5,7 +5,6 @@ import ( "time" "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" @@ -24,8 +23,7 @@ var _ = Describe("Radio", func() { Describe("UploadedImagePath", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DataFolder = conf.NewDir("/data") + conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir("/data") }) }) It("returns empty string when no image uploaded", func() { diff --git a/model/tag_mappings.go b/model/tag_mappings.go index 5a8168754..c6a4a03bd 100644 --- a/model/tag_mappings.go +++ b/model/tag_mappings.go @@ -143,7 +143,7 @@ var artistSplitExceptions atomic.Pointer[artistSplitExceptionsCache] // configured list changes. Lock-free on the cache-hit path, as this is called // per tag mapping per scanned file, across concurrent scanner goroutines. func artistSplitExceptionsRx() *regexp.Regexp { - names := conf.Server.Scanner.ArtistSplitExceptions + names := conf.Server().Scanner.ArtistSplitExceptions if c := artistSplitExceptions.Load(); c != nil && slices.Equal(c.names, names) { return c.rx } @@ -338,16 +338,16 @@ func loadTagMappings() { } // Use Scanner.GenreSeparators if specified and Tags.genre is not defined - if conf.Server.Scanner.GenreSeparators != "" && len(conf.Server.Tags["genre"].Aliases) == 0 { + if conf.Server().Scanner.GenreSeparators != "" && len(conf.Server().Tags["genre"].Aliases) == 0 { genreConf := _mappings.Main[TagName("genre")] - genreConf.Split = strings.Split(conf.Server.Scanner.GenreSeparators, "") + genreConf.Split = strings.Split(conf.Server().Scanner.GenreSeparators, "") genreConf.SplitRx = compileSplitRegex("genre", genreConf.Split) _mappings.Main[TagName("genre")] = genreConf log.Debug("Loading deprecated list of genre separators", "separators", genreConf.Split) } // Overwrite the default mappings with the ones from the config - for tag, cfg := range conf.Server.Tags { + for tag, cfg := range conf.Server().Tags { if cfg.Ignore { delete(_mappings.Main, TagName(tag)) delete(_mappings.Additional, TagName(tag)) diff --git a/model/tag_mappings_test.go b/model/tag_mappings_test.go index 91e54e5d4..8a3cf8b78 100644 --- a/model/tag_mappings_test.go +++ b/model/tag_mappings_test.go @@ -2,7 +2,6 @@ package model import ( "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -145,28 +144,25 @@ var _ = Describe("TagConf", func() { }) Describe("artistSplitExceptionsRx", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) It("returns nil when no exceptions are configured", func() { - conf.Server.Scanner.ArtistSplitExceptions = nil + conf.Update(func(c *conf.Options) { c.Scanner.ArtistSplitExceptions = nil }) Expect(artistSplitExceptionsRx()).To(BeNil()) }) It("compiles the configured exceptions", func() { - conf.Server.Scanner.ArtistSplitExceptions = []string{"Iron and Wine"} + conf.Update(func(c *conf.Options) { c.Scanner.ArtistSplitExceptions = []string{"Iron and Wine"} }) rx := artistSplitExceptionsRx() Expect(rx).ToNot(BeNil()) Expect(rx.MatchString("iron and wine")).To(BeTrue()) }) It("caches the compiled regex until the configuration changes", func() { - conf.Server.Scanner.ArtistSplitExceptions = []string{"Iron and Wine"} + conf.Update(func(c *conf.Options) { c.Scanner.ArtistSplitExceptions = []string{"Iron and Wine"} }) first := artistSplitExceptionsRx() Expect(artistSplitExceptionsRx()).To(BeIdenticalTo(first)) - conf.Server.Scanner.ArtistSplitExceptions = []string{"AC/DC"} + conf.Update(func(c *conf.Options) { c.Scanner.ArtistSplitExceptions = []string{"AC/DC"} }) second := artistSplitExceptionsRx() Expect(second).ToNot(BeIdenticalTo(first)) Expect(second.MatchString("AC/DC")).To(BeTrue()) @@ -175,8 +171,7 @@ var _ = Describe("TagConf", func() { Describe("WithParticipantExceptions", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Scanner.ArtistSplitExceptions = []string{"Iron and Wine"} + conf.Update(func(c *conf.Options) { c.Scanner.ArtistSplitExceptions = []string{"Iron and Wine"} }) }) It("attaches the exceptions regex to participant tags", func() { diff --git a/persistence/album_repository.go b/persistence/album_repository.go index 6a940a320..6e12c9ecd 100644 --- a/persistence/album_repository.go +++ b/persistence/album_repository.go @@ -150,7 +150,7 @@ var albumFilters = sync.OnceValue(func() map[string]filterFunc { }) func recentlyAddedSort() string { - if conf.Server.RecentlyAddedByModTime { + if conf.Server().RecentlyAddedByModTime { return "album.updated_at, album.id" } return "album.created_at, album.id" diff --git a/persistence/album_repository_test.go b/persistence/album_repository_test.go index 0235805c0..087fb0802 100644 --- a/persistence/album_repository_test.go +++ b/persistence/album_repository_test.go @@ -11,7 +11,6 @@ import ( "github.com/Masterminds/squirrel" "github.com/deluan/rest" "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/model/id" @@ -44,7 +43,6 @@ var _ = Describe("AlbumRepository", func() { var ids []string BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) ids = nil for _, n := range []string{"foo 1", "foo 10", "foo 2", "foo 20", "foo 3"} { aid := "nat-" + n @@ -60,8 +58,10 @@ var _ = Describe("AlbumRepository", func() { DescribeTable("sorts albums by name", func(naturalSorting, preferSortTags bool, expected []string) { - conf.Server.EnableNaturalSorting = naturalSorting - conf.Server.PreferSortTags = preferSortTags + conf.Update(func(c *conf.Options) { + c.EnableNaturalSorting = naturalSorting + c.PreferSortTags = preferSortTags + }) albumRepo = NewAlbumRepository(GetDBXBuilder()).(*albumRepository) albums, err := albumRepo.GetAll(ctx, model.QueryOptions{ Sort: "name", Filters: squirrel.Eq{"album.id": ids}, @@ -497,7 +497,7 @@ var _ = Describe("AlbumRepository", func() { // Implementation is in withAnnotation() method DescribeTable("normalizes play count when AlbumPlayCountMode is absolute", func(songCount, playCount, expected int) { - conf.Server.AlbumPlayCountMode = consts.AlbumPlayCountModeAbsolute + conf.Update(func(c *conf.Options) { c.AlbumPlayCountMode = consts.AlbumPlayCountModeAbsolute }) newID := id.NewRandom() Expect(albumRepo.Put(ctx, &model.Album{LibraryID: 1, ID: newID, Name: "name", SongCount: songCount})).To(Succeed()) @@ -520,7 +520,7 @@ var _ = Describe("AlbumRepository", func() { DescribeTable("normalizes play count when AlbumPlayCountMode is normalized", func(songCount, playCount, expected int) { - conf.Server.AlbumPlayCountMode = consts.AlbumPlayCountModeNormalized + conf.Update(func(c *conf.Options) { c.AlbumPlayCountMode = consts.AlbumPlayCountModeNormalized }) newID := id.NewRandom() Expect(albumRepo.Put(ctx, &model.Album{LibraryID: 1, ID: newID, Name: "name", SongCount: songCount})).To(Succeed()) diff --git a/persistence/artist_repository.go b/persistence/artist_repository.go index da1ef7f0d..07dcdfbc0 100644 --- a/persistence/artist_repository.go +++ b/persistence/artist_repository.go @@ -133,7 +133,7 @@ func (dba dbArtists) toModels() model.Artists { func NewArtistRepository(db dbx.Builder) model.ArtistRepository { r := &artistRepository{} r.db = db - r.indexGroups = utils.ParseIndexGroups(conf.Server.IndexGroups) + r.indexGroups = utils.ParseIndexGroups(conf.Server().IndexGroups) r.tableName = "artist" // To be used by the idFilter below r.registerModel(&model.Artist{}, map[string]filterFunc{ "id": idFilter(r.tableName), @@ -309,7 +309,7 @@ func (r *artistRepository) GetCursor(ctx context.Context, options ...model.Query func (r *artistRepository) getIndexKey(a model.Artist) string { source := a.OrderArtistName - if conf.Server.PreferSortTags { + if conf.Server().PreferSortTags { source = cmp.Or(a.SortArtistName, a.OrderArtistName) } name := strings.ToLower(source) diff --git a/persistence/artist_repository_test.go b/persistence/artist_repository_test.go index 25ea4ce06..6afc08736 100644 --- a/persistence/artist_repository_test.go +++ b/persistence/artist_repository_test.go @@ -11,7 +11,6 @@ import ( "github.com/Masterminds/squirrel" "github.com/deluan/rest" "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/model/request" @@ -59,12 +58,11 @@ var _ = Describe("ArtistRepository", func() { Context("Core Functionality", func() { Describe("GetIndexKey", func() { // Note: OrderArtistName should never be empty, so we don't need to test for that - r := artistRepository{indexGroups: utils.ParseIndexGroups(conf.Server.IndexGroups)} + r := artistRepository{indexGroups: utils.ParseIndexGroups(conf.Server().IndexGroups)} DescribeTable("returns correct index key based on PreferSortTags setting", func(preferSortTags bool, sortArtistName, orderArtistName, expectedKey string) { - DeferCleanup(configtest.SetupConfig()) - conf.Server.PreferSortTags = preferSortTags + conf.Update(func(c *conf.Options) { c.PreferSortTags = preferSortTags }) a := model.Artist{SortArtistName: sortArtistName, OrderArtistName: orderArtistName, Name: "Test"} idx := GetIndexKey(&r, a) Expect(idx).To(Equal(expectedKey)) @@ -453,7 +451,7 @@ var _ = Describe("ArtistRepository", func() { Describe("GetIndex", func() { When("PreferSortTags is true", func() { BeforeEach(func() { - conf.Server.PreferSortTags = true + conf.Update(func(c *conf.Options) { c.PreferSortTags = true }) }) It("returns the index when PreferSortTags is true and SortArtistName is not empty", func() { // Set SortArtistName to "Foo" for Beatles @@ -505,7 +503,7 @@ var _ = Describe("ArtistRepository", func() { When("PreferSortTags is false", func() { BeforeEach(func() { - conf.Server.PreferSortTags = false + conf.Update(func(c *conf.Options) { c.PreferSortTags = false }) }) It("returns the index when SortArtistName is NOT empty", func() { // Set SortArtistName to "Foo" for Beatles @@ -833,9 +831,8 @@ var _ = Describe("ArtistRepository", func() { DescribeTable("narrows artist search to the requested library", func(backend string, artist model.Artist, query string) { - DeferCleanup(configtest.SetupConfig()) if backend != "" { - conf.Server.Search.Backend = backend + conf.Update(func(c *conf.Options) { c.Search.Backend = backend }) } Expect(createArtistWithLibrary(ctx, repo, &artist, lib2.ID)).To(Succeed()) DeferCleanup(func() { @@ -889,8 +886,7 @@ var _ = Describe("ArtistRepository", func() { DescribeTable("reports only the requested libraries' songs and albums", func(backend, query string) { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = backend + conf.Update(func(c *conf.Options) { c.Search.Backend = backend }) counts := func(libIDs ...int) []int64 { opts := model.QueryOptions{Max: 100} @@ -914,8 +910,7 @@ var _ = Describe("ArtistRepository", func() { ) It("ranks LIKE results by the requested library's song count", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = "legacy" + conf.Update(func(c *conf.Options) { c.Search.Backend = "legacy" }) seedArtist("scoped-counts-artist-b", "Scoped Counts Artist B", "", map[int]string{ 1: `{"total":{"m":10,"a":2,"s":1000}}`, }) @@ -1308,9 +1303,8 @@ var _ = Describe("ArtistRepository", func() { var tmpDir string BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) tmpDir = GinkgoT().TempDir() - conf.Server.DataFolder = conf.NewDir(tmpDir) + conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) }) ctx = request.WithUser(ctx, adminUser) repo = NewArtistRepository(GetDBXBuilder()).(*artistRepository) diff --git a/persistence/artwork_hydration.go b/persistence/artwork_hydration.go index 76646ec74..b1640e2b7 100644 --- a/persistence/artwork_hydration.go +++ b/persistence/artwork_hydration.go @@ -41,7 +41,10 @@ func streamByIDs[S ~[]T, T any](ids []string, fetch func(chunk []string) (S, err func chunkOptions(options []model.QueryOptions, idField string) func([]string) model.QueryOptions { var base model.QueryOptions if len(options) > 0 { - base = model.QueryOptions{Sort: options[0].Sort, Order: options[0].Order, Filters: options[0].Filters} + base = model.QueryOptions{ + Sort: options[0].Sort, Order: options[0].Order, SortOrders: options[0].SortOrders, + Filters: options[0].Filters, + } } return func(chunk []string) model.QueryOptions { opts := base @@ -99,7 +102,7 @@ func hydrateMediaFileArtwork(ctx context.Context, db dbx.Builder, mfs model.Medi var eligibleIDs []string for i := range mfs { albumIDs[i] = mfs[i].AlbumID - if mfs[i].HasCoverArt && conf.Server.EnableMediaFileCoverArt { + if mfs[i].HasCoverArt && conf.Server().EnableMediaFileCoverArt { eligibleIDs = append(eligibleIDs, mfs[i].ID) } } @@ -108,7 +111,7 @@ func hydrateMediaFileArtwork(ctx context.Context, db dbx.Builder, mfs model.Medi for i := range mfs { mf := &mfs[i] applyItemImage(albumInfos, mf.AlbumID, &mf.AlbumImage) - eligible := mf.HasCoverArt && conf.Server.EnableMediaFileCoverArt + eligible := mf.HasCoverArt && conf.Server().EnableMediaFileCoverArt ownInfo, ownResolved := mfInfos[mf.ID] if eligible && ownResolved && !ownInfo.Absent() { mf.ItemImage = ownInfo.Image() diff --git a/persistence/artwork_hydration_test.go b/persistence/artwork_hydration_test.go index 89182d6cc..b07a52c78 100644 --- a/persistence/artwork_hydration_test.go +++ b/persistence/artwork_hydration_test.go @@ -8,7 +8,6 @@ import ( "github.com/Masterminds/squirrel" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -239,8 +238,7 @@ var _ = Describe("Artwork hydration", func() { BeforeEach(func() { repo = NewMediaFileRepository(GetDBXBuilder()) - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableMediaFileCoverArt = true + conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true }) }) It("resolves the embedded-eligible fallback matrix", func() { @@ -360,7 +358,7 @@ var _ = Describe("Artwork hydration", func() { }) It("uses album info for an eligible file when EnableMediaFileCoverArt is off", func() { - conf.Server.EnableMediaFileCoverArt = false + conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false }) setCover("1001", true) DeferCleanup(func() { setCover("1001", false) }) diff --git a/persistence/criteria_sql_benchmark_test.go b/persistence/criteria_sql_benchmark_test.go index 30c1ba100..4b0571c3b 100644 --- a/persistence/criteria_sql_benchmark_test.go +++ b/persistence/criteria_sql_benchmark_test.go @@ -10,7 +10,6 @@ import ( "github.com/Masterminds/squirrel" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" @@ -30,9 +29,9 @@ const ( // between the current implementation (merged join-table via criteria pipeline) and // the old baseline (unmerged json_tree subqueries). func BenchmarkSmartPlaylistRole(b *testing.B) { - configtest.SetupConfig() + b.Cleanup(conf.SnapshotConfig()) tmpDir := b.TempDir() - conf.Server.DbPath = filepath.Join(tmpDir, "bench-smartpl.db") + conf.Update(func(c *conf.Options) { c.DbPath = filepath.Join(tmpDir, "bench-smartpl.db") }) cleanup := db.Init(context.Background()) defer cleanup() log.SetLevel(log.LevelFatal) @@ -65,9 +64,9 @@ func BenchmarkSmartPlaylistRole(b *testing.B) { // between the current implementation (merged NOT EXISTS via criteria pipeline) and the // old baseline (one separate NOT EXISTS subquery per pattern). func BenchmarkSmartPlaylistNegatedRole(b *testing.B) { - configtest.SetupConfig() + b.Cleanup(conf.SnapshotConfig()) tmpDir := b.TempDir() - conf.Server.DbPath = filepath.Join(tmpDir, "bench-smartpl-neg.db") + conf.Update(func(c *conf.Options) { c.DbPath = filepath.Join(tmpDir, "bench-smartpl-neg.db") }) cleanup := db.Init(context.Background()) defer cleanup() log.SetLevel(log.LevelFatal) diff --git a/persistence/e2e/e2e_suite_test.go b/persistence/e2e/e2e_suite_test.go index a757901d3..94724f62a 100644 --- a/persistence/e2e/e2e_suite_test.go +++ b/persistence/e2e/e2e_suite_test.go @@ -38,6 +38,8 @@ func TestSmartPlaylistE2E(t *testing.T) { RunSpecs(t, "Smart Playlist E2E Suite") } +var _ = configtest.RestoreAfterEachSpec() + type _t = map[string]any var template = storagetest.Template @@ -239,12 +241,14 @@ var _ = BeforeSuite(func() { tmpDir := GinkgoT().TempDir() dbFilePath = filepath.Join(tmpDir, "smartplaylist-e2e.db") snapshotPath = filepath.Join(tmpDir, "smartplaylist-e2e.db.snapshot") - conf.Server.DbPath = dbFilePath + "?_journal_mode=WAL" + conf.Update(func(c *conf.Options) { c.DbPath = dbFilePath + "?_journal_mode=WAL" }) db.Db().SetMaxOpenConns(1) - conf.Server.MusicFolder = "fake:///music" - conf.Server.DevExternalScanner = false - conf.Server.SmartPlaylistRefreshDelay = 0 + conf.Update(func(c *conf.Options) { + c.MusicFolder = "fake:///music" + c.DevExternalScanner = false + c.SmartPlaylistRefreshDelay = 0 + }) db.Init(ctx) @@ -340,10 +344,12 @@ func restoreDB() { func setupTestDB() { ctx = request.WithUser(GinkgoT().Context(), adminUser) - DeferCleanup(configtest.SetupConfig()) - conf.Server.MusicFolder = "fake:///music" - conf.Server.DevExternalScanner = false - conf.Server.SmartPlaylistRefreshDelay = 0 + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.MusicFolder = "fake:///music" + c.DevExternalScanner = false + c.SmartPlaylistRefreshDelay = 0 + }) restoreDB() ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} diff --git a/persistence/helpers.go b/persistence/helpers.go index 1da31cf02..06e3e9b3e 100644 --- a/persistence/helpers.go +++ b/persistence/helpers.go @@ -87,7 +87,7 @@ var sortOrderRegex = regexp.MustCompile(`order_([a-z_]+)`) // naturalSort makes a plain text column sort numbers by value, leaving it alone // otherwise so it keeps its declared collation. Parens guard buildSortOrder's space split. func naturalSort(col string) string { - if !conf.Server.EnableNaturalSorting { + if !conf.Server().EnableNaturalSorting { return col } return fmt.Sprintf("(%s collate %s)", col, db.NaturalCollation) @@ -99,11 +99,11 @@ func naturalSort(col string) string { // It finds order column names anywhere in the substring func mapSortOrder(tableName, order string) string { col := tableName + ".order_$1" - if conf.Server.PreferSortTags { + if conf.Server().PreferSortTags { col = fmt.Sprintf("coalesce(nullif(%[1]s.sort_$1,''),%[1]s.order_$1)", tableName) } collation := "nocase" - if conf.Server.EnableNaturalSorting { + if conf.Server().EnableNaturalSorting { collation = db.NaturalCollation } repl := fmt.Sprintf("(%s collate %s)", col, collation) diff --git a/persistence/helpers_test.go b/persistence/helpers_test.go index 3019609f3..6b00ac250 100644 --- a/persistence/helpers_test.go +++ b/persistence/helpers_test.go @@ -5,7 +5,6 @@ import ( "github.com/Masterminds/squirrel" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -87,9 +86,6 @@ var _ = Describe("Helpers", func() { }) Describe("mapSortOrder", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) It("does not change the sort string if there are no order columns", func() { Expect(mapSortOrder("album", "album_name asc")).To(Equal("album_name asc")) @@ -97,8 +93,10 @@ var _ = Describe("Helpers", func() { DescribeTable("maps order columns to a collated expression", func(preferSortTags, naturalSorting bool, expected string) { - conf.Server.PreferSortTags = preferSortTags - conf.Server.EnableNaturalSorting = naturalSorting + conf.Update(func(c *conf.Options) { + c.PreferSortTags = preferSortTags + c.EnableNaturalSorting = naturalSorting + }) Expect(mapSortOrder("album", "ORDER_ALBUM_NAME asc")).To(Equal(expected)) }, Entry("qualified column", false, false, @@ -112,7 +110,7 @@ var _ = Describe("Helpers", func() { ) It("changes multiple order columns to sort expressions", func() { - conf.Server.PreferSortTags = true + conf.Update(func(c *conf.Options) { c.PreferSortTags = true }) sort := "compilation, order_title asc, order_album_artist_name desc, year desc" Expect(mapSortOrder("album", sort)).To(Equal( `compilation, (coalesce(nullif(album.sort_title,''),album.order_title) collate nocase) asc,` + @@ -121,16 +119,13 @@ var _ = Describe("Helpers", func() { }) Describe("naturalSort", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) It("leaves the column alone by default, keeping its declared collation", func() { Expect(naturalSort("media_file.title")).To(Equal("media_file.title")) }) It("applies the natural collation when enabled", func() { - conf.Server.EnableNaturalSorting = true + conf.Update(func(c *conf.Options) { c.EnableNaturalSorting = true }) Expect(naturalSort("media_file.title")).To(Equal("(media_file.title collate NATSORT)")) }) }) diff --git a/persistence/library_repository.go b/persistence/library_repository.go index 85da65cbc..3d5363f74 100644 --- a/persistence/library_repository.go +++ b/persistence/library_repository.go @@ -136,15 +136,15 @@ ON CONFLICT (user_id, library_id) DO NOTHING;`, // TODO Remove this method when we have a proper UI to add libraries // This is a temporary method to store the music folder path from the config in the DB func (r *libraryRepository) StoreMusicFolder(ctx context.Context) error { - sq := Update(r.tableName).Set("path", conf.Server.MusicFolder). + sq := Update(r.tableName).Set("path", conf.Server().MusicFolder). Set("updated_at", time.Now()). Where(Eq{"id": model.DefaultLibraryID}). - Where(NotEq{"path": conf.Server.MusicFolder}) + Where(NotEq{"path": conf.Server().MusicFolder}) rowsAffected, err := r.executeSQL(ctx, sq) if err == nil && rowsAffected > 0 { libLock.Lock() defer libLock.Unlock() - libCache[model.DefaultLibraryID] = conf.Server.MusicFolder + libCache[model.DefaultLibraryID] = conf.Server().MusicFolder } return err } diff --git a/persistence/library_repository_test.go b/persistence/library_repository_test.go index bf485a06f..0da217876 100644 --- a/persistence/library_repository_test.go +++ b/persistence/library_repository_test.go @@ -6,7 +6,6 @@ import ( "github.com/Masterminds/squirrel" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -149,7 +148,6 @@ var _ = Describe("LibraryRepository", func() { libBefore, err = repo.Get(ctx, model.DefaultLibraryID) Expect(err).ToNot(HaveOccurred()) - DeferCleanup(configtest.SetupConfig()) DeferCleanup(func() { _, _ = conn.NewQuery("update library set path = {:path}, updated_at = {:updated_at} where id = {:id}"). Bind(dbx.Params{"path": libBefore.Path, "updated_at": libBefore.UpdatedAt, "id": model.DefaultLibraryID}). @@ -161,7 +159,7 @@ var _ = Describe("LibraryRepository", func() { }) It("skips updating the default library when the configured path is unchanged", func() { - conf.Server.MusicFolder = libBefore.Path + conf.Update(func(c *conf.Options) { c.MusicFolder = libBefore.Path }) Expect(repo.StoreMusicFolder(ctx)).To(Succeed()) libAfter, err := repo.Get(ctx, model.DefaultLibraryID) @@ -171,12 +169,12 @@ var _ = Describe("LibraryRepository", func() { }) It("updates the default library only when the configured path changes", func() { - conf.Server.MusicFolder = libBefore.Path + "-updated" + conf.Update(func(c *conf.Options) { c.MusicFolder = libBefore.Path + "-updated" }) Expect(repo.StoreMusicFolder(ctx)).To(Succeed()) libAfter, err := repo.Get(ctx, model.DefaultLibraryID) Expect(err).ToNot(HaveOccurred()) - Expect(libAfter.Path).To(Equal(conf.Server.MusicFolder)) + Expect(libAfter.Path).To(Equal(conf.Server().MusicFolder)) Expect(libAfter.UpdatedAt).ToNot(Equal(libBefore.UpdatedAt)) }) }) diff --git a/persistence/mediafile_repository.go b/persistence/mediafile_repository.go index b9a5c3374..6369c5b71 100644 --- a/persistence/mediafile_repository.go +++ b/persistence/mediafile_repository.go @@ -140,7 +140,7 @@ func mediaFileArtistFilter(_ string, value any) Sqlizer { } func mediaFileRecentlyAddedSort() string { - if conf.Server.RecentlyAddedByModTime { + if conf.Server().RecentlyAddedByModTime { return "media_file.updated_at, media_file.id" } return "media_file.created_at, media_file.id" diff --git a/persistence/mediafile_repository_test.go b/persistence/mediafile_repository_test.go index 14590090c..c782b44b4 100644 --- a/persistence/mediafile_repository_test.go +++ b/persistence/mediafile_repository_test.go @@ -10,7 +10,6 @@ import ( "github.com/Masterminds/squirrel" "github.com/deluan/rest" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/criteria" @@ -530,7 +529,6 @@ var _ = Describe("MediaRepository", func() { var testMediaFiles []model.MediaFile BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) // Create test media files with specific timestamps testMediaFiles = []model.MediaFile{ @@ -606,7 +604,7 @@ var _ = Describe("MediaRepository", func() { var testRepo model.MediaFileRepository BeforeEach(func() { - conf.Server.RecentlyAddedByModTime = false + conf.Update(func(c *conf.Options) { c.RecentlyAddedByModTime = false }) // Create repository AFTER setting config testRepo = NewMediaFileRepository(GetDBXBuilder()) }) @@ -648,7 +646,7 @@ var _ = Describe("MediaRepository", func() { var testRepo model.MediaFileRepository BeforeEach(func() { - conf.Server.RecentlyAddedByModTime = true + conf.Update(func(c *conf.Options) { c.RecentlyAddedByModTime = true }) // Create repository AFTER setting config testRepo = NewMediaFileRepository(GetDBXBuilder()) }) @@ -671,7 +669,7 @@ var _ = Describe("MediaRepository", func() { }) It("breaks ties deterministically when files share the same created_at", func() { - conf.Server.RecentlyAddedByModTime = false + conf.Update(func(c *conf.Options) { c.RecentlyAddedByModTime = false }) ctx := log.NewContext(GinkgoT().Context()) ctx = request.WithUser(ctx, model.User{ID: "userid"}) repo := NewMediaFileRepository(GetDBXBuilder()) diff --git a/persistence/persistence_suite_test.go b/persistence/persistence_suite_test.go index afed8f0b3..f1e2dd091 100644 --- a/persistence/persistence_suite_test.go +++ b/persistence/persistence_suite_test.go @@ -11,6 +11,7 @@ import ( "github.com/Masterminds/squirrel" _ "github.com/mattn/go-sqlite3" "github.com/navidrome/navidrome/conf" + "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" @@ -26,13 +27,15 @@ func TestPersistence(t *testing.T) { //os.Remove("./test-123.db") //conf.Server.DbPath = "./test-123.db" - conf.Server.DbPath = "file::memory:?cache=shared&_foreign_keys=on" + conf.Update(func(c *conf.Options) { c.DbPath = "file::memory:?cache=shared&_foreign_keys=on" }) defer db.Init(context.Background())() log.SetLevel(log.LevelFatal) RegisterFailHandler(Fail) RunSpecs(t, "Persistence Suite") } +var _ = configtest.RestoreAfterEachSpec() + func mf(mf model.MediaFile) model.MediaFile { mf.Tags = model.Tags{} mf.LibraryID = 1 diff --git a/persistence/playlist_repository_test.go b/persistence/playlist_repository_test.go index b7be0588b..749fa85d7 100644 --- a/persistence/playlist_repository_test.go +++ b/persistence/playlist_repository_test.go @@ -7,7 +7,6 @@ import ( "github.com/Masterminds/squirrel" "github.com/deluan/rest" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/criteria" @@ -31,8 +30,7 @@ var _ = Describe("PlaylistRepository", func() { var ids []string BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableNaturalSorting = true + conf.Update(func(c *conf.Options) { c.EnableNaturalSorting = true }) ctx := log.NewContext(GinkgoT().Context()) ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "userid", IsAdmin: true}) repo = NewPlaylistRepository(GetDBXBuilder()) diff --git a/persistence/playqueue_repository_test.go b/persistence/playqueue_repository_test.go index 877faddfc..94bd9bd52 100644 --- a/persistence/playqueue_repository_test.go +++ b/persistence/playqueue_repository_test.go @@ -5,7 +5,6 @@ import ( "time" "github.com/Masterminds/squirrel" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/id" @@ -19,7 +18,6 @@ var _ = Describe("PlayQueueRepository", func() { var ctx context.Context BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) ctx = log.NewContext(context.TODO()) ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "userid", IsAdmin: true}) repo = NewPlayQueueRepository(GetDBXBuilder()) diff --git a/persistence/share_repository_test.go b/persistence/share_repository_test.go index 33b5e2110..06cf1e8e5 100644 --- a/persistence/share_repository_test.go +++ b/persistence/share_repository_test.go @@ -6,7 +6,6 @@ import ( "github.com/Masterminds/squirrel" "github.com/deluan/rest" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -20,7 +19,6 @@ var _ = Describe("ShareRepository", func() { var adminUser = model.User{ID: "admin", UserName: "admin", IsAdmin: true} BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) ctx = request.WithUser(log.NewContext(GinkgoT().Context()), adminUser) repo = NewShareRepository(GetDBXBuilder()) diff --git a/persistence/smart_playlist_repository_test.go b/persistence/smart_playlist_repository_test.go index 4d4c5edb0..57a1e7e60 100644 --- a/persistence/smart_playlist_repository_test.go +++ b/persistence/smart_playlist_repository_test.go @@ -6,7 +6,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/criteria" @@ -113,13 +112,10 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { }) Context("child smart playlists", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) When("refresh delay has expired", func() { It("should refresh tracks for smart playlist referenced in parent smart playlist criteria", func() { - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) childRules := &criteria.Criteria{ Expression: criteria.All{ @@ -177,7 +173,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { }) It("does not recurse forever when two smart playlists reference each other", func() { - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) plsA := model.Playlist{Name: "Cycle A", OwnerID: "userid", Public: true, Rules: &criteria.Criteria{ Expression: criteria.All{criteria.Contains{"title": "Day"}}, @@ -199,7 +195,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { }) It("does not treat an empty path as a reference to every playlist without a path", func() { - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) bystander := model.Playlist{Name: "Bystander", OwnerID: "userid", Public: true, Rules: &criteria.Criteria{ Expression: criteria.All{criteria.Contains{"title": "Day"}}, @@ -222,7 +218,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { }) It("matches a child path stored in a different Unicode normalization form", func() { - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) child := model.Playlist{Name: "NFD Child", OwnerID: "userid", Public: true, Path: filepath.FromSlash("/mu\u0301sica/child.nsp"), Rules: &criteria.Criteria{ Expression: criteria.All{criteria.Contains{"title": "Day"}}, @@ -244,7 +240,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { When("refresh delay has not expired", func() { It("should NOT refresh tracks for smart playlist referenced in parent smart playlist criteria", func() { - conf.Server.SmartPlaylistRefreshDelay = 1 * time.Hour + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = 1 * time.Hour }) childEvaluatedAt := time.Now().Add(-30 * time.Minute) childRules := &criteria.Criteria{ @@ -285,12 +281,9 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { }) Context("per-playlist refreshDelay", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) It("does NOT refresh when the per-playlist delay has not elapsed, even if global has", func() { - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) evaluatedAt := time.Now().Add(-1 * time.Hour) rules := &criteria.Criteria{ @@ -309,7 +302,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { }) It("refreshes when the per-playlist delay has elapsed, even if global has not", func() { - conf.Server.SmartPlaylistRefreshDelay = 1 * time.Hour + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = 1 * time.Hour }) evaluatedAt := time.Now().Add(-10 * time.Minute) rules := &criteria.Criteria{ @@ -385,7 +378,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { Expect(repo.Put(ctx, &newPls)).To(Succeed()) testPlaylistID = newPls.ID - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) pls, err := repo.GetWithTracks(ctx, newPls.ID, true, false) Expect(err).ToNot(HaveOccurred()) @@ -408,7 +401,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { Expect(repo.Put(ctx, &newPls)).To(Succeed()) testPlaylistID = newPls.ID - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) pls, err := repo.GetWithTracks(ctx, newPls.ID, true, false) Expect(err).ToNot(HaveOccurred()) @@ -433,7 +426,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { Expect(repo.Put(ctx, &newPls)).To(Succeed()) testPlaylistID = newPls.ID - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) pls, err := repo.GetWithTracks(ctx, newPls.ID, true, false) Expect(err).ToNot(HaveOccurred()) @@ -455,7 +448,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { Expect(repo.Put(ctx, &newPls)).To(Succeed()) testPlaylistID = newPls.ID - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) pls, err := repo.GetWithTracks(ctx, newPls.ID, true, false) Expect(err).ToNot(HaveOccurred()) @@ -475,7 +468,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { Expect(repo.Put(ctx, &newPls)).To(Succeed()) testPlaylistID = newPls.ID - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) pls, err := repo.GetWithTracks(ctx, newPls.ID, true, false) Expect(err).ToNot(HaveOccurred()) @@ -510,7 +503,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { Expect(repo.Put(ctx, &stringPls)).To(Succeed()) testPlaylistID = stringPls.ID - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) boolResult, err := repo.GetWithTracks(ctx, boolPls.ID, true, false) Expect(err).ToNot(HaveOccurred()) stringResult, err := repo.GetWithTracks(ctx, stringPls.ID, true, false) @@ -530,8 +523,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { Describe("Smart Playlists with Album Aggregate Criteria", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) }) trackIDsOf := func(rules *criteria.Criteria) []string { @@ -634,7 +626,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { testPlaylistID = newPls.ID By("refreshing the smart playlist") - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second // Force refresh + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) // Force refresh pls, err := repo.GetWithTracks(ctx, newPls.ID, true, false) Expect(err).ToNot(HaveOccurred()) @@ -655,7 +647,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { testPlaylistID = newPls.ID By("refreshing the smart playlist") - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second // Force refresh + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) // Force refresh pls, err := repo.GetWithTracks(ctx, newPls.ID, true, false) Expect(err).ToNot(HaveOccurred()) @@ -775,7 +767,7 @@ var _ = Describe("PlaylistRepository - Smart Playlists", func() { testPlaylistID = newPls.ID By("refreshing the smart playlist") - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second // Force refresh + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) // Force refresh pls, err := restrictedRepo.GetWithTracks(ctx, newPls.ID, true, false) Expect(err).ToNot(HaveOccurred()) diff --git a/persistence/sort_index_coverage_test.go b/persistence/sort_index_coverage_test.go index 138cb32c8..eb4faf8a3 100644 --- a/persistence/sort_index_coverage_test.go +++ b/persistence/sort_index_coverage_test.go @@ -9,7 +9,6 @@ import ( "slices" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" @@ -125,8 +124,7 @@ var _ = Describe("Sort index coverage", func() { } It("uses an index for recently_added when RecentlyAddedByModTime is enabled", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.RecentlyAddedByModTime = true + conf.Update(func(c *conf.Options) { c.RecentlyAddedByModTime = true }) for _, c := range cases[:2] { // media_file and album r := c.newRepo(newCtx()) for _, dir := range []string{"asc", "desc"} { diff --git a/persistence/sql_annotations.go b/persistence/sql_annotations.go index 51c7dc146..ad8954339 100644 --- a/persistence/sql_annotations.go +++ b/persistence/sql_annotations.go @@ -77,7 +77,7 @@ func (r sqlRepository) withAnnotation(ctx context.Context, query SelectBuilder, "play_date", "rated_at", ) - if conf.Server.AlbumPlayCountMode == consts.AlbumPlayCountModeNormalized && r.tableName == "album" { + if conf.Server().AlbumPlayCountMode == consts.AlbumPlayCountModeNormalized && r.tableName == "album" { query = query.Columns( fmt.Sprintf("round(coalesce(round(cast(play_count as float) / coalesce(%[1]s.song_count, 1), 1), 0)) as play_count", r.tableName), ) diff --git a/persistence/sql_base_repository.go b/persistence/sql_base_repository.go index 03cc6a01b..eb6ba3518 100644 --- a/persistence/sql_base_repository.go +++ b/persistence/sql_base_repository.go @@ -128,7 +128,7 @@ func (r *sqlRepository) setSortMappings(mappings map[string]string, tableName .. if len(tableName) > 0 { tn = tableName[0] } - if conf.Server.PreferSortTags || conf.Server.EnableNaturalSorting { + if conf.Server().PreferSortTags || conf.Server().EnableNaturalSorting { for k, v := range mappings { mappings[k] = mapSortOrder(tn, v) } @@ -155,7 +155,14 @@ func (r sqlRepository) applyOptions(sq SelectBuilder, options ...model.QueryOpti sq = sq.Offset(uint64(options[0].Offset)) } if options[0].Sort != "" { - sq = sq.OrderBy(r.buildSortOrder(options[0].Sort, options[0].Order)) + sort, order := options[0].Sort, options[0].Order + // Per-key directions are absolute, so buildSortOrder gets an ascending baseline. + // resetSeededRandom has already rewritten "random" to SEEDEDRAND by here. + if len(options[0].SortOrders) > 0 && sort != "random" && !strings.HasPrefix(sort, "SEEDEDRAND(") { + sort = r.sortWithKeyOrders(sort, options[0].SortOrders) + order = "" + } + sq = sq.OrderBy(r.buildSortOrder(sort, order)) } } return sq @@ -196,6 +203,39 @@ func (r sqlRepository) lookupSortMapping(sort string) (mapping, snakeCased strin return mapping, snakeCased, ok } +// sortWithKeyOrders maps each logical sort key, then marks descending keys so buildSortOrder +// keeps that direction on every column the mapping expands into. +func (r sqlRepository) sortWithKeyOrders(sort string, orders []string) string { + keys := strings.FieldsFunc(sort, splitFunc(',')) + out := make([]string, 0, len(keys)) + for i, key := range keys { + key = strings.TrimSpace(key) + if key == "" { + continue + } + mapped := r.sortMapping(key) + if !descendingOrder(i, orders) { + out = append(out, mapped) + continue + } + for _, col := range strings.FieldsFunc(mapped, splitFunc(',')) { + out = append(out, strings.TrimSpace(col)+" desc") + } + } + return strings.Join(out, ", ") +} + +func descendingOrder(i int, orders []string) bool { + if len(orders) == 0 { + return false + } + raw := orders[0] + if i < len(orders) { + raw = orders[i] + } + return raw == "desc" +} + func (r sqlRepository) buildSortOrder(sort, order string) string { sort = r.sortMapping(sort) order = strings.ToLower(strings.TrimSpace(order)) @@ -475,7 +515,7 @@ func (r sqlRepository) queryAllSlice(ctx context.Context, sq SelectBuilder, resp // optimizePagination uses a less inefficient pagination, by not using OFFSET. // See https://gist.github.com/ssokolow/262503 func (r sqlRepository) optimizePagination(sq SelectBuilder, options model.QueryOptions) SelectBuilder { - if options.Offset > conf.Server.DevOffsetOptimize { + if options.Offset > conf.Server().DevOffsetOptimize { sq = sq.RemoveOffset() rowidSq := sq.RemoveColumns().Columns(r.tableName + ".rowid") rowidSq = rowidSq.Limit(uint64(options.Offset)) diff --git a/persistence/sql_base_repository_test.go b/persistence/sql_base_repository_test.go index 4b42e7f1d..ab364e794 100644 --- a/persistence/sql_base_repository_test.go +++ b/persistence/sql_base_repository_test.go @@ -62,6 +62,18 @@ var _ = Describe("sqlRepository", func() { sql, _, _ := sq.ToSql() Expect(sql).To(Equal("SELECT * FROM test ORDER BY title desc LIMIT 1 OFFSET 2")) }) + + It("applies a per-key SortOrder after mappings expand", func() { + r.sortMappings["max_year"] = "coalesce(nullif(original_date,''), cast(max_year as text)), release_date" + sq = r.applyOptions(sq, model.QueryOptions{ + Sort: "duration, name, max_year, play_count", + Order: "desc", + SortOrders: []string{"desc", "asc", "desc"}, + }) + sql, _, _ := sq.ToSql() + Expect(sql).To(Equal("SELECT * FROM test ORDER BY duration desc, title asc, " + + "coalesce(nullif(original_date,''), cast(max_year as text)) desc, release_date desc, play_count desc")) + }) }) Describe("toSQL", func() { diff --git a/persistence/sql_restful_test.go b/persistence/sql_restful_test.go index 32f418b8e..3d40e88be 100644 --- a/persistence/sql_restful_test.go +++ b/persistence/sql_restful_test.go @@ -7,7 +7,6 @@ import ( "github.com/Masterminds/squirrel" "github.com/deluan/rest" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -27,8 +26,7 @@ var _ = Describe("sqlRestful", func() { }) It(`returns nil if tries a filter with legacySearchExpr("'")`, func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = "legacy" + conf.Update(func(c *conf.Options) { c.Search.Backend = "legacy" }) r.filterMappings = map[string]filterFunc{ "name": fullTextFilter("table"), } @@ -78,8 +76,7 @@ var _ = Describe("sqlRestful", func() { var mbidFields []string BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = "legacy" + conf.Update(func(c *conf.Options) { c.Search.Backend = "legacy" }) tableName = "test_table" mbidFields = []string{"mbid", "artist_mbid"} filter = fullTextFilter(tableName, mbidFields...) @@ -138,7 +135,7 @@ var _ = Describe("sqlRestful", func() { Context("when SearchFullString config changes behavior", func() { It("uses different separator with SearchFullString=false", func() { - conf.Server.Search.FullString = false + conf.Update(func(c *conf.Options) { c.Search.FullString = false }) result := filter("search", "test query") sql, args, err := result.ToSql() @@ -150,7 +147,7 @@ var _ = Describe("sqlRestful", func() { }) It("uses no separator with SearchFullString=true", func() { - conf.Server.Search.FullString = true + conf.Update(func(c *conf.Options) { c.Search.FullString = true }) result := filter("search", "test query") sql, args, err := result.ToSql() @@ -164,7 +161,7 @@ var _ = Describe("sqlRestful", func() { Context("single-character queries (regression: must not be rejected)", func() { It("returns valid filter for single-char query with legacy backend", func() { - conf.Server.Search.Backend = "legacy" + conf.Update(func(c *conf.Options) { c.Search.Backend = "legacy" }) result := filter("search", "a") Expect(result).ToNot(BeNil(), "single-char REST filter must not be dropped") sql, args, err := result.ToSql() @@ -174,8 +171,10 @@ var _ = Describe("sqlRestful", func() { }) It("returns valid filter for single-char query with FTS backend", func() { - conf.Server.Search.Backend = "fts" - conf.Server.Search.FullString = false + conf.Update(func(c *conf.Options) { + c.Search.Backend = "fts" + c.Search.FullString = false + }) ftsFilter := fullTextFilter(tableName, mbidFields...) result := ftsFilter("search", "a") Expect(result).ToNot(BeNil(), "single-char REST filter must not be dropped") diff --git a/persistence/sql_search.go b/persistence/sql_search.go index aa8707247..21e2571d9 100644 --- a/persistence/sql_search.go +++ b/persistence/sql_search.go @@ -39,7 +39,7 @@ type searchStrategy interface { // getSearchStrategy returns the appropriate search strategy based on config and query content. // Returns nil when the query produces no searchable tokens. func getSearchStrategy(tableName, query string) searchStrategy { - if conf.Server.Search.Backend == "legacy" || conf.Server.Search.FullString { + if conf.Server().Search.Backend == "legacy" || conf.Server().Search.FullString { return newLegacySearch(tableName, query) } if containsCJK(query) { diff --git a/persistence/sql_search_like.go b/persistence/sql_search_like.go index c7d94cc04..5cd500169 100644 --- a/persistence/sql_search_like.go +++ b/persistence/sql_search_like.go @@ -57,7 +57,7 @@ func legacySearchExpr(tableName string, s string) Sqlizer { return nil } var sep string - if !conf.Server.Search.FullString { + if !conf.Server().Search.FullString { sep = " " } parts := strings.Split(q, " ") diff --git a/persistence/sql_search_like_test.go b/persistence/sql_search_like_test.go index 2bfeba29b..048aa2c8c 100644 --- a/persistence/sql_search_like_test.go +++ b/persistence/sql_search_like_test.go @@ -4,7 +4,6 @@ import ( "context" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -106,8 +105,7 @@ var _ = Describe("Legacy Integration Search", func() { BeforeEach(func() { ctx = request.WithUser(log.NewContext(GinkgoT().Context()), adminUser) - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = "legacy" + conf.Update(func(c *conf.Options) { c.Search.Backend = "legacy" }) conn := GetDBXBuilder() mr = NewMediaFileRepository(conn) diff --git a/persistence/sql_search_test.go b/persistence/sql_search_test.go index 68ee205b4..018fb3716 100644 --- a/persistence/sql_search_test.go +++ b/persistence/sql_search_test.go @@ -2,7 +2,6 @@ package persistence import ( "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -16,9 +15,10 @@ var _ = Describe("sqlRepository", func() { Describe("getSearchStrategy", func() { It("returns FTS strategy by default", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = "fts" - conf.Server.Search.FullString = false + conf.Update(func(c *conf.Options) { + c.Search.Backend = "fts" + c.Search.FullString = false + }) strategy := getSearchStrategy("media_file", "test") Expect(strategy).ToNot(BeNil()) @@ -28,9 +28,10 @@ var _ = Describe("sqlRepository", func() { }) It("returns legacy LIKE strategy when SearchBackend is legacy", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = "legacy" - conf.Server.Search.FullString = false + conf.Update(func(c *conf.Options) { + c.Search.Backend = "legacy" + c.Search.FullString = false + }) strategy := getSearchStrategy("media_file", "test") Expect(strategy).ToNot(BeNil()) @@ -40,9 +41,10 @@ var _ = Describe("sqlRepository", func() { }) It("falls back to legacy LIKE strategy when SearchFullString is enabled", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = "fts" - conf.Server.Search.FullString = true + conf.Update(func(c *conf.Options) { + c.Search.Backend = "fts" + c.Search.FullString = true + }) strategy := getSearchStrategy("media_file", "test") Expect(strategy).ToNot(BeNil()) @@ -52,9 +54,10 @@ var _ = Describe("sqlRepository", func() { }) It("routes CJK queries to LIKE strategy instead of FTS", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = "fts" - conf.Server.Search.FullString = false + conf.Update(func(c *conf.Options) { + c.Search.Backend = "fts" + c.Search.FullString = false + }) strategy := getSearchStrategy("media_file", "周杰伦") Expect(strategy).ToNot(BeNil()) @@ -66,9 +69,10 @@ var _ = Describe("sqlRepository", func() { }) It("routes non-CJK queries to FTS strategy", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = "fts" - conf.Server.Search.FullString = false + conf.Update(func(c *conf.Options) { + c.Search.Backend = "fts" + c.Search.FullString = false + }) strategy := getSearchStrategy("media_file", "beatles") Expect(strategy).ToNot(BeNil()) @@ -78,27 +82,30 @@ var _ = Describe("sqlRepository", func() { }) It("returns non-nil for single-character query (no min-length in strategy)", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = "fts" - conf.Server.Search.FullString = false + conf.Update(func(c *conf.Options) { + c.Search.Backend = "fts" + c.Search.FullString = false + }) strategy := getSearchStrategy("media_file", "a") Expect(strategy).ToNot(BeNil(), "single-char queries must be accepted by strategies (min-length is enforced in doSearch)") }) It("returns non-nil for single-character query with legacy backend", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = "legacy" - conf.Server.Search.FullString = false + conf.Update(func(c *conf.Options) { + c.Search.Backend = "legacy" + c.Search.FullString = false + }) strategy := getSearchStrategy("media_file", "a") Expect(strategy).ToNot(BeNil(), "single-char queries must be accepted by legacy strategy (min-length is enforced in doSearch)") }) It("uses legacy for CJK when SearchBackend is legacy", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = "legacy" - conf.Server.Search.FullString = false + conf.Update(func(c *conf.Options) { + c.Search.Backend = "legacy" + c.Search.FullString = false + }) strategy := getSearchStrategy("media_file", "周杰伦") Expect(strategy).ToNot(BeNil()) diff --git a/persistence/tag_library_filtering_test.go b/persistence/tag_library_filtering_test.go index a4382dccf..6399ab3bb 100644 --- a/persistence/tag_library_filtering_test.go +++ b/persistence/tag_library_filtering_test.go @@ -5,7 +5,6 @@ import ( "time" "github.com/deluan/rest" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/id" @@ -44,7 +43,6 @@ var _ = Describe("Tag Library Filtering", func() { } BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) // Generate unique path suffix to avoid conflicts with other tests uniqueSuffix := time.Now().Format("20060102150405.000") diff --git a/persistence/tag_repository_test.go b/persistence/tag_repository_test.go index 730d26357..ae3eabcdb 100644 --- a/persistence/tag_repository_test.go +++ b/persistence/tag_repository_test.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/deluan/rest" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/id" @@ -22,7 +21,6 @@ var _ = Describe("TagRepository", func() { var ctx context.Context BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) ctx = request.WithUser(log.NewContext(context.TODO()), model.User{ID: "userid", UserName: "johndoe", IsAdmin: true}) tagRepo := NewTagRepository(GetDBXBuilder()) repo = tagRepo diff --git a/persistence/user_repository.go b/persistence/user_repository.go index 26f7b19d4..afdc86390 100644 --- a/persistence/user_repository.go +++ b/persistence/user_repository.go @@ -281,7 +281,7 @@ func (r *userRepository) Update(ctx context.Context, id string, entity model.Use return rest.ErrPermissionDenied } if !usr.IsAdmin { - if !conf.Server.EnableUserEditing { + if !conf.Server().EnableUserEditing { return rest.ErrPermissionDenied } u.IsAdmin = false @@ -394,11 +394,11 @@ func keyTo32Bytes(input string) []byte { func (r *userRepository) initPasswordEncryptionKey(ctx context.Context) error { encKey = keyTo32Bytes(consts.DefaultEncryptionKey) - if conf.Server.PasswordEncryptionKey == "" { + if conf.Server().PasswordEncryptionKey == "" { return nil } - key := keyTo32Bytes(conf.Server.PasswordEncryptionKey) + key := keyTo32Bytes(conf.Server().PasswordEncryptionKey) keySum := fmt.Sprintf("%x", sha256.Sum256(key)) ctx = log.WithSecrets(ctx, keySum) diff --git a/plugins/host_artwork_test.go b/plugins/host_artwork_test.go index 311bf21d5..2e3f75844 100644 --- a/plugins/host_artwork_test.go +++ b/plugins/host_artwork_test.go @@ -11,7 +11,6 @@ import ( "strings" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -44,10 +43,12 @@ var _ = Describe("ArtworkService", Ordered, func() { hashHex := hex.EncodeToString(hash[:]) // Setup config - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + }) // Initialize auth (required for token generation) ds := &tests.MockDataStore{MockedProperty: &tests.MockedPropertyRepo{}} diff --git a/plugins/host_cache_test.go b/plugins/host_cache_test.go index 925856701..9906f2e28 100644 --- a/plugins/host_cache_test.go +++ b/plugins/host_cache_test.go @@ -14,7 +14,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" @@ -341,10 +340,12 @@ var _ = Describe("CacheService Integration", Ordered, func() { hashHex := hex.EncodeToString(hash[:]) // Setup config - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + }) // Setup mock DataStore with pre-enabled plugin mockPluginRepo := tests.CreateMockPluginRepo() diff --git a/plugins/host_config_test.go b/plugins/host_config_test.go index 80b06efe1..3a51f36e0 100644 --- a/plugins/host_config_test.go +++ b/plugins/host_config_test.go @@ -11,7 +11,6 @@ import ( "path/filepath" "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" @@ -53,10 +52,12 @@ func setupTestConfigPlugin(configJSON string) (*Manager, func(context.Context, t hashHex := hex.EncodeToString(hash[:]) // Setup config - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + }) // Setup mock DataStore mockPluginRepo := tests.CreateMockPluginRepo() diff --git a/plugins/host_kvstore.go b/plugins/host_kvstore.go index 2224b7485..9a7aee84a 100644 --- a/plugins/host_kvstore.go +++ b/plugins/host_kvstore.go @@ -54,7 +54,7 @@ func newKVStoreService(ctx context.Context, pluginName string, perm *KVStorePerm } // Create plugin data directory - dataDir := filepath.Join(conf.Server.DataFolder.String(), "plugins", pluginName) + dataDir := filepath.Join(conf.Server().DataFolder.String(), "plugins", pluginName) if err := os.MkdirAll(dataDir, 0700); err != nil { return nil, fmt.Errorf("creating plugin data directory: %w", err) } diff --git a/plugins/host_kvstore_test.go b/plugins/host_kvstore_test.go index 9af3fcbcd..ec795ad88 100644 --- a/plugins/host_kvstore_test.go +++ b/plugins/host_kvstore_test.go @@ -13,7 +13,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" @@ -31,8 +30,7 @@ var _ = Describe("KVStoreService", func() { tmpDir, err = os.MkdirTemp("", "kvstore-test-*") Expect(err).ToNot(HaveOccurred()) - DeferCleanup(configtest.SetupConfig()) - conf.Server.DataFolder = conf.NewDir(tmpDir) + conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) }) // Create service with 1KB limit for testing service, err = newKVStoreService(ctx, "test_plugin", &KVStorePermission{MaxSize: new("1KB")}) @@ -698,11 +696,13 @@ var _ = Describe("KVStoreService Integration", Ordered, func() { hashHex := hex.EncodeToString(hash[:]) // Setup config - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false - conf.Server.DataFolder = conf.NewDir(tmpDir) + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + c.DataFolder = conf.NewDir(tmpDir) + }) // Setup mock DataStore with pre-enabled plugin mockPluginRepo := tests.CreateMockPluginRepo() diff --git a/plugins/host_library_test.go b/plugins/host_library_test.go index edd4b546f..8ff834382 100644 --- a/plugins/host_library_test.go +++ b/plugins/host_library_test.go @@ -11,7 +11,6 @@ import ( "path/filepath" "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,7 @@ var _ = Describe("LibraryService", Ordered, func() { ) BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) + DeferCleanup(conf.SnapshotConfig()) ctx = context.Background() ds = &tests.MockDataStore{} }) @@ -244,9 +243,11 @@ var _ = Describe("LibraryService", Ordered, func() { // Note: Since we don't have WASM test plugins yet, we can test // the service registration and configuration without full plugin execution - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + }) // Create mock &tests.MockLibraryRepo{} mockLibRepo := &tests.MockLibraryRepo{} @@ -338,10 +339,12 @@ var _ = Describe("LibraryService Integration", Ordered, func() { hashHex := hex.EncodeToString(hash[:]) // Setup config - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + }) // Setup mock DataStore with pre-enabled plugin and library mockPluginRepo := tests.CreateMockPluginRepo() diff --git a/plugins/host_matcher_test.go b/plugins/host_matcher_test.go index 7d3e47fae..e44175c87 100644 --- a/plugins/host_matcher_test.go +++ b/plugins/host_matcher_test.go @@ -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/model/request" "github.com/navidrome/navidrome/plugins/host" @@ -24,7 +23,7 @@ import ( var _ = Describe("MatcherService", Ordered, func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) + DeferCleanup(conf.SnapshotConfig()) }) // newConverter returns the service as its concrete type so converter unit @@ -372,10 +371,12 @@ var _ = Describe("MatcherService Integration", Ordered, func() { hash := sha256.Sum256(data) hashHex := hex.EncodeToString(hash[:]) - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + }) mockPluginRepo := tests.CreateMockPluginRepo() mockPluginRepo.Permitted = true diff --git a/plugins/host_scheduler_test.go b/plugins/host_scheduler_test.go index 6940d8820..4c68caba4 100644 --- a/plugins/host_scheduler_test.go +++ b/plugins/host_scheduler_test.go @@ -11,7 +11,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/scheduler" "github.com/navidrome/navidrome/tests" @@ -47,10 +46,12 @@ var _ = Describe("SchedulerService", Ordered, func() { hashHex := hex.EncodeToString(hash[:]) // Setup config - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + }) // Create mock scheduler and timer registry mockSched = newMockScheduler() diff --git a/plugins/host_scrobbleretriever_test.go b/plugins/host_scrobbleretriever_test.go index 6721c1487..443443d86 100644 --- a/plugins/host_scrobbleretriever_test.go +++ b/plugins/host_scrobbleretriever_test.go @@ -11,7 +11,6 @@ import ( extism "github.com/extism/go-sdk" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -53,7 +52,7 @@ var _ = Describe("Scrobble Retriever Host Function", Ordered, func() { tmpDir, err = os.MkdirTemp("", "scrobble-retriever-test-*") Expect(err).ToNot(HaveOccurred()) - conf.Server.DbPath = filepath.Join(tmpDir, "test-scanner.db?_journal_mode=WAL") + conf.Update(func(c *conf.Options) { c.DbPath = filepath.Join(tmpDir, "test-scanner.db?_journal_mode=WAL") }) db.Init(ctx) DeferCleanup(func() { @@ -70,10 +69,12 @@ var _ = Describe("Scrobble Retriever Host Function", Ordered, func() { Expect(err).ToNot(HaveOccurred()) // Setup config - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + }) userRepo := dataStore.User() // Add test users diff --git a/plugins/host_storage.go b/plugins/host_storage.go index e2ead7aae..765796e19 100644 --- a/plugins/host_storage.go +++ b/plugins/host_storage.go @@ -15,7 +15,7 @@ const storageMount = "/storage" type storageServiceImpl struct{} func getHostStoragePath(pluginName string) string { - return filepath.Join(conf.Server.DataFolder.String(), "plugins", pluginName, "storage") + return filepath.Join(conf.Server().DataFolder.String(), "plugins", pluginName, "storage") } func newStorageService(pluginName string) (host.StorageService, error) { diff --git a/plugins/host_storage_test.go b/plugins/host_storage_test.go index 9d8df23a0..883fef395 100644 --- a/plugins/host_storage_test.go +++ b/plugins/host_storage_test.go @@ -10,7 +10,6 @@ import ( extism "github.com/extism/go-sdk" "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" @@ -25,8 +24,8 @@ var _ = Describe("utility functions", Ordered, func() { tmpDir, err = os.MkdirTemp("", "storage-test-*") Expect(err).ToNot(HaveOccurred()) - DeferCleanup(configtest.SetupConfig()) - conf.Server.DataFolder = conf.NewDir(tmpDir) + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) }) DeferCleanup(func() { _ = os.RemoveAll(tmpDir) @@ -89,11 +88,13 @@ var _ = Describe("Storage Host Function", Ordered, func() { mockPluginRepo.Permitted = true // Setup config - DeferCleanup(configtest.SetupConfig()) - conf.Server.DataFolder = conf.NewDir(tmpDir) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.DataFolder = conf.NewDir(tmpDir) + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + }) pluginPaths := []string{ID, ID + "-2"} plugins := []model.Plugin{} diff --git a/plugins/host_subsonicapi_test.go b/plugins/host_subsonicapi_test.go index 0d9c75ee7..52791145c 100644 --- a/plugins/host_subsonicapi_test.go +++ b/plugins/host_subsonicapi_test.go @@ -11,7 +11,6 @@ import ( "path/filepath" "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" @@ -41,10 +40,12 @@ var _ = Describe("SubsonicAPI Host Function", Ordered, func() { Expect(err).ToNot(HaveOccurred()) // Setup config - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + }) // Setup mock router and data store router = &fakeSubsonicRouter{} diff --git a/plugins/host_taskqueue.go b/plugins/host_taskqueue.go index b15cfaf56..c06f801d6 100644 --- a/plugins/host_taskqueue.go +++ b/plugins/host_taskqueue.go @@ -84,7 +84,7 @@ type taskQueueServiceImpl struct { // newTaskQueueService creates a new taskQueueServiceImpl with its own SQLite database. // The given ctx bounds the service's background work (queue workers, cleanup loop). func newTaskQueueService(ctx context.Context, pluginName string, manager *Manager, maxConcurrency int32) (*taskQueueServiceImpl, error) { - dataDir := filepath.Join(conf.Server.DataFolder.String(), "plugins", pluginName) + dataDir := filepath.Join(conf.Server().DataFolder.String(), "plugins", pluginName) if err := os.MkdirAll(dataDir, 0700); err != nil { return nil, fmt.Errorf("creating plugin data directory: %w", err) } diff --git a/plugins/host_taskqueue_test.go b/plugins/host_taskqueue_test.go index 993ddc7f6..849eed13b 100644 --- a/plugins/host_taskqueue_test.go +++ b/plugins/host_taskqueue_test.go @@ -17,7 +17,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/plugins/host" "github.com/navidrome/navidrome/tests" @@ -37,8 +36,7 @@ var _ = Describe("TaskQueueService", func() { tmpDir, err = os.MkdirTemp("", "taskqueue-test-*") Expect(err).ToNot(HaveOccurred()) - DeferCleanup(configtest.SetupConfig()) - conf.Server.DataFolder = conf.NewDir(tmpDir) + conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) }) manager = &Manager{ plugins: make(map[string]*plugin), @@ -840,12 +838,14 @@ var _ = Describe("TaskQueueService Integration", Ordered, func() { hashHex := hex.EncodeToString(hash[:]) // Setup config - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false - conf.Server.CacheFolder = conf.NewDir(filepath.Join(tmpDir, "cache")) - conf.Server.DataFolder = conf.NewDir(tmpDir) + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + c.CacheFolder = conf.NewDir(filepath.Join(tmpDir, "cache")) + c.DataFolder = conf.NewDir(tmpDir) + }) // Setup mock DataStore with pre-enabled plugin mockPluginRepo := tests.CreateMockPluginRepo() diff --git a/plugins/host_users_test.go b/plugins/host_users_test.go index 56edd9f67..855362bfb 100644 --- a/plugins/host_users_test.go +++ b/plugins/host_users_test.go @@ -11,7 +11,6 @@ import ( "path/filepath" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/plugins/host" "github.com/navidrome/navidrome/tests" @@ -481,9 +480,11 @@ func createTestUsers(ctx context.Context, mockUserRepo *tests.MockedUserRepo) { // setupTestUsersConfig sets up common plugin configuration func setupTestUsersConfig(tmpDir string) { - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + }) } // testUsersInput represents input for test-users plugin calls @@ -544,7 +545,7 @@ func setupUsersIntegrationManagerWithEnabled(enabled, allUsers bool, allowedUser Expect(err).ToNot(HaveOccurred()) // Setup config - cleanupConfig := configtest.SetupConfig() + cleanupConfig := conf.SnapshotConfig() setupTestUsersConfig(setup.tmpDir) // Setup mock DataStore with plugin and users diff --git a/plugins/host_websocket_test.go b/plugins/host_websocket_test.go index 9b94e4b70..88cefcb1e 100644 --- a/plugins/host_websocket_test.go +++ b/plugins/host_websocket_test.go @@ -16,7 +16,6 @@ import ( "github.com/gorilla/websocket" "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" @@ -48,10 +47,12 @@ var _ = Describe("WebSocketService", Ordered, func() { hashHex := hex.EncodeToString(hash[:]) // Setup config - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + }) // Setup mock DataStore with pre-enabled plugin mockPluginRepo := tests.CreateMockPluginRepo() diff --git a/plugins/manager.go b/plugins/manager.go index 90247a75c..e7f7c2f6c 100644 --- a/plugins/manager.go +++ b/plugins/manager.go @@ -107,7 +107,7 @@ func (m *Manager) SetSubsonicRouter(router SubsonicRouter) { // 1. Sync plugins folder with DB (discover new, update changed, remove deleted) // 2. Load only enabled plugins from DB func (m *Manager) Start(ctx context.Context) error { - if !conf.Server.Plugins.Enabled { + if !conf.Server().Plugins.Enabled { log.Debug(ctx, "Plugin system is disabled") return nil } @@ -116,19 +116,19 @@ func (m *Manager) Start(ctx context.Context) error { log.Fatal(ctx, "Plugin manager requires the SubsonicAPI router to be configured") } - cacheDir := filepath.Join(conf.Server.CacheFolder.MustPath(), "plugins") - purgeCacheBySize(ctx, cacheDir, conf.Server.Plugins.CacheSize) + cacheDir := filepath.Join(conf.Server().CacheFolder.MustPath(), "plugins") + purgeCacheBySize(ctx, cacheDir, conf.Server().Plugins.CacheSize) if err := m.initRuntime(ctx, cacheDir); err != nil { return err } - if conf.Server.Plugins.Folder.String() == "" { + if conf.Server().Plugins.Folder.String() == "" { log.Debug(ctx, "No plugins folder configured") return nil } - folder := conf.Server.Plugins.Folder.MustPath() + folder := conf.Server().Plugins.Folder.MustPath() log.Info(ctx, "Starting plugin manager", "folder", folder) @@ -151,7 +151,7 @@ func (m *Manager) Start(ctx context.Context) error { } // Start file watcher if auto-reload is enabled - if conf.Server.Plugins.AutoReload { + if conf.Server().Plugins.AutoReload { if err := m.startWatcher(); err != nil { log.Error(ctx, "Failed to start plugin file watcher", err) // Non-fatal - plugins are still loaded, just no auto-reload @@ -163,9 +163,9 @@ func (m *Manager) Start(ctx context.Context) error { // initRuntime prepares the extism/wazero runtime that instantiating a plugin needs. func (m *Manager) initRuntime(ctx context.Context, cacheDir string) error { - pluginLogLevel := conf.Server.Plugins.LogLevel + pluginLogLevel := conf.Server().Plugins.LogLevel if pluginLogLevel == "" { - pluginLogLevel = conf.Server.LogLevel + pluginLogLevel = conf.Server().LogLevel } extism.SetLogLevel(toExtismLogLevel(log.ParseLogLevel(pluginLogLevel))) @@ -189,12 +189,12 @@ type transientLoad struct { // LoadPlugins loads the plugins named in only, so a CLI sees the agents a server would. Each is // instantiated, creating any KVStore, TaskQueue or Storage it declares; call Stop when done. func (m *Manager) LoadPlugins(ctx context.Context, only []string, runInit bool) error { - if !conf.Server.Plugins.Enabled || conf.Server.Plugins.Folder.String() == "" || len(only) == 0 { + if !conf.Server().Plugins.Enabled || conf.Server().Plugins.Folder.String() == "" || len(only) == 0 { return nil } m.transient = &transientLoad{only: only, runInit: runInit} - cacheDir := filepath.Join(conf.Server.CacheFolder.MustPath(), "plugins") + cacheDir := filepath.Join(conf.Server().CacheFolder.MustPath(), "plugins") if err := m.initRuntime(ctx, cacheDir); err != nil { return err } @@ -458,7 +458,7 @@ func (m *Manager) UpdatePluginLibraries(ctx context.Context, id, librariesJSON s // This synchronizes the database with the filesystem, discovering new plugins, // updating changed ones, and removing deleted ones. func (m *Manager) RescanPlugins(ctx context.Context) error { - folder := conf.Server.Plugins.Folder.String() + folder := conf.Server().Plugins.Folder.String() if folder == "" { return fmt.Errorf("plugins folder not configured") } diff --git a/plugins/manager_loader_load_test.go b/plugins/manager_loader_load_test.go index eb004276e..0ce07ec88 100644 --- a/plugins/manager_loader_load_test.go +++ b/plugins/manager_loader_load_test.go @@ -8,7 +8,6 @@ import ( "path/filepath" "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" @@ -30,11 +29,12 @@ var _ = Describe("loadPluginWithConfig", func() { Expect(os.WriteFile(dest, data, 0600)).To(Succeed()) hash := sha256.Sum256(data) - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(pluginsDir) - conf.Server.Plugins.AutoReload = false - conf.Server.DataFolder = conf.NewDir(dataDir) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(pluginsDir) + c.Plugins.AutoReload = false + c.DataFolder = conf.NewDir(dataDir) + }) repo := tests.CreateMockPluginRepo() repo.Permitted = true diff --git a/plugins/manager_readonly_test.go b/plugins/manager_readonly_test.go index 0c88459c0..24d0e6339 100644 --- a/plugins/manager_readonly_test.go +++ b/plugins/manager_readonly_test.go @@ -6,7 +6,6 @@ import ( "path/filepath" "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" @@ -28,16 +27,17 @@ var _ = Describe("Manager.LoadPlugins", func() { // newManager builds a manager over rows the caller can corrupt, with no Subsonic router: a CLI // has none, and Start would log.Fatal on that. newManager := func(rows model.Plugins) *Manager { - DeferCleanup(configtest.SetupConfig()) var err error tmpDir, err = os.MkdirTemp("", "plugins-readonly-*") Expect(err).ToNot(HaveOccurred()) DeferCleanup(func() { _ = os.RemoveAll(tmpDir) }) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false - conf.Server.CacheFolder = conf.NewDir(tmpDir) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + c.CacheFolder = conf.NewDir(tmpDir) + }) if rows == nil { rows = installTestPlugins(tmpDir, "test-metadata-agent"+PackageExtension) @@ -120,7 +120,7 @@ var _ = Describe("Manager.LoadPlugins", func() { It("does nothing when the plugin system is disabled", func() { mgr = newManager(nil) - conf.Server.Plugins.Enabled = false + conf.Update(func(c *conf.Options) { c.Plugins.Enabled = false }) Expect(mgr.LoadPlugins(ctx, []string{"test-metadata-agent", "broken"}, false)).To(Succeed()) diff --git a/plugins/manager_watcher.go b/plugins/manager_watcher.go index ce9e25a9d..b5e7eba04 100644 --- a/plugins/manager_watcher.go +++ b/plugins/manager_watcher.go @@ -19,7 +19,7 @@ const debounceDuration = 2 * time.Second // startWatcher starts the file watcher for the plugins folder. // It watches for CREATE, WRITE, and REMOVE events on .wasm files. func (m *Manager) startWatcher() error { - folder := conf.Server.Plugins.Folder.String() + folder := conf.Server().Plugins.Folder.String() if folder == "" { return nil } @@ -150,7 +150,7 @@ func (m *Manager) processPluginEvent(pluginName string) { delete(m.debounceTimers, pluginName) m.debounceMu.Unlock() - folder := conf.Server.Plugins.Folder.String() + folder := conf.Server().Plugins.Folder.String() ndpPath := filepath.Join(folder, pluginName+PackageExtension) action := determinePluginAction(ndpPath) diff --git a/plugins/manager_watcher_test.go b/plugins/manager_watcher_test.go index 17d9489dc..c9b9f1ca7 100644 --- a/plugins/manager_watcher_test.go +++ b/plugins/manager_watcher_test.go @@ -130,7 +130,7 @@ var _ = Describe("Plugin Watcher", func() { It("starts file watcher when AutoReload is enabled", func() { _ = manager.Stop() - conf.Server.Plugins.AutoReload = true + conf.Update(func(c *conf.Options) { c.Plugins.AutoReload = true }) // Set up a mock DataStore for the auto-reload manager mockPluginRepo := tests.CreateMockPluginRepo() diff --git a/plugins/plugins_suite_test.go b/plugins/plugins_suite_test.go index aa07eae32..5bd31807f 100644 --- a/plugins/plugins_suite_test.go +++ b/plugins/plugins_suite_test.go @@ -36,16 +36,20 @@ var ( func TestPlugins(t *testing.T) { tests.Init(t, false) - // Set globally so tests using configtest.SetupConfig inherit it. The cache + // Set globally so every spec's config snapshot inherits it. The cache // persists between runs; entries are content-addressed, so a stale one only misses. - conf.Server.CacheFolder = conf.NewDir(filepath.Join(testDataDir, wazeroCacheDir)) - conf.Server.Plugins.CacheSize = "1GB" // the default evicts the cache mid-run + conf.Update(func(c *conf.Options) { + c.CacheFolder = conf.NewDir(filepath.Join(testDataDir, wazeroCacheDir)) + c.Plugins.CacheSize = "1GB" + }) // the default evicts the cache mid-run log.SetLevel(log.LevelFatal) RegisterFailHandler(Fail) RunSpecs(t, "Plugins Suite") } +var _ = configtest.RestoreAfterEachSpec() + // stubLocalhostDNS resolves "localhost." without real DNS: the trailing dot never matches /etc/hosts. func stubLocalhostDNS() { dialResolver = tests.StubResolver(map[string]string{"localhost.": "127.0.0.1"}) @@ -106,10 +110,12 @@ func createTestManagerWithPluginsAndMetrics(pluginConfig map[string]map[string]s } // Setup config - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + }) // Setup mock DataStore with pre-enabled plugins mockPluginRepo := tests.CreateMockPluginRepo() diff --git a/plugins/sandbox_fs_test.go b/plugins/sandbox_fs_test.go index 0dd9d15ab..77ecc207d 100644 --- a/plugins/sandbox_fs_test.go +++ b/plugins/sandbox_fs_test.go @@ -8,7 +8,6 @@ import ( "path/filepath" "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" @@ -34,10 +33,12 @@ func startSandboxManager(tmpDir, libraryDir string, grant func(*model.Plugin)) * installed := installTestPlugins(tmpDir, "test-library"+PackageExtension) grant(&installed[0]) - DeferCleanup(configtest.SetupConfig()) - conf.Server.Plugins.Enabled = true - conf.Server.Plugins.Folder = conf.NewDir(tmpDir) - conf.Server.Plugins.AutoReload = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.Plugins.Enabled = true + c.Plugins.Folder = conf.NewDir(tmpDir) + c.Plugins.AutoReload = false + }) mockPluginRepo := tests.CreateMockPluginRepo() mockPluginRepo.Permitted = true diff --git a/resources/embed.go b/resources/embed.go index 040bb5d84..2dd32fba8 100644 --- a/resources/embed.go +++ b/resources/embed.go @@ -16,6 +16,6 @@ var embedFS embed.FS func FS() fs.FS { return merge.FS{ Base: embedFS, - Overlay: os.DirFS(path.Join(conf.Server.DataFolder.String(), "resources")), + Overlay: os.DirFS(path.Join(conf.Server().DataFolder.String(), "resources")), } } diff --git a/scanner/README.md b/scanner/README.md index b2c682381..7d921b2b9 100644 --- a/scanner/README.md +++ b/scanner/README.md @@ -411,7 +411,7 @@ The scanner implements a sophisticated concurrency model to optimize performance 2. **Within-Phase Concurrency**: - Each phase has configurable concurrency for its stages - - For example, `phase_1_folders.go` processes folders concurrently: `ppl.NewStage(p.processFolder, ppl.Name("process folder"), ppl.Concurrency(conf.Server.DevScannerThreads))` + - For example, `phase_1_folders.go` processes folders concurrently: `ppl.NewStage(p.processFolder, ppl.Name("process folder"), ppl.Concurrency(conf.Server().DevScannerThreads))` - Multiple stages can exist within a phase, each with its own concurrency level 3. **Pipeline Architecture Benefits**: diff --git a/scanner/controller.go b/scanner/controller.go index 1b13c1846..e222a7b74 100644 --- a/scanner/controller.go +++ b/scanner/controller.go @@ -36,10 +36,10 @@ func New(rootCtx context.Context, ds model.DataStore, broker events.Broker, broker: broker, pls: pls, metrics: m, - devExternalScanner: conf.Server.DevExternalScanner, + devExternalScanner: conf.Server().DevExternalScanner, } if !c.devExternalScanner { - c.limiter = new(rate.Sometimes{Interval: conf.Server.DevActivityPanelUpdateRate}) + c.limiter = new(rate.Sometimes{Interval: conf.Server().DevActivityPanelUpdateRate}) } return c } diff --git a/scanner/controller_test.go b/scanner/controller_test.go index 974540e32..25b72c0b5 100644 --- a/scanner/controller_test.go +++ b/scanner/controller_test.go @@ -4,7 +4,6 @@ import ( "context" "time" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core/metrics" @@ -29,7 +28,6 @@ var _ = Describe("Controller", func() { ctx = context.Background() db.Init(ctx) DeferCleanup(func() { Expect(tests.ClearDB()).To(Succeed()) }) - DeferCleanup(configtest.SetupConfig()) ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} ds.MockedProperty = &tests.MockedPropertyRepo{} ctrl = scanner.New(ctx, ds, events.NoopBroker(), playlists.NewPlaylists(ds, artwork.NewUploader(ds)), metrics.NewNoopInstance()) diff --git a/scanner/external.go b/scanner/external.go index 7f573fe3e..dd546c611 100644 --- a/scanner/external.go +++ b/scanner/external.go @@ -44,9 +44,9 @@ func (s *scannerExternal) scan(ctx context.Context, fullScan bool, targets []mod args := []string{ "scan", "--nobanner", "--subprocess", - "--configfile", conf.Server.ConfigFile, - "--datafolder", conf.Server.DataFolder.String(), - "--cachefolder", conf.Server.CacheFolder.String(), + "--configfile", conf.Server().ConfigFile, + "--datafolder", conf.Server().DataFolder.String(), + "--cachefolder", conf.Server().CacheFolder.String(), } // Add targets if provided diff --git a/scanner/folder_entry_test.go b/scanner/folder_entry_test.go index 4493f9309..e3773d216 100644 --- a/scanner/folder_entry_test.go +++ b/scanner/folder_entry_test.go @@ -5,7 +5,6 @@ import ( "time" "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" @@ -19,7 +18,6 @@ var _ = Describe("folder_entry", func() { ) BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) lib = model.Library{ ID: 500, Path: "/music", @@ -171,9 +169,7 @@ var _ = Describe("folder_entry", func() { It("sets NumPlaylists when folder is in playlists path", func() { // Mock InPlaylistsPath to return true by setting empty PlaylistsPath - originalPath := conf.Server.PlaylistsPath - conf.Server.PlaylistsPath = "" - DeferCleanup(func() { conf.Server.PlaylistsPath = originalPath }) + conf.Update(func(c *conf.Options) { c.PlaylistsPath = "" }) folder := entry.toFolder() Expect(folder.NumPlaylists).To(Equal(3)) @@ -181,9 +177,7 @@ var _ = Describe("folder_entry", func() { It("does not set NumPlaylists when folder is not in playlists path", func() { // Mock InPlaylistsPath to return false by setting a different path - originalPath := conf.Server.PlaylistsPath - conf.Server.PlaylistsPath = "different/path" - DeferCleanup(func() { conf.Server.PlaylistsPath = originalPath }) + conf.Update(func(c *conf.Options) { c.PlaylistsPath = "different/path" }) folder := entry.toFolder() Expect(folder.NumPlaylists).To(BeZero()) diff --git a/scanner/phase_1_folders.go b/scanner/phase_1_folders.go index 4edaecacd..e056c7e17 100644 --- a/scanner/phase_1_folders.go +++ b/scanner/phase_1_folders.go @@ -214,7 +214,7 @@ func (p *phaseFolders) measure(entry *folderEntry) func() time.Duration { func (p *phaseFolders) stages() []ppl.Stage[*folderEntry] { return []ppl.Stage[*folderEntry]{ - ppl.NewStage(p.processFolder, ppl.Name("process folder"), ppl.Concurrency(conf.Server.DevScannerThreads)), + ppl.NewStage(p.processFolder, ppl.Name("process folder"), ppl.Concurrency(conf.Server().DevScannerThreads)), // persistChanges is not reentrant, so it always has to run with concurrency=1 ppl.NewStage(p.persistChanges, ppl.Name("persist changes"), ppl.Concurrency(1)), ppl.NewStage(p.logFolder, ppl.Name("log results")), diff --git a/scanner/phase_2_missing_tracks.go b/scanner/phase_2_missing_tracks.go index 945257e47..afc8b2bed 100644 --- a/scanner/phase_2_missing_tracks.go +++ b/scanner/phase_2_missing_tracks.go @@ -347,7 +347,7 @@ func (p *phaseMissingTracks) finalize(err error) error { } // Check if we should purge missing items - if conf.Server.Scanner.PurgeMissing == consts.PurgeMissingAlways || (conf.Server.Scanner.PurgeMissing == consts.PurgeMissingFull && p.state.fullScan) { + if conf.Server().Scanner.PurgeMissing == consts.PurgeMissingAlways || (conf.Server().Scanner.PurgeMissing == consts.PurgeMissingFull && p.state.fullScan) { if err = p.purgeMissing(); err != nil { log.Error(p.ctx, "Scanner: Error purging missing items", err) } diff --git a/scanner/phase_2_missing_tracks_test.go b/scanner/phase_2_missing_tracks_test.go index f61aa4244..6ba5dcc68 100644 --- a/scanner/phase_2_missing_tracks_test.go +++ b/scanner/phase_2_missing_tracks_test.go @@ -393,7 +393,7 @@ var _ = Describe("phaseMissingTracks", func() { When("PurgeMissing is 'always'", func() { BeforeEach(func() { - conf.Server.Scanner.PurgeMissing = consts.PurgeMissingAlways + conf.Update(func(c *conf.Options) { c.Scanner.PurgeMissing = consts.PurgeMissingAlways }) mr.SetCountAll(3) mr.DeleteAllMissingValue = 3 }) @@ -407,7 +407,7 @@ var _ = Describe("phaseMissingTracks", func() { When("PurgeMissing is 'full'", func() { BeforeEach(func() { - conf.Server.Scanner.PurgeMissing = consts.PurgeMissingFull + conf.Update(func(c *conf.Options) { c.Scanner.PurgeMissing = consts.PurgeMissingFull }) mr.SetCountAll(2) mr.DeleteAllMissingValue = 2 }) @@ -428,7 +428,7 @@ var _ = Describe("phaseMissingTracks", func() { When("PurgeMissing is 'never'", func() { BeforeEach(func() { - conf.Server.Scanner.PurgeMissing = consts.PurgeMissingNever + conf.Update(func(c *conf.Options) { c.Scanner.PurgeMissing = consts.PurgeMissingNever }) mr.SetCountAll(1) mr.DeleteAllMissingValue = 1 }) diff --git a/scanner/phase_4_playlists.go b/scanner/phase_4_playlists.go index bb67c1ba3..68fab52c7 100644 --- a/scanner/phase_4_playlists.go +++ b/scanner/phase_4_playlists.go @@ -45,7 +45,7 @@ func (p *phasePlaylists) producer() ppl.Producer[*model.Folder] { } func (p *phasePlaylists) produce(put func(entry *model.Folder)) error { - if !conf.Server.AutoImportPlaylists { + if !conf.Server().AutoImportPlaylists { log.Info(p.ctx, "Playlists will not be imported, AutoImportPlaylists is set to false") return nil } diff --git a/scanner/phase_4_playlists_test.go b/scanner/phase_4_playlists_test.go index 303af338f..0cb313000 100644 --- a/scanner/phase_4_playlists_test.go +++ b/scanner/phase_4_playlists_test.go @@ -8,7 +8,6 @@ import ( "sort" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/playlists" "github.com/navidrome/navidrome/model" @@ -32,8 +31,7 @@ var _ = Describe("phasePlaylists", func() { var propRepo *tests.MockedPropertyRepo BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.AutoImportPlaylists = true + conf.Update(func(c *conf.Options) { c.AutoImportPlaylists = true }) ctx = context.Background() folderRepo = &mockFolderRepository{} userRepo = tests.CreateMockUserRepo() diff --git a/scanner/scanner_benchmark_test.go b/scanner/scanner_benchmark_test.go index e6797df36..21ba16e68 100644 --- a/scanner/scanner_benchmark_test.go +++ b/scanner/scanner_benchmark_test.go @@ -44,9 +44,11 @@ func BenchmarkScan(b *testing.B) { tests.Init(b, false) tmpDir := b.TempDir() - conf.Server.DbPath = filepath.Join(tmpDir, "test-scanner.db?_journal_mode=WAL") - // The default library is seeded from MusicFolder, and its path cannot be changed afterwards - conf.Server.MusicFolder = "fake:///music" + conf.Update(func(c *conf.Options) { + c.DbPath = filepath.Join(tmpDir, "test-scanner.db?_journal_mode=WAL") + // The default library is seeded from MusicFolder, and its path cannot be changed afterwards + c.MusicFolder = "fake:///music" + }) // TestScanner may run first and close the shared DB singleton; drop it so db.Init // opens a fresh one whether or not the test suite ran before this benchmark. singleton.DeleteInstance[*sql.DB]() @@ -54,7 +56,7 @@ func BenchmarkScan(b *testing.B) { defer db.Init(context.Background())() ds := persistence.New(db.Db()) - conf.Server.DevExternalScanner = false + conf.Update(func(c *conf.Options) { c.DevExternalScanner = false }) s := scanner.New(context.Background(), ds, events.NoopBroker(), playlists.NewPlaylists(ds, artwork.NewUploader(ds)), metrics.NewNoopInstance()) diff --git a/scanner/scanner_multilibrary_test.go b/scanner/scanner_multilibrary_test.go index f6634c875..0d439879d 100644 --- a/scanner/scanner_multilibrary_test.go +++ b/scanner/scanner_multilibrary_test.go @@ -9,7 +9,6 @@ import ( "github.com/Masterminds/squirrel" "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/core/metrics" @@ -45,15 +44,19 @@ var _ = Describe("Scanner - Multi-Library", Ordered, func() { tests.SkipOnWindows("SQLite file lock blocks TempDir cleanup (#TBD-path-sep-scanner)") ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "123", IsAdmin: true}) tmpDir := GinkgoT().TempDir() - conf.Server.DbPath = filepath.Join(tmpDir, "test-scanner-multilibrary.db?_journal_mode=WAL") - log.Warn("Using DB at " + conf.Server.DbPath) + conf.Update(func(c *conf.Options) { + c.DbPath = filepath.Join(tmpDir, "test-scanner-multilibrary.db?_journal_mode=WAL") + }) + log.Warn("Using DB at " + conf.Server().DbPath) db.Db().SetMaxOpenConns(1) }) BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.MusicFolder = "default:///music" // Use a distinct schema for the default library - conf.Server.DevExternalScanner = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.MusicFolder = "default:///music" // Use a distinct schema for the default library + c.DevExternalScanner = false + }) // Register an empty fake storage for the default library emptyFS := storagetest.FakeFS{} @@ -931,7 +934,7 @@ var _ = Describe("Scanner - Multi-Library", Ordered, func() { changeRockInDB() changeBlueTrainInDB() - conf.Server.PID.Album = "album" + conf.Update(func(c *conf.Options) { c.PID.Album = "album" }) Expect(runScanner(ctx, false)).To(Succeed()) // Rock follows the global config, so it was rescanned in full and its title restored diff --git a/scanner/scanner_selective_test.go b/scanner/scanner_selective_test.go index 2f27b74ce..b3edd6f1a 100644 --- a/scanner/scanner_selective_test.go +++ b/scanner/scanner_selective_test.go @@ -8,7 +8,6 @@ import ( "github.com/Masterminds/squirrel" "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/core/metrics" @@ -38,15 +37,17 @@ var _ = Describe("ScanFolders", Ordered, func() { tests.SkipOnWindows("SQLite file lock blocks TempDir cleanup (#TBD-path-sep-scanner)") ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "123", IsAdmin: true}) tmpDir := GinkgoT().TempDir() - conf.Server.DbPath = filepath.Join(tmpDir, "test-selective-scan.db?_journal_mode=WAL") - log.Warn("Using DB at " + conf.Server.DbPath) + conf.Update(func(c *conf.Options) { c.DbPath = filepath.Join(tmpDir, "test-selective-scan.db?_journal_mode=WAL") }) + log.Warn("Using DB at " + conf.Server().DbPath) db.Db().SetMaxOpenConns(1) }) BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.MusicFolder = "fake:///music" - conf.Server.DevExternalScanner = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.MusicFolder = "fake:///music" + c.DevExternalScanner = false + }) db.Init(ctx) DeferCleanup(func() { diff --git a/scanner/scanner_suite_test.go b/scanner/scanner_suite_test.go index 07ffd6e3a..8ed54283d 100644 --- a/scanner/scanner_suite_test.go +++ b/scanner/scanner_suite_test.go @@ -5,6 +5,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/db" @@ -46,3 +47,5 @@ func TestScanner(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Scanner Suite") } + +var _ = configtest.RestoreAfterEachSpec() diff --git a/scanner/scanner_test.go b/scanner/scanner_test.go index 4ce8cce1e..30dc23c4f 100644 --- a/scanner/scanner_test.go +++ b/scanner/scanner_test.go @@ -15,7 +15,6 @@ import ( "github.com/google/uuid" "github.com/mattn/go-sqlite3" "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/core/metrics" @@ -60,16 +59,18 @@ var _ = Describe("Scanner", Ordered, func() { tmpDir, err := os.MkdirTemp("", "scanner-test") Expect(err).ToNot(HaveOccurred()) DeferCleanup(func() { _ = os.RemoveAll(tmpDir) }) - conf.Server.DbPath = filepath.Join(tmpDir, "test-scanner.db?_journal_mode=WAL") - log.Warn("Using DB at " + conf.Server.DbPath) + conf.Update(func(c *conf.Options) { c.DbPath = filepath.Join(tmpDir, "test-scanner.db?_journal_mode=WAL") }) + log.Warn("Using DB at " + conf.Server().DbPath) //conf.Server.DbPath = ":memory:" db.Db().SetMaxOpenConns(1) }) BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.MusicFolder = "fake:///music" // Set to match test library path - conf.Server.DevExternalScanner = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.MusicFolder = "fake:///music" // Set to match test library path + c.DevExternalScanner = false + }) db.Init(ctx) DeferCleanup(func() { @@ -800,8 +801,8 @@ var _ = Describe("Scanner", Ordered, func() { // its media_file_artists rows, RefreshStats recomputes its stats to '{}', and the cleanup // drops its last library_artist row — leaving the artist row alive but orphaned. RefreshStats // must then mark it missing (see markOrphansMissing). - DeferCleanup(configtest.SetupConfig()) - conf.Server.Scanner.PurgeMissing = consts.PurgeMissingAlways + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { c.Scanner.PurgeMissing = consts.PurgeMissingAlways }) By("Starting from a library where Pink Floyd has its own single album") floyd := template(_t{"artist": "Pink Floyd", "album": "The Wall", "year": 1979}) @@ -900,8 +901,8 @@ var _ = Describe("Scanner", Ordered, func() { Context("When PurgeMissing is configured", func() { When("PurgeMissing is set to 'never'", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Scanner.PurgeMissing = consts.PurgeMissingNever + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { c.Scanner.PurgeMissing = consts.PurgeMissingNever }) }) It("should mark files as missing but not delete them", func() { @@ -929,7 +930,7 @@ var _ = Describe("Scanner", Ordered, func() { When("PurgeMissing is set to 'always'", func() { BeforeEach(func() { - conf.Server.Scanner.PurgeMissing = consts.PurgeMissingAlways + conf.Update(func(c *conf.Options) { c.Scanner.PurgeMissing = consts.PurgeMissingAlways }) }) It("should purge missing files on any scan", func() { @@ -956,7 +957,7 @@ var _ = Describe("Scanner", Ordered, func() { When("PurgeMissing is set to 'full'", func() { BeforeEach(func() { - conf.Server.Scanner.PurgeMissing = consts.PurgeMissingFull + conf.Update(func(c *conf.Options) { c.Scanner.PurgeMissing = consts.PurgeMissingFull }) }) It("should not purge missing files on incremental scans", func() { diff --git a/scanner/walk_dir_tree.go b/scanner/walk_dir_tree.go index d39cad5f6..4ab28d1d2 100644 --- a/scanner/walk_dir_tree.go +++ b/scanner/walk_dir_tree.go @@ -45,7 +45,7 @@ func walkDirTree(ctx context.Context, job *scanJob, targetFolders ...string) (<- // A full walk never descends into symlinked folders when following is disabled, so a // target reached through one (e.g. a watcher event for a new link) is skipped too. - if !conf.Server.Scanner.FollowSymlinks && isSymlinkedPath(job.fs, folderPath) { + if !conf.Server().Scanner.FollowSymlinks && isSymlinkedPath(job.fs, folderPath) { log.Debug(ctx, "Scanner: Skipping symlinked target folder, following is disabled", "path", folderPath) continue } @@ -221,7 +221,7 @@ func isDirOrSymlinkToDir(fsys fs.FS, baseDir string, dirEnt fs.DirEntry) (bool, return false, nil } // If symlinks are disabled, return false for symlinks - if !conf.Server.Scanner.FollowSymlinks { + if !conf.Server().Scanner.FollowSymlinks { return false, nil } // Does this symlink point to a directory? @@ -255,7 +255,7 @@ func resolveEntryName(ctx context.Context, fsys fs.FS, dirPath string, entry fs. return entry.Name(), true } linkPath := path.Join(dirPath, entry.Name()) - if !conf.Server.Scanner.FollowSymlinks { + if !conf.Server().Scanner.FollowSymlinks { log.Trace(ctx, "Scanner: Skipping symlink, following is disabled", "path", linkPath) return "", false } @@ -333,7 +333,7 @@ func isIgnoredEntry(name string, isDir bool) bool { if isDir && isDirIgnored(name) { return true } - return isDotEntry(name) && (!isDir || conf.Server.Scanner.IgnoreDotFolders) + return isDotEntry(name) && (!isDir || conf.Server().Scanner.IgnoreDotFolders) } // isDirIgnored returns true if the directory name is in the explicit ignoredDirs diff --git a/scanner/walk_dir_tree_test.go b/scanner/walk_dir_tree_test.go index 0c2aba3e0..6f1d52bcc 100644 --- a/scanner/walk_dir_tree_test.go +++ b/scanner/walk_dir_tree_test.go @@ -11,7 +11,6 @@ import ( "testing/fstest" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/storage" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/tests" @@ -30,7 +29,6 @@ var _ = Describe("walk_dir_tree", func() { Context("full library", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) ctx = GinkgoT().Context() fsys = &mockMusicFS{ FS: fstest.MapFS{ @@ -82,7 +80,7 @@ var _ = Describe("walk_dir_tree", func() { DescribeTable("symlink handling", func(followSymlinks bool, expectedFolderCount int) { - conf.Server.Scanner.FollowSymlinks = followSymlinks + conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = followSymlinks }) folders := getFolders() Expect(folders).To(HaveLen(expectedFolderCount + 2)) // +2 for `.` and `root` @@ -130,8 +128,10 @@ var _ = Describe("walk_dir_tree", func() { DescribeTable("dot-prefixed folders with IgnoreDotFolders disabled", func(followSymlinks bool) { - conf.Server.Scanner.FollowSymlinks = followSymlinks - conf.Server.Scanner.IgnoreDotFolders = false + conf.Update(func(c *conf.Options) { + c.Scanner.FollowSymlinks = followSymlinks + c.Scanner.IgnoreDotFolders = false + }) folders := getFolders() // Dot-prefixed album folders are now traversed and indexed @@ -154,7 +154,6 @@ var _ = Describe("walk_dir_tree", func() { Context("with target folders", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) ctx = GinkgoT().Context() fsys = &mockMusicFS{ FS: fstest.MapFS{ @@ -285,7 +284,7 @@ var _ = Describe("walk_dir_tree", func() { DescribeTable("with FollowSymlinks disabled", func(target string, expected ...string) { - conf.Server.Scanner.FollowSymlinks = false + conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = false }) Expect(slices.Collect(maps.Keys(walkTargets(target)))).To(ConsistOf(expected)) }, Entry("skips a target that is a symlink", "Wolfgang Amadeus Mozart"), @@ -294,7 +293,7 @@ var _ = Describe("walk_dir_tree", func() { ) It("walks a symlinked target when FollowSymlinks is enabled", func() { - conf.Server.Scanner.FollowSymlinks = true + conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = true }) folders := walkTargets("Wolfgang Amadeus Mozart") Expect(folders).To(HaveKey("Wolfgang Amadeus Mozart/Album1")) Expect(folders["Wolfgang Amadeus Mozart/Album1"].audioFiles).To(HaveKey("track.mp3")) @@ -309,14 +308,11 @@ var _ = Describe("walk_dir_tree", func() { baseDir := filepath.Join("tests", "fixtures") Describe("isDirOrSymlinkToDir", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) Context("with symlinks enabled", func() { BeforeEach(func() { tests.SkipOnWindows("symlink semantics") - conf.Server.Scanner.FollowSymlinks = true + conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = true }) }) DescribeTable("returns expected result", @@ -333,7 +329,7 @@ var _ = Describe("walk_dir_tree", func() { Context("with symlinks disabled", func() { BeforeEach(func() { - conf.Server.Scanner.FollowSymlinks = false + conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = false }) }) DescribeTable("returns expected result", @@ -352,7 +348,6 @@ var _ = Describe("walk_dir_tree", func() { Describe("resolveEntryName", func() { var fsys fs.FS BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) fsys = fstest.MapFS{ "dir/real.mp3": {Data: []byte("AUDIO")}, "dir/mid.mp3": {Mode: fs.ModeSymlink, Data: []byte("real.mp3")}, @@ -378,7 +373,7 @@ var _ = Describe("walk_dir_tree", func() { } Context("with symlinks enabled", func() { - BeforeEach(func() { conf.Server.Scanner.FollowSymlinks = true }) + BeforeEach(func() { conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = true }) }) It("returns the entry name for a plain file", func() { name, ok := resolve("real.mp3") @@ -407,7 +402,7 @@ var _ = Describe("walk_dir_tree", func() { }) Context("with symlinks disabled", func() { - BeforeEach(func() { conf.Server.Scanner.FollowSymlinks = false }) + BeforeEach(func() { conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = false }) }) It("returns the entry name for a plain file", func() { name, ok := resolve("real.mp3") @@ -424,7 +419,6 @@ var _ = Describe("walk_dir_tree", func() { Describe("symlink chain (real fs)", func() { BeforeEach(func() { tests.SkipOnWindows("symlink semantics") - DeferCleanup(configtest.SetupConfig()) }) classify := func(fsys fs.FS, dirPath, name string) (string, bool) { @@ -443,7 +437,7 @@ var _ = Describe("walk_dir_tree", func() { // tests.Init chdirs to the repo root, so the committed fixtures are at "tests/fixtures". var fsys fs.FS BeforeEach(func() { - conf.Server.Scanner.FollowSymlinks = true + conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = true }) wd, err := os.Getwd() Expect(err).ToNot(HaveOccurred()) fsys = os.DirFS(wd) @@ -464,7 +458,7 @@ var _ = Describe("walk_dir_tree", func() { }) It("skips the chain entirely when FollowSymlinks is disabled", func() { - conf.Server.Scanner.FollowSymlinks = false + conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = false }) _, ok := classify(fsys, "tests/fixtures/symlink_chain", "level3.mp3") Expect(ok).To(BeFalse()) _, ok = classify(fsys, "tests/fixtures/symlink_chain", "evil3.mp3") @@ -480,7 +474,7 @@ var _ = Describe("walk_dir_tree", func() { var musicFS storage.MusicFS BeforeEach(func() { - conf.Server.Scanner.FollowSymlinks = true + conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = true }) // Reproduces the reported layout: a "pool" with the real files and a // library containing only symlinks into the pool. @@ -534,7 +528,7 @@ var _ = Describe("walk_dir_tree", func() { }) It("skips all file symlinks when FollowSymlinks is disabled", func() { - conf.Server.Scanner.FollowSymlinks = false + conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = false }) root := walkRoot() Expect(root.audioFiles).To(BeEmpty()) }) @@ -543,7 +537,7 @@ var _ = Describe("walk_dir_tree", func() { Context("out-of-tree escape (temp dir)", func() { var root string BeforeEach(func() { - conf.Server.Scanner.FollowSymlinks = true + conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = true }) root = GinkgoT().TempDir() outside := GinkgoT().TempDir() Expect(os.WriteFile(filepath.Join(outside, "passwd"), []byte("TOPSECRET"), 0600)).To(Succeed()) @@ -571,7 +565,7 @@ var _ = Describe("walk_dir_tree", func() { }) It("skips all file symlinks when FollowSymlinks is disabled", func() { - conf.Server.Scanner.FollowSymlinks = false + conf.Update(func(c *conf.Options) { c.Scanner.FollowSymlinks = false }) fsys := os.DirFS(root) entries, err := fs.ReadDir(fsys, ".") Expect(err).ToNot(HaveOccurred()) @@ -604,13 +598,10 @@ var _ = Describe("walk_dir_tree", func() { }) Describe("isIgnoredEntry", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) DescribeTable("with IgnoreDotFolders enabled (default)", func(name string, isDir, expected bool) { - conf.Server.Scanner.IgnoreDotFolders = true + conf.Update(func(c *conf.Options) { c.Scanner.IgnoreDotFolders = true }) Expect(isIgnoredEntry(name, isDir)).To(Equal(expected)) }, Entry("normal dir", "Album", true, false), @@ -623,7 +614,7 @@ var _ = Describe("walk_dir_tree", func() { DescribeTable("with IgnoreDotFolders disabled", func(name string, isDir, expected bool) { - conf.Server.Scanner.IgnoreDotFolders = false + conf.Update(func(c *conf.Options) { c.Scanner.IgnoreDotFolders = false }) Expect(isIgnoredEntry(name, isDir)).To(Equal(expected)) }, Entry("normal dir", "Album", true, false), diff --git a/scanner/watcher.go b/scanner/watcher.go index 1ac5468f0..78347f1ac 100644 --- a/scanner/watcher.go +++ b/scanner/watcher.go @@ -48,7 +48,7 @@ func GetWatcher(ds model.DataStore, s model.Scanner) Watcher { return &watcher{ ds: ds, scanner: s, - triggerWait: conf.Server.Scanner.WatcherWait, + triggerWait: conf.Server().Scanner.WatcherWait, watcherNotify: make(chan scanNotification, 500), libraryWatchers: make(map[int]*libraryWatcherInstance), } @@ -101,7 +101,7 @@ func (w *watcher) Run(ctx context.Context) error { go func() { var err error - if conf.Server.DevSelectiveWatcher { + if conf.Server().DevSelectiveWatcher { _, err = w.scanner.ScanFolders(ctx, false, targetSlice) } else { _, err = w.scanner.ScanAll(ctx, false) diff --git a/scanner/watcher_test.go b/scanner/watcher_test.go index 12c94602c..fa6b26980 100644 --- a/scanner/watcher_test.go +++ b/scanner/watcher_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/storage/storagetest" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/tests" @@ -25,16 +24,14 @@ var _ = Describe("Watcher", func() { var lib *model.Library BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) // Must dwarf the 20ms Consistently windows below, or a loaded runner's delayed timer reset flakes the debouncing spec. - conf.Server.Scanner.WatcherWait = 200 * time.Millisecond + conf.Update(func(c *conf.Options) { c.Scanner.WatcherWait = 200 * time.Millisecond }) ctx, cancel = context.WithCancel(GinkgoT().Context()) DeferCleanup(cancel) // Use a fake storage scheme: watchLibrary goroutines spawned by Run/Watch are not - // joined on spec teardown, and the real file:// storage reads conf.Server on - // construction, racing with the configtest cleanup that restores the config. + // joined on spec teardown. storagetest.Register("fake-watcher", &storagetest.FakeFS{}) lib = &model.Library{ ID: 1, @@ -53,7 +50,7 @@ var _ = Describe("Watcher", func() { w = &watcher{ ds: mockDS, scanner: mockScanner, - triggerWait: conf.Server.Scanner.WatcherWait, + triggerWait: conf.Server().Scanner.WatcherWait, watcherNotify: make(chan scanNotification, 10), libraryWatchers: make(map[int]*libraryWatcherInstance), mainCtx: ctx, @@ -439,13 +436,10 @@ var _ = Describe("Watcher", func() { }) var _ = Describe("isIgnoredPath", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) Context("with IgnoreDotFolders enabled (default)", func() { BeforeEach(func() { - conf.Server.Scanner.IgnoreDotFolders = true + conf.Update(func(c *conf.Options) { c.Scanner.IgnoreDotFolders = true }) }) DescribeTable("returns expected result", @@ -465,7 +459,7 @@ var _ = Describe("isIgnoredPath", func() { Context("with IgnoreDotFolders disabled", func() { BeforeEach(func() { - conf.Server.Scanner.IgnoreDotFolders = false + conf.Update(func(c *conf.Options) { c.Scanner.IgnoreDotFolders = false }) }) DescribeTable("returns expected result", diff --git a/server/apiv1/apiv1_suite_test.go b/server/apiv1/apiv1_suite_test.go index 00b26abc4..87ad5cc18 100644 --- a/server/apiv1/apiv1_suite_test.go +++ b/server/apiv1/apiv1_suite_test.go @@ -35,12 +35,15 @@ func TestAPIv1(t *testing.T) { RunSpecs(t, "API v1 Suite") } +var _ = configtest.RestoreAfterEachSpec() + var specRouter routers.Router // One database for the suite (db.Db() is a process-wide singleton); each spec clears users and grants. var _ = BeforeSuite(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DbPath = filepath.Join(GinkgoT().TempDir(), "apiv1.db") + "?_journal_mode=WAL&_foreign_keys=on&_busy_timeout=5000" + conf.Update(func(c *conf.Options) { + c.DbPath = filepath.Join(GinkgoT().TempDir(), "apiv1.db") + "?_journal_mode=WAL&_foreign_keys=on&_busy_timeout=5000" + }) DeferCleanup(db.Init(GinkgoT().Context())) realDS = persistence.New(db.Db()) diff --git a/server/apiv1/spec.go b/server/apiv1/spec.go index bdca19693..244160d66 100644 --- a/server/apiv1/spec.go +++ b/server/apiv1/spec.go @@ -32,7 +32,7 @@ func specHandler(body []byte, contentType string) http.HandlerFunc { // withBasePath adds BasePath to the advertised server URL, since only the running server knows it. func withBasePath(body []byte, key string, quotedInBundle bool) []byte { - serverURL := path.Join(conf.Server.BasePath, consts.URLPathAPIv1) + serverURL := path.Join(conf.Server().BasePath, consts.URLPathAPIv1) if serverURL == consts.URLPathAPIv1 { return body } diff --git a/server/apiv1/spec_test.go b/server/apiv1/spec_test.go index a2368f899..a7a2bee45 100644 --- a/server/apiv1/spec_test.go +++ b/server/apiv1/spec_test.go @@ -8,7 +8,6 @@ import ( "github.com/navidrome/navidrome/api" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" @@ -93,8 +92,7 @@ var _ = Describe("OpenAPI document routes", func() { BeforeEach(func() { plainETag = get("/api/v1/openapi.json", nil).Header().Get("ETag") - DeferCleanup(configtest.SetupConfig()) - conf.Server.BasePath = "/music" + conf.Update(func(c *conf.Options) { c.BasePath = "/music" }) router = New(&tests.MockDataStore{}) }) @@ -119,7 +117,7 @@ var _ = Describe("OpenAPI document routes", func() { }) It("escapes base paths that need quoting", func() { - conf.Server.BasePath = "/my music: \"live\"" + conf.Update(func(c *conf.Options) { c.BasePath = "/my music: \"live\"" }) router = New(&tests.MockDataStore{}) Expect(serverURL(decode("json", get("/api/v1/openapi.json", nil).Body.Bytes()))).To(Equal("/my music: \"live\"/api/v1")) Expect(serverURL(decode("yaml", get("/api/v1/openapi.yaml", nil).Body.Bytes()))).To(Equal("/my music: \"live\"/api/v1")) diff --git a/server/auth.go b/server/auth.go index e772c1da2..bf71c8351 100644 --- a/server/auth.go +++ b/server/auth.go @@ -74,7 +74,7 @@ func buildAuthPayload(user *model.User) map[string]any { "username": user.UserName, "isAdmin": user.IsAdmin, } - if conf.Server.EnableGravatar && user.Email != "" { + if conf.Server().EnableGravatar && user.Email != "" { payload["avatar"] = gravatar.Url(user.Email, 50) } @@ -182,7 +182,7 @@ func UsernameFromToken(r *http.Request) string { } func UsernameFromExtAuthHeader(r *http.Request) string { - if conf.Server.ExtAuth.TrustedSources == "" { + if conf.Server().ExtAuth.TrustedSources == "" { return "" } reverseProxyIp, ok := request.ReverseProxyIpFrom(r.Context()) @@ -190,11 +190,11 @@ func UsernameFromExtAuthHeader(r *http.Request) string { log.Error("ExtAuth enabled but no proxy IP found in request context. Please report this error.") return "" } - username := r.Header.Get(conf.Server.ExtAuth.UserHeader) + username := r.Header.Get(conf.Server().ExtAuth.UserHeader) if username == "" { return "" } - if !validateIPAgainstList(reverseProxyIp, conf.Server.ExtAuth.TrustedSources) { + if !validateIPAgainstList(reverseProxyIp, conf.Server().ExtAuth.TrustedSources) { log.Warn(r.Context(), "IP is not whitelisted for external authentication", "proxy-ip", reverseProxyIp, "client-ip", r.RemoteAddr) return "" } @@ -212,7 +212,7 @@ func InternalAuth(r *http.Request) string { } func UsernameFromConfig(*http.Request) string { - return conf.Server.DevAutoLoginUsername + return conf.Server().DevAutoLoginUsername } func contextWithUser(ctx context.Context, ds model.DataStore, username string) (context.Context, error) { @@ -396,7 +396,7 @@ func validateIPAgainstList(ip string, comaSeparatedList string) bool { // Per https://github.com/golang/go/issues/49825, the remote address // on a unix socket is '@' - if ip == "@" && strings.HasPrefix(conf.Server.Address, "unix:") { + if ip == "@" && strings.HasPrefix(conf.Server().Address, "unix:") { return slices.Contains(cidrs, "@") } diff --git a/server/auth_test.go b/server/auth_test.go index b7db3a881..33b660d9f 100644 --- a/server/auth_test.go +++ b/server/auth_test.go @@ -13,7 +13,6 @@ 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" @@ -123,8 +122,10 @@ var _ = Describe("Auth", func() { req = httptest.NewRequest("GET", "/index.html", nil) req.Header.Add("Remote-User", "janedoe") resp = httptest.NewRecorder() - conf.Server.UILoginBackgroundURL = "" - conf.Server.ExtAuth.TrustedSources = "192.168.0.0/16,2001:4860:4860::/48" + conf.Update(func(c *conf.Options) { + c.UILoginBackgroundURL = "" + c.ExtAuth.TrustedSources = "192.168.0.0/16,2001:4860:4860::/48" + }) }) It("sets auth data if IPv4 matches whitelist", func() { @@ -198,8 +199,10 @@ var _ = Describe("Auth", func() { }) It("does not set auth data when listening on unix socket without whitelist", func() { - conf.Server.Address = "unix:/tmp/navidrome-test" - conf.Server.ExtAuth.TrustedSources = "" + conf.Update(func(c *conf.Options) { + c.Address = "unix:/tmp/navidrome-test" + c.ExtAuth.TrustedSources = "" + }) // No ReverseProxyIp in request context serveIndex(ds, fs, nil)(resp, req) @@ -209,7 +212,7 @@ var _ = Describe("Auth", func() { }) It("does not set auth data when listening on unix socket with incorrect whitelist", func() { - conf.Server.Address = "unix:/tmp/navidrome-test" + conf.Update(func(c *conf.Options) { c.Address = "unix:/tmp/navidrome-test" }) req = req.WithContext(request.WithReverseProxyIp(req.Context(), "@")) serveIndex(ds, fs, nil)(resp, req) @@ -219,8 +222,10 @@ var _ = Describe("Auth", func() { }) It("sets auth data when listening on unix socket with correct whitelist", func() { - conf.Server.Address = "unix:/tmp/navidrome-test" - conf.Server.ExtAuth.TrustedSources = conf.Server.ExtAuth.TrustedSources + ",@" + conf.Update(func(c *conf.Options) { + c.Address = "unix:/tmp/navidrome-test" + c.ExtAuth.TrustedSources = c.ExtAuth.TrustedSources + ",@" + }) req = req.WithContext(request.WithReverseProxyIp(req.Context(), "@")) serveIndex(ds, fs, nil)(resp, req) @@ -273,7 +278,7 @@ var _ = Describe("Auth", func() { var r *http.Request BeforeEach(func() { - conf.Server.ExtAuth.TrustedSources = "192.168.0.0/16" + conf.Update(func(c *conf.Options) { c.ExtAuth.TrustedSources = "192.168.0.0/16" }) prevLevel := log.CurrentLevel() l, h := test.NewNullLogger() hook = h @@ -403,8 +408,10 @@ var _ = Describe("Auth", func() { ds = &tests.MockDataStore{} req = httptest.NewRequest("GET", "/", nil) req = req.WithContext(request.WithReverseProxyIp(req.Context(), trustedIP)) - conf.Server.ExtAuth.TrustedSources = "192.168.0.0/16" - conf.Server.ExtAuth.UserHeader = "Remote-User" + conf.Update(func(c *conf.Options) { + c.ExtAuth.TrustedSources = "192.168.0.0/16" + c.ExtAuth.UserHeader = "Remote-User" + }) }) It("makes the first user an admin", func() { @@ -449,8 +456,7 @@ var _ = Describe("Auth", func() { var usr *model.User BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.SessionTimeout = time.Hour + conf.Update(func(c *conf.Options) { c.SessionTimeout = time.Hour }) ds = &tests.MockDataStore{} auth.Init(ds) ur := ds.User().(*tests.MockedUserRepo) @@ -489,7 +495,7 @@ var _ = Describe("Auth", func() { }) It("ignores a stray token for someone else when config auto-login resolves the user", func() { - conf.Server.DevAutoLoginUsername = usr.UserName + conf.Update(func(c *conf.Options) { c.DevAutoLoginUsername = usr.UserName }) tokenStr, err := auth.CreateToken(&model.User{UserName: "someone-else"}) Expect(err).ToNot(HaveOccurred()) Expect(serve(tokenStr).Code).To(Equal(http.StatusOK)) @@ -505,9 +511,8 @@ var _ = Describe("Auth", func() { Describe("JWTRefresher", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) // TouchClaims reads this; left at zero every refreshed token is born expired. - conf.Server.SessionTimeout = time.Hour + conf.Update(func(c *conf.Options) { c.SessionTimeout = time.Hour }) auth.Init(&tests.MockDataStore{}) }) diff --git a/server/filter/filters.go b/server/filter/filters.go index 9014bb799..a4ca6f333 100644 --- a/server/filter/filters.go +++ b/server/filter/filters.go @@ -46,9 +46,9 @@ func AlbumsByArtist() Options { return addDefaultFilters(Options{Sort: "artist"}) } -func AlbumsByArtistID(artistId string) Options { +func AlbumsByArtistID(artistId any) Options { roles := []model.Role{model.RoleAlbumArtist} - if conf.Server.Subsonic.ArtistParticipations { + if conf.Server().Subsonic.ArtistParticipations { roles = append(roles, model.RoleArtist) } return addDefaultFilters(Options{ @@ -57,10 +57,9 @@ func AlbumsByArtistID(artistId string) Options { }) } -// AlbumsByContributingArtistID matches albums where the artist performs on a track but is not the -// album artist — Jellyfin's "Featured On". The disjoint complement of AlbumsByArtistID, so an -// artist's own discography never leaks into it. -func AlbumsByContributingArtistID(artistId string) Options { +// AlbumsByContributingArtistID matches albums where the artist (an id or a slice of ids) performs on +// a track but is not the album artist: Jellyfin's "Featured On", the complement of AlbumsByArtistID. +func AlbumsByContributingArtistID(artistId any) Options { return addDefaultFilters(Options{ Sort: "max_year", Filters: And{ @@ -101,7 +100,7 @@ func SongsByAlbum(albumId string) Options { // SongsByArtistID matches media files where the artist participates as album or track artist, in // album order. -func SongsByArtistID(artistId string) Options { +func SongsByArtistID(artistId any) Options { return addDefaultFilters(Options{ Sort: "album", Filters: persistence.ParticipantIDFilter("media_file", artistId, model.RoleArtist, model.RoleAlbumArtist), diff --git a/server/initial_setup.go b/server/initial_setup.go index 462e22e54..8c48c6f44 100644 --- a/server/initial_setup.go +++ b/server/initial_setup.go @@ -27,8 +27,8 @@ func initialSetup(ds model.DataStore) { return nil } log.Info("Running initial setup") - if conf.Server.DevAutoCreateAdminPassword != "" { - if err = createInitialAdminUser(ctx, tx, conf.Server.DevAutoCreateAdminPassword); err != nil { + if conf.Server().DevAutoCreateAdminPassword != "" { + if err = createInitialAdminUser(ctx, tx, conf.Server().DevAutoCreateAdminPassword); err != nil { return err } } @@ -80,17 +80,17 @@ func checkFFmpegInstallation() { } func checkExternalCredentials() { - if conf.Server.EnableExternalServices { - if !conf.Server.LastFM.Enabled { + if conf.Server().EnableExternalServices { + if !conf.Server().LastFM.Enabled { log.Info("Last.fm integration is DISABLED") } else { log.Debug("Last.fm integration is ENABLED") } - if !conf.Server.ListenBrainz.Enabled { + if !conf.Server().ListenBrainz.Enabled { log.Info("ListenBrainz integration is DISABLED") } else { - log.Debug("ListenBrainz integration is ENABLED", "ListenBrainz.BaseURL", conf.Server.ListenBrainz.BaseURL) + log.Debug("ListenBrainz integration is ENABLED", "ListenBrainz.BaseURL", conf.Server().ListenBrainz.BaseURL) } } } diff --git a/server/jellyfin/README.md b/server/jellyfin/README.md index 48e69cb05..2df74a419 100644 --- a/server/jellyfin/README.md +++ b/server/jellyfin/README.md @@ -162,7 +162,9 @@ in Jellyfin; `Likes` and `Dislikes` are not supported, and `IsFolder`, `IsNotFol `IsResumable` have no Navidrome equivalent, so all five are ignored; `SortBy`/`SortOrder` (every recognized key is applied in order, so secondary keys break ties; unrecognized keys are skipped, and `Random` always sorts alone); `StartIndex`/`Limit`; and `Ids` (batch fetch by id). `Recursive=false` with a library `ParentId` -returns direct children only (no tracks — no track is a library's direct child). +returns direct children only (no tracks — no track is a library's direct child). With no `ParentId`, +no `Recursive=true` and none of the filters above, `/Items` lists the user's libraries (the same +views as `UserViews`), as Jellyfin does at the user root. ## Implemented endpoints diff --git a/server/jellyfin/api.go b/server/jellyfin/api.go index b9fd32150..ed3a735b0 100644 --- a/server/jellyfin/api.go +++ b/server/jellyfin/api.go @@ -79,8 +79,8 @@ func (api *Router) routes() http.Handler { // Rate-limit the password login, mirroring the native /auth/login: it's an unauthenticated // brute-force surface, so it must share the same per-client throttle when one is configured. login := inner.With(server.LimitLoginBody) - if conf.Server.AuthRequestLimit > 0 { - login = login.With(server.ClientIPRateLimiter(conf.Server.AuthRequestLimit, conf.Server.AuthWindowLength)) + if conf.Server().AuthRequestLimit > 0 { + login = login.With(server.ClientIPRateLimiter(conf.Server().AuthRequestLimit, conf.Server().AuthWindowLength)) } login.Post("/users/authenticatebyname", api.authenticateByName) quickConnectLogin := login.With(requireQuickConnect) @@ -94,8 +94,8 @@ func (api *Router) routes() http.Handler { // Bound concurrency like Subsonic's getCoverArt: image decode/resize is CPU- and memory-heavy, // and an unbounded burst (a client fetching artwork across a large library) can exhaust memory. inner.Group(func(r chi.Router) { - r.Use(server.ThrottleBacklog(conf.Server.DevArtworkMaxRequests, conf.Server.DevArtworkThrottleBacklogLimit, - conf.Server.DevArtworkThrottleBacklogTimeout)) + r.Use(server.ThrottleBacklog(conf.Server().DevArtworkMaxRequests, conf.Server().DevArtworkThrottleBacklogLimit, + conf.Server().DevArtworkThrottleBacklogTimeout)) r.Get("/items/{itemId}/images/{type}", api.getItemImage) r.Get("/items/{itemId}/images/{type}/{index}", api.getItemImage) r.Head("/items/{itemId}/images/{type}", api.getItemImage) @@ -116,8 +116,8 @@ func (api *Router) routes() http.Handler { r.Get("/users/{userId}", api.getCurrentUser) // Throttled like login so a signed-in user cannot enumerate other people's pending codes. approve := r.With(requireQuickConnect) - if conf.Server.AuthRequestLimit > 0 { - approve = approve.With(server.ClientIPRateLimiter(conf.Server.AuthRequestLimit, conf.Server.AuthWindowLength)) + if conf.Server().AuthRequestLimit > 0 { + approve = approve.With(server.ClientIPRateLimiter(conf.Server().AuthRequestLimit, conf.Server().AuthWindowLength)) } approve.Post("/quickconnect/authorize", api.quickConnectAuthorize) @@ -126,7 +126,7 @@ func (api *Router) routes() http.Handler { // scanner, scrobbles and the UI. Cap them at half the pool (see conf.MaxOpenConns); excess // requests queue rather than fail. r.Group(func(r chi.Router) { - r.Use(throttleStreams(conf.Server.Jellyfin.MaxConcurrentStreams)) + r.Use(throttleStreams(conf.Server().Jellyfin.MaxConcurrentStreams)) r.Get("/items", api.getItems) r.Get("/users/{userId}/items", api.getItems) r.Get("/items/latest", api.getLatest) diff --git a/server/jellyfin/api_test.go b/server/jellyfin/api_test.go index 0c6ac9b98..03abbae9f 100644 --- a/server/jellyfin/api_test.go +++ b/server/jellyfin/api_test.go @@ -9,7 +9,6 @@ import ( "github.com/go-chi/chi/v5/middleware" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/quickconnect" "github.com/navidrome/navidrome/model" @@ -76,9 +75,10 @@ var _ = Describe("Router", func() { }) It("rate-limits AuthenticateByName by IP when a login limit is configured", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.AuthRequestLimit = 2 - conf.Server.AuthWindowLength = time.Minute + conf.Update(func(c *conf.Options) { + c.AuthRequestLimit = 2 + c.AuthWindowLength = time.Minute + }) api := New(&tests.MockDataStore{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) login := func() int { @@ -95,10 +95,11 @@ var _ = Describe("Router", func() { }) It("rate-limits Quick Connect approval by IP when a login limit is configured", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.AuthRequestLimit = 2 - conf.Server.AuthWindowLength = time.Minute - conf.Server.Jellyfin.QuickConnect = true + conf.Update(func(c *conf.Options) { + c.AuthRequestLimit = 2 + c.AuthWindowLength = time.Minute + c.Jellyfin.QuickConnect = true + }) ds := &tests.MockDataStore{} auth.Init(ds) usr := model.User{ID: testID("alice"), UserName: "alice"} @@ -122,9 +123,10 @@ var _ = Describe("Router", func() { }) It("rate-limits AuthenticateByName by resolved client IP, not by the proxy connection", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.AuthRequestLimit = 1 - conf.Server.AuthWindowLength = time.Minute + conf.Update(func(c *conf.Options) { + c.AuthRequestLimit = 1 + c.AuthWindowLength = time.Minute + }) api := New(&tests.MockDataStore{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) // Every request arrives on the same proxy connection, so only the resolved client IP // can separate the buckets. diff --git a/server/jellyfin/browsing.go b/server/jellyfin/browsing.go index baebbf0f3..958d3f980 100644 --- a/server/jellyfin/browsing.go +++ b/server/jellyfin/browsing.go @@ -57,7 +57,8 @@ func (api *Router) listArtistsByRole(w http.ResponseWriter, r *http.Request, rol func (api *Router) getGenres(w http.ResponseWriter, r *http.Request) { ctx := r.Context() p := req.Params(r) - opts := model.QueryOptions{Offset: p.IntOr("startindex", 0), Max: p.IntOr("limit", 0)} + offset, limit := pageParams(p) + opts := model.QueryOptions{Offset: offset, Max: limit} res, err := api.listGenres(ctx, opts) if err != nil { api.internalError(w, r, err) @@ -83,8 +84,8 @@ func (api *Router) getStudios(w http.ResponseWriter, r *http.Request) { return } items := slice.Map(labels, dto.StudioToBaseItem) - offset, max := p.IntOr("startindex", 0), p.IntOr("limit", 0) - api.ok(w, r, result(paginate(items, offset, max), len(items), offset)) + offset, limit := pageParams(p) + api.ok(w, r, result(paginate(items, offset, limit), len(items), offset)) } // getQueryFiltersLegacy handles GET /Items/Filters. Genres and Years are scoped to ParentId's diff --git a/server/jellyfin/browsing_test.go b/server/jellyfin/browsing_test.go index 48a62c4e5..24fad828b 100644 --- a/server/jellyfin/browsing_test.go +++ b/server/jellyfin/browsing_test.go @@ -206,6 +206,16 @@ var _ = Describe("Browsing", func() { invoke(api.getGenres, w, r) Expect(w.Code).To(Equal(http.StatusOK)) }) + + It("treats a negative StartIndex as 0 instead of panicking", func() { + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/Genres?StartIndex=-1&Limit=5", nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) + invoke(api.getGenres, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + var res dto.QueryResult + Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + Expect(res.StartIndex).To(Equal(0)) + }) }) Describe("getStudios", func() { @@ -238,6 +248,16 @@ var _ = Describe("Browsing", func() { invoke(api.getStudios, w, r) Expect(w.Code).To(Equal(http.StatusNotFound)) }) + + It("treats a negative StartIndex as 0 instead of panicking", func() { + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/Studios?StartIndex=-1&Limit=5", nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) + invoke(api.getStudios, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + var res dto.QueryResult + Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + Expect(res.StartIndex).To(Equal(0)) + }) }) Describe("getQueryFiltersLegacy", func() { diff --git a/server/jellyfin/discovery.go b/server/jellyfin/discovery.go index d111287a6..a3d8e436b 100644 --- a/server/jellyfin/discovery.go +++ b/server/jellyfin/discovery.go @@ -87,23 +87,23 @@ func (d *Discovery) ServeOn(ctx context.Context, conn net.PacketConn) { // Behind a unix socket nothing listens on Port, so only a BaseURL host gives clients an address. func hasAdvertisableAddress() bool { - return conf.Server.BaseHost != "" || !strings.HasPrefix(conf.Server.Address, "unix:") + return conf.Server().BaseHost != "" || !strings.HasPrefix(conf.Server().Address, "unix:") } func discoveryAddress(ctx context.Context, remote net.Addr) string { - scheme := gg.If(conf.Server.TLSEnabled(), "https", "http") - host := net.JoinHostPort(localIPFor(remote), strconv.Itoa(conf.Server.Port)) + scheme := gg.If(conf.Server().TLSEnabled(), "https", "http") + host := net.JoinHostPort(localIPFor(remote), strconv.Itoa(conf.Server().Port)) return publicurl.AbsoluteURL(request.WithServerAddress(ctx, scheme, host), consts.URLPathJellyfinAPI, nil) } // On a multi-homed host, only the interface that routes to the requester is reachable by it. func localIPFor(remote net.Addr) string { - if ip := parseIP(conf.Server.Address); ip.IsValid() && !ip.IsUnspecified() { + if ip := parseIP(conf.Server().Address); ip.IsValid() && !ip.IsUnspecified() { return ip.String() } c, err := net.Dial("udp", remote.String()) if err != nil { - return conf.Server.Address + return conf.Server().Address } defer c.Close() return c.LocalAddr().(*net.UDPAddr).IP.String() diff --git a/server/jellyfin/discovery_test.go b/server/jellyfin/discovery_test.go index bcd11fe76..96eb52cac 100644 --- a/server/jellyfin/discovery_test.go +++ b/server/jellyfin/discovery_test.go @@ -9,7 +9,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -32,15 +31,16 @@ var _ = Describe("Discovery", func() { var d *Discovery BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Jellyfin.ServerName = "Test Server" - conf.Server.Address = "0.0.0.0" - conf.Server.Port = 4533 - conf.Server.BaseHost = "" - conf.Server.BaseScheme = "" - conf.Server.BasePath = "" - conf.Server.TLSCert = "" - conf.Server.TLSKey = "" + conf.Update(func(c *conf.Options) { + c.Jellyfin.ServerName = "Test Server" + c.Address = "0.0.0.0" + c.Port = 4533 + c.BaseHost = "" + c.BaseScheme = "" + c.BasePath = "" + c.TLSCert = "" + c.TLSKey = "" + }) d = &Discovery{} }) @@ -51,37 +51,43 @@ var _ = Describe("Discovery", func() { Expect(discoveryAddress(context.Background(), remote)).To(Equal(expected)) }, Entry("uses the BaseURL host and scheme when set", func() { - conf.Server.BaseScheme = "https" - conf.Server.BaseHost = "music.example.com" - conf.Server.BasePath = "/nd" + conf.Update(func(c *conf.Options) { + c.BaseScheme = "https" + c.BaseHost = "music.example.com" + c.BasePath = "/nd" + }) }, "https://music.example.com/nd/jellyfin"), Entry("uses a specific bind Address with the Port", func() { - conf.Server.Address = "192.168.1.10" + conf.Update(func(c *conf.Options) { c.Address = "192.168.1.10" }) }, "http://192.168.1.10:4533/jellyfin"), Entry("falls back to the interface facing the requester when Address is unspecified", func() {}, "http://127.0.0.1:4533/jellyfin"), Entry("falls back to the interface facing the requester when Address is empty", func() { - conf.Server.Address = "" + conf.Update(func(c *conf.Options) { c.Address = "" }) }, "http://127.0.0.1:4533/jellyfin"), Entry("advertises https when TLS is configured", func() { - conf.Server.TLSCert = "/path/cert.pem" - conf.Server.TLSKey = "/path/key.pem" + conf.Update(func(c *conf.Options) { + c.TLSCert = "/path/cert.pem" + c.TLSKey = "/path/key.pem" + }) }, "https://127.0.0.1:4533/jellyfin"), Entry("advertises http when only the TLS cert is configured", func() { - conf.Server.TLSCert = "/path/cert.pem" + conf.Update(func(c *conf.Options) { c.TLSCert = "/path/cert.pem" }) }, "http://127.0.0.1:4533/jellyfin"), Entry("keeps a path-only BaseURL as the path prefix", func() { - conf.Server.BasePath = "/music" + conf.Update(func(c *conf.Options) { c.BasePath = "/music" }) }, "http://127.0.0.1:4533/music/jellyfin"), Entry("does not double the slash when BasePath has a trailing slash", func() { - conf.Server.BasePath = "/music/" + conf.Update(func(c *conf.Options) { c.BasePath = "/music/" }) }, "http://127.0.0.1:4533/music/jellyfin"), ) DescribeTable("hasAdvertisableAddress", func(address, baseHost string, expected bool) { - conf.Server.Address = address - conf.Server.BaseHost = baseHost + conf.Update(func(c *conf.Options) { + c.Address = address + c.BaseHost = baseHost + }) Expect(hasAdvertisableAddress()).To(Equal(expected)) }, Entry("TCP listener", "0.0.0.0", "", true), diff --git a/server/jellyfin/dto/dto_suite_test.go b/server/jellyfin/dto/dto_suite_test.go index a4eebb0d3..4ce43bdab 100644 --- a/server/jellyfin/dto/dto_suite_test.go +++ b/server/jellyfin/dto/dto_suite_test.go @@ -3,6 +3,7 @@ package dto import ( "testing" + "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model/id" "github.com/navidrome/navidrome/tests" @@ -17,6 +18,8 @@ func TestDto(t *testing.T) { RunSpecs(t, "Jellyfin DTO Suite") } +var _ = configtest.RestoreAfterEachSpec() + // testID maps a readable label to a deterministic canonical id, so fixtures exercise the same // id shape production uses. func testID(label string) string { return id.NewHash("jellyfin-test", label) } diff --git a/server/jellyfin/dto/mappers.go b/server/jellyfin/dto/mappers.go index 620df783f..f3d87cab0 100644 --- a/server/jellyfin/dto/mappers.go +++ b/server/jellyfin/dto/mappers.go @@ -15,7 +15,7 @@ import ( // sortName must match the persistence ORDER BY key (see setSortMappings): Finamp's A-Z jump // scans SortName client-side, and any mismatch with the server's sort order scrolls to the top. func sortName(sortTag, orderName, displayName string) string { - if conf.Server.PreferSortTags { + if conf.Server().PreferSortTags { return cmp.Or(sortTag, orderName, displayName) } return cmp.Or(orderName, displayName) @@ -257,7 +257,7 @@ func SongToBaseItem(mf model.MediaFile, fields Fields) BaseItemDto { } func embeddedArtPending(mf model.MediaFile) bool { - return mf.HasCoverArt && conf.Server.EnableMediaFileCoverArt && + return mf.HasCoverArt && conf.Server().EnableMediaFileCoverArt && mf.ImageHash == "" && !mf.ItemImage.ImageAbsent } diff --git a/server/jellyfin/dto/mappers_test.go b/server/jellyfin/dto/mappers_test.go index 3e4ba941f..2373f388e 100644 --- a/server/jellyfin/dto/mappers_test.go +++ b/server/jellyfin/dto/mappers_test.go @@ -5,7 +5,6 @@ import ( "time" "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" @@ -63,10 +62,6 @@ var _ = Describe("mappers", func() { ar := model.Artist{ID: testID("art-1"), Name: "The B-52's", SortArtistName: "B-52's, The", OrderArtistName: "b-52's"} al := model.Album{ID: testID("alb-1"), Name: "The Wall", SortAlbumName: "Wall, The", OrderAlbumName: "wall"} - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) - It("is omitted unless Fields=SortName", func() { Expect(SongToBaseItem(song, nil).SortName).To(BeEmpty()) Expect(ArtistToBaseItem(ar, nil).SortName).To(BeEmpty()) @@ -81,7 +76,7 @@ var _ = Describe("mappers", func() { Context("with PreferSortTags", func() { BeforeEach(func() { - conf.Server.PreferSortTags = true + conf.Update(func(c *conf.Options) { c.PreferSortTags = true }) }) It("prefers the sort tags", func() { @@ -534,8 +529,7 @@ var _ = Describe("mappers", func() { // advertising just the album image would leave that cover unreachable. Describe("unresolved embedded art", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableMediaFileCoverArt = true + conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true }) }) It("advertises the track id so the client triggers the read-through", func() { @@ -568,7 +562,7 @@ var _ = Describe("mappers", func() { }) It("falls back to the album when per-track art is disabled", func() { - conf.Server.EnableMediaFileCoverArt = false + conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false }) mf := model.MediaFile{ID: testID("mf-4"), AlbumID: testID("alb-1"), HasCoverArt: true} mf.AlbumImage.ImageHash = "0123456789abcdef" diff --git a/server/jellyfin/e2e/auth_test.go b/server/jellyfin/e2e/auth_test.go index 35daaf598..94b99c6ab 100644 --- a/server/jellyfin/e2e/auth_test.go +++ b/server/jellyfin/e2e/auth_test.go @@ -5,7 +5,6 @@ import ( "net/http/httptest" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/server/jellyfin/dto" . "github.com/onsi/ginkgo/v2" @@ -110,14 +109,12 @@ var _ = Describe("Authentication", func() { } It("returns an empty list when no users are exposed", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Jellyfin.ExposedPublicUsers = "" + conf.Update(func(c *conf.Options) { c.Jellyfin.ExposedPublicUsers = "" }) Expect(publicUsers()).To(BeEmpty()) }) It("lists the configured users to an unauthenticated caller, without policy", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Jellyfin.ExposedPublicUsers = "regular" + conf.Update(func(c *conf.Options) { c.Jellyfin.ExposedPublicUsers = "regular" }) users := publicUsers() Expect(users).To(HaveLen(1)) Expect(users[0].Name).To(Equal("regular")) diff --git a/server/jellyfin/e2e/e2e_suite_test.go b/server/jellyfin/e2e/e2e_suite_test.go index 4f3cd82b5..08e701876 100644 --- a/server/jellyfin/e2e/e2e_suite_test.go +++ b/server/jellyfin/e2e/e2e_suite_test.go @@ -72,6 +72,8 @@ func TestJellyfinE2E(t *testing.T) { RunSpecs(t, "Jellyfin API E2E Suite") } +var _ = configtest.RestoreAfterEachSpec() + // testID maps a readable label to a deterministic canonical id, so fixtures exercise the same // id shape production uses. func testID(label string) string { return id.NewHash("jellyfin-test", label) } @@ -298,9 +300,11 @@ var _ = BeforeSuite(func() { dataFolder = filepath.Join(GinkgoT().TempDir(), "data") Expect(os.MkdirAll(dataFolder, 0o755)).To(Succeed()) - conf.Server.MusicFolder = "fake:///music" - conf.Server.DataFolder = conf.NewDir(dataFolder) - conf.Server.DevExternalScanner = false + conf.Update(func(c *conf.Options) { + c.MusicFolder = "fake:///music" + c.DataFolder = conf.NewDir(dataFolder) + c.DevExternalScanner = false + }) buildTestFS() goldenDB = harness.SetupDB(ctx, &adminUser, ®ularUser) @@ -316,11 +320,13 @@ var _ = AfterSuite(func() { func setupTestDB() { ctx = request.WithUser(GinkgoT().Context(), adminUser) - DeferCleanup(configtest.SetupConfig()) - conf.Server.MusicFolder = "fake:///music" - conf.Server.DataFolder = conf.NewDir(dataFolder) - conf.Server.DevExternalScanner = false - conf.Server.DevEnableMediaFileProbe = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.MusicFolder = "fake:///music" + c.DataFolder = conf.NewDir(dataFolder) + c.DevExternalScanner = false + c.DevEnableMediaFileProbe = false + }) goldenDB.Restore() diff --git a/server/jellyfin/e2e/quickconnect_test.go b/server/jellyfin/e2e/quickconnect_test.go index 1beffc56f..1b9618d61 100644 --- a/server/jellyfin/e2e/quickconnect_test.go +++ b/server/jellyfin/e2e/quickconnect_test.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/server/jellyfin/dto" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -15,8 +14,7 @@ import ( var _ = Describe("QuickConnect", func() { BeforeEach(func() { setupTestDB() - DeferCleanup(configtest.SetupConfig()) - conf.Server.Jellyfin.QuickConnect = true + conf.Update(func(c *conf.Options) { c.Jellyfin.QuickConnect = true }) }) clientReq := func(deviceID, method, path, body string) *httptest.ResponseRecorder { @@ -81,7 +79,7 @@ var _ = Describe("QuickConnect", func() { }) It("answers 401 on every Quick Connect call when disabled", func() { - conf.Server.Jellyfin.QuickConnect = false + conf.Update(func(c *conf.Options) { c.Jellyfin.QuickConnect = false }) Expect(rawReq("GET", "/QuickConnect/Enabled", "").Body.String()).To(MatchJSON("false")) Expect(clientReq("new-device", "POST", "/QuickConnect/Initiate", "").Code).To(Equal(http.StatusUnauthorized)) Expect(rawReq("GET", "/QuickConnect/Connect?Secret=x", "").Code).To(Equal(http.StatusUnauthorized)) diff --git a/server/jellyfin/images.go b/server/jellyfin/images.go index 6af533dbb..e1962190c 100644 --- a/server/jellyfin/images.go +++ b/server/jellyfin/images.go @@ -109,7 +109,7 @@ func (api *Router) postItemImage(w http.ResponseWriter, r *http.Request) { // Honor the same artwork-upload gate and size cap as the native endpoint. u, _ := request.UserFrom(ctx) - if !conf.Server.EnableArtworkUpload && !u.IsAdmin { + if !conf.Server().EnableArtworkUpload && !u.IsAdmin { http.Error(w, "Forbidden", http.StatusForbidden) return } diff --git a/server/jellyfin/images_test.go b/server/jellyfin/images_test.go index b7cf9b7e7..1e7784a06 100644 --- a/server/jellyfin/images_test.go +++ b/server/jellyfin/images_test.go @@ -18,7 +18,6 @@ import ( "github.com/go-chi/chi/v5" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -337,8 +336,7 @@ var _ = Describe("postItemImage", func() { }) It("rejects an oversized body with 400, like the native endpoint", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.MaxImageUploadSize = "16" // 16 bytes + conf.Update(func(c *conf.Options) { c.MaxImageUploadSize = "16" }) // 16 bytes w := httptest.NewRecorder() r := httptest.NewRequest("POST", "/Items/"+dto.EncodeID(testID("pl1"))+"/Images/Primary", bytes.NewReader(jpegBytes())) r.Header.Set("Content-Type", "image/jpeg") @@ -351,10 +349,9 @@ var _ = Describe("postItemImage", func() { }) It("applies the size limit to the decoded image, not the base64 body", func() { - DeferCleanup(configtest.SetupConfig()) img := pngBytes() // The raw image is exactly at the limit; its base64 form is 4/3 bigger. - conf.Server.MaxImageUploadSize = strconv.Itoa(len(img)) + conf.Update(func(c *conf.Options) { c.MaxImageUploadSize = strconv.Itoa(len(img)) }) body := []byte(base64.StdEncoding.EncodeToString(img)) Expect(len(body)).To(BeNumerically(">", len(img))) w := httptest.NewRecorder() @@ -369,9 +366,8 @@ var _ = Describe("postItemImage", func() { }) It("rejects a base64 body whose decoded image exceeds the limit with 400", func() { - DeferCleanup(configtest.SetupConfig()) img := pngBytes() - conf.Server.MaxImageUploadSize = strconv.Itoa(len(img) - 1) + conf.Update(func(c *conf.Options) { c.MaxImageUploadSize = strconv.Itoa(len(img) - 1) }) body := []byte(base64.StdEncoding.EncodeToString(img)) w := httptest.NewRecorder() r := httptest.NewRequest("POST", "/Items/"+dto.EncodeID(testID("pl1"))+"/Images/Primary", bytes.NewReader(body)) @@ -410,8 +406,7 @@ var _ = Describe("postItemImage", func() { }) It("forbids a non-admin upload when artwork upload is disabled", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableArtworkUpload = false + conf.Update(func(c *conf.Options) { c.EnableArtworkUpload = false }) w := httptest.NewRecorder() r := httptest.NewRequest("POST", "/Items/"+dto.EncodeID(testID("pl1"))+"/Images/Primary", bytes.NewReader(jpegBytes())) r.Header.Set("Content-Type", "image/jpeg") @@ -425,8 +420,7 @@ var _ = Describe("postItemImage", func() { }) It("still allows an admin upload when artwork upload is disabled", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableArtworkUpload = false + conf.Update(func(c *conf.Options) { c.EnableArtworkUpload = false }) w := httptest.NewRecorder() r := httptest.NewRequest("POST", "/Items/"+dto.EncodeID(testID("pl1"))+"/Images/Primary", bytes.NewReader(jpegBytes())) r.Header.Set("Content-Type", "image/jpeg") diff --git a/server/jellyfin/items.go b/server/jellyfin/items.go index 28de4c31e..727c48967 100644 --- a/server/jellyfin/items.go +++ b/server/jellyfin/items.go @@ -31,6 +31,12 @@ func searchTerm(p *req.Values) string { return strings.TrimSpace(p.StringOr("searchterm", "")) } +// joinedStrings joins repeated values of a query param with commas. Clients send lists either +// comma-separated (Finamp) or as repeated keys (@jellyfin/sdk), and the parsers split on commas. +func joinedStrings(p *req.Values, key string) string { + return strings.Join(p.Strings(key), ",") +} + // itemFilters is the parsed Filters=... list together with the standalone isFavorite/isPlayed params // clients may send instead. A nil field means the client asked for no filtering on that dimension. type itemFilters struct { @@ -42,7 +48,7 @@ type itemFilters struct { // Jellyfin. Tokens with no Navidrome equivalent (Likes, IsFolder, IsResumable) are dropped. func parseItemFilters(p *req.Values) itemFilters { f := itemFilters{favorite: p.BoolPtr("isfavorite"), played: p.BoolPtr("isplayed")} - for token := range strings.SplitSeq(p.StringOr("filters", ""), ",") { + for token := range strings.SplitSeq(joinedStrings(p, "filters"), ",") { switch strings.TrimSpace(token) { case "IsFavorite", "IsFavoriteOrLikes": f.favorite = new(true) @@ -294,25 +300,34 @@ type itemsQuery struct { entityParent string isLibraryParent bool scopeIDs []int - // artistId selects that artist's own discography; contributingOnly means albums they merely - // appear on (Jellyfin's "Featured On"), which must exclude that discography. - artistId string + // artistIds selects those artists' own discography (any of them). contributingOnly means albums + // they merely appear on (Jellyfin's "Featured On"), which must exclude that discography. + artistIds []string contributingOnly bool genreIds []string albumIds []string years []int studioIds []string + userRoot bool +} + +// hasFilters reports the params that make a ParentId-less /Items a content query, not the user root. +func (q itemsQuery) hasFilters() bool { + return q.rawTypes != "" || len(q.ids) > 0 || q.search != "" || len(q.artistIds) > 0 || + len(q.genreIds) > 0 || len(q.albumIds) > 0 || len(q.studioIds) > 0 || len(q.years) > 0 || + q.filters != (itemFilters{}) } // listParams reads the itemsQuery fields that come straight from query params. func listParams(p *req.Values) itemsQuery { + offset, limit := pageParams(p) return itemsQuery{ fields: dto.ParseFields(p.Strings("fields")...), search: searchTerm(p), - sortBy: p.StringOr("sortby", ""), - sortOrder: p.StringOr("sortorder", ""), - offset: p.IntOr("startindex", 0), - limit: p.IntOr("limit", 0), + sortBy: joinedStrings(p, "sortby"), + sortOrder: joinedStrings(p, "sortorder"), + offset: offset, + limit: limit, filters: parseItemFilters(p), } } @@ -349,7 +364,7 @@ func (api *Router) parseItemsQuery(ctx context.Context, r *http.Request) (itemsQ } q := listParams(p) q.ids = ids - q.rawTypes = knownItemKinds(p.StringOr("includeitemtypes", "")) + q.rawTypes = knownItemKinds(joinedStrings(p, "includeitemtypes")) q.parentId = parentId q.genreIds = genreIds q.albumIds = albumIds @@ -357,21 +372,25 @@ func (api *Router) parseItemsQuery(ctx context.Context, r *http.Request) (itemsQ q.studioIds = studioIds // An artist's page filters by artist, not ParentId: Finamp sends ParentId= for scoping // plus AlbumArtistIds/ArtistIds/contributingArtistIds for the artist. - albumArtistScope := firstNonEmpty(p.StringOr("albumartistids", ""), p.StringOr("artistids", "")) - contributingScope := p.StringOr("contributingartistids", "") - artistId, ok := firstDecodedID(firstNonEmpty(albumArtistScope, contributingScope)) + albumArtistScope := joinedStrings(p, "albumartistids") + artistScope := joinedStrings(p, "artistids") + contributingScope := joinedStrings(p, "contributingartistids") + artistIds, ok := decodedIDList(firstNonEmpty(albumArtistScope, artistScope, contributingScope)) if !ok { return itemsQuery{}, model.ErrNotFound } - q.artistId = artistId - q.contributingOnly = albumArtistScope == "" && contributingScope != "" + q.artistIds = artistIds + q.contributingOnly = albumArtistScope == "" && artistScope == "" && contributingScope != "" + + recursive := p.BoolOr("recursive", false) + q.userRoot = q.parentId == "" && !recursive && !q.hasFilters() q.types = parseTypes(q.rawTypes) q.scopeIDs, q.isLibraryParent = resolveLibraryScope(ctx, q.parentId) // Recursive=false asks for direct children only, and no track is a library's direct child. // Finamp's sync probes a library this way, and every track is a wrong, unbounded answer. - if q.isLibraryParent && !p.BoolOr("recursive", false) { + if q.isLibraryParent && !recursive { q.types = slices.DeleteFunc(q.types, func(t string) bool { return t == "Audio" }) } @@ -410,6 +429,14 @@ func (api *Router) queryItems(ctx context.Context, r *http.Request) (itemsResult // A ManualPlaylistsFolder query asks for the synthetic "playlists library" container, not real items. case strings.Contains(strings.ToLower(q.rawTypes), "manualplaylistsfolder"): return materialized(result([]dto.BaseItemDto{playlistsFolder()}, 1, 0)), nil + // Symfonium's sync reads the libraries this way; answering with albums makes it sync nothing. + case q.userRoot: + views, err := api.userViews(ctx) + if err != nil { + return itemsResult{}, err + } + sortViews(views, q.sortBy, q.sortOrder) + return materialized(result(paginate(views, q.offset, q.limit), len(views), q.offset)), nil } if repo, ok := api.playlistTracksRepo(ctx, q); ok { return api.playlistTrackPage(ctx, repo, q.fields, q.offset, q.limit) @@ -497,7 +524,8 @@ func (api *Router) mergeTypesPaged(ctx context.Context, q itemsQuery, offset int // Each per-type query needs at most offset+limit rows (worst case: one type fills the whole window). window := offset + q.limit if q.search != "" { - window = min(window, maxSearchLimit) + // Capping offset before the sum keeps a huge StartIndex from wrapping the window negative. + window = min(min(offset, maxSearchLimit)+q.limit, maxSearchLimit) } lists := make([][]dto.BaseItemDto, len(q.types)) totals := make([]int, len(q.types)) @@ -560,14 +588,25 @@ func firstNonEmpty(vals ...string) string { return "" } -// firstDecodedID decodes the first id from a (possibly comma-separated) Jellyfin id list, reporting -// whether it decoded successfully (see decodeFilterParam). -func firstDecodedID(s string) (string, bool) { - if s == "" { - return "", true +// decodedIDList decodes every id in a comma-joined Jellyfin id list. ok is false when any entry is +// malformed, so a later bad id can't be dropped and widen the query (see decodeFilterParam). +func decodedIDList(s string) ([]string, bool) { + if strings.TrimSpace(s) == "" { + return nil, true } - first, _, _ := strings.Cut(s, ",") - return decodeFilterParam(strings.TrimSpace(first)) + var ids []string + for part := range strings.SplitSeq(s, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + id, ok := decodeFilterParam(part) + if !ok { + return nil, false + } + ids = append(ids, id) + } + return ids, true } // decodedQueryIDs reads an id-list param in both client spellings (see queryIDs). ok is false if @@ -632,9 +671,16 @@ func parseTypes(types string) []string { return slice.Unique(recognized) } -// paginate applies StartIndex/Limit to an in-memory item list, for the multi-type merge path only -// (single-type queries push Offset/Max down to SQL instead). +// pageParams reads StartIndex/Limit; Jellyfin treats a negative StartIndex as 0. +func pageParams(p *req.Values) (offset, limit int) { + return max(p.IntOr("startindex", 0), 0), p.IntOr("limit", 0) +} + +// paginate applies StartIndex/Limit to an in-memory item list (single-type queries push Offset/Max +// down to SQL instead). func paginate(items []dto.BaseItemDto, offset, limit int) []dto.BaseItemDto { + // A negative offset would panic the slice below; Jellyfin treats it as 0. + offset = max(offset, 0) if offset >= len(items) { return []dto.BaseItemDto{} } @@ -645,6 +691,40 @@ func paginate(items []dto.BaseItemDto, offset, limit int) []dto.BaseItemDto { return items } +// sortViews applies SortBy/SortOrder to the user-root libraries, sorted in memory since a user only +// has a handful; without a usable key they keep the repository order. +func sortViews(views []dto.BaseItemDto, sortBy, order string) { + type sortKey struct { + value func(dto.BaseItemDto) string + desc bool + } + dirs := listParts(order) + var keys []sortKey + for i, key := range listParts(sortBy) { + desc := sortDirection(i, dirs) == "desc" + switch strings.ToLower(key) { + case "sortname", "name": + keys = append(keys, sortKey{func(v dto.BaseItemDto) string { return strings.ToLower(v.SortName) }, desc}) + case "datecreated": + keys = append(keys, sortKey{func(v dto.BaseItemDto) string { return v.DateCreated }, desc}) + } + } + if len(keys) == 0 { + return + } + slices.SortStableFunc(views, func(a, b dto.BaseItemDto) int { + for _, k := range keys { + if r := strings.Compare(k.value(a), k.value(b)); r != 0 { + if k.desc { + r = -r + } + return r + } + } + return 0 + }) +} + // interleave merges per-type item lists round-robin: one item from each list in turn, preserving // each list's own order, so no single type dominates the head of a mixed-type result. func interleave(lists [][]dto.BaseItemDto) []dto.BaseItemDto { @@ -707,10 +787,12 @@ func (api *Router) listAlbums(ctx context.Context, opts model.QueryOptions, q it // For albums, ParentId (browse an artist) and AlbumArtistIds/ArtistIds both mean "this artist's // albums"; contributingArtistIds means "albums they only appear on" (Featured On). switch { - case q.contributingOnly && q.artistId != "": - filters = append(filters, filter.AlbumsByContributingArtistID(q.artistId).Filters) - case firstNonEmpty(q.artistId, q.entityParent) != "": - filters = append(filters, filter.AlbumsByArtistID(firstNonEmpty(q.artistId, q.entityParent)).Filters) + case q.contributingOnly && len(q.artistIds) > 0: + filters = append(filters, filter.AlbumsByContributingArtistID(q.artistIds).Filters) + case len(q.artistIds) > 0: + filters = append(filters, filter.AlbumsByArtistID(q.artistIds).Filters) + case q.entityParent != "": + filters = append(filters, filter.AlbumsByArtistID(q.entityParent).Filters) default: filters = append(filters, notMissing) } @@ -753,8 +835,8 @@ func (api *Router) listSongs(ctx context.Context, opts model.QueryOptions, q ite filters := squirrel.And{} // For songs, ArtistIds/AlbumArtistIds selects an artist's tracks; ParentId selects an album's. switch { - case q.artistId != "": - filters = append(filters, filter.SongsByArtistID(q.artistId).Filters) + case len(q.artistIds) > 0: + filters = append(filters, filter.SongsByArtistID(q.artistIds).Filters) case q.entityParent != "": filters = append(filters, filter.SongsByAlbum(q.entityParent).Filters) default: @@ -791,7 +873,7 @@ func (api *Router) listSongs(ctx context.Context, opts model.QueryOptions, q ite } // When browsing an album's tracks, default to disc+track order (like Subsonic's GetAlbum); an // explicit client SortBy still wins, since applySort already set opts.Sort. - if q.artistId == "" && q.entityParent != "" && opts.Sort == "" { + if len(q.artistIds) == 0 && q.entityParent != "" && opts.Sort == "" { opts.Sort = filter.SongsByAlbum(q.entityParent).Sort } // A full-library request (Finamp's sync, with MediaSources) is tens of thousands of fat rows. @@ -1011,17 +1093,24 @@ func result(items []dto.BaseItemDto, total, start int) dto.QueryResult { return dto.QueryResult{Items: items, TotalRecordCount: total, StartIndex: start} } -// applySort keeps every recognized SortBy key, so secondary keys break ties as Jellyfin intends. -// Unrecognized keys are skipped, not passed through raw where they could make an invalid ORDER BY. +// applySort keeps every recognized SortBy key, paired with SortOrder by index as Jellyfin's GetOrderBy +// does. Unrecognized keys are skipped, not passed through raw where they could make an invalid ORDER BY. func applySort(opts *model.QueryOptions, itemType, sortBy, order string) { - var cols []string - for key := range strings.SplitSeq(sortBy, ",") { + dirs := listParts(order) + var cols, colOrders []string + for i, key := range strings.Split(sortBy, ",") { + // An absent SortBy splits to one empty part; that is "no sort", not a key to count. + if sortBy == "" { + break + } + dir := sortDirection(i, dirs) col, ok := sortColumn(itemType, strings.TrimSpace(key)) // The repo matches random by exact string equality, so it can only ever sort alone. if !ok || slices.Contains(cols, col) || (col == "random" && len(cols) > 0) { continue } cols = append(cols, col) + colOrders = append(colOrders, dir) if col == "random" { break } @@ -1029,16 +1118,62 @@ func applySort(opts *model.QueryOptions, itemType, sortBy, order string) { switch { case len(cols) > 0: opts.Sort = strings.Join(cols, ", ") - case sortBy != "": + case strings.TrimSpace(sortBy) != "": log.Debug("Jellyfin API: no usable SortBy key, falling back to the default order", "itemType", itemType, "sortBy", sortBy) } - // Jellyfin allows a per-key SortOrder list, which one Order can't express; honor the first value - // for every key, as Jellyfin does for keys past the end of the list. - first, _, _ := strings.Cut(order, ",") - if strings.EqualFold(first, "Descending") { - opts.Order = "desc" + if !mixedDirections(colOrders) { + // With no kept key, a lone SortOrder still sets Order. + dir := sortDirection(0, dirs) + if len(colOrders) > 0 { + dir = colOrders[0] + } + if dir == "desc" { + opts.Order = "desc" + } + return } + opts.SortOrders = colOrders +} + +// listParts splits a comma-joined query value. An absent value is nil, not a single empty part. +func listParts(s string) []string { + if strings.TrimSpace(s) == "" { + return nil + } + parts := strings.Split(s, ",") + for i, part := range parts { + parts[i] = strings.TrimSpace(part) + } + return parts +} + +// sortDirection is "desc" only for Jellyfin's Descending. Keys past the end of dirs reuse the first +// entry, which is what Jellyfin does for a SortOrder list shorter than SortBy. +func sortDirection(i int, dirs []string) string { + if len(dirs) == 0 { + return "asc" + } + raw := dirs[0] + if i < len(dirs) { + raw = dirs[i] + } + if strings.EqualFold(raw, "Descending") { + return "desc" + } + return "asc" +} + +func mixedDirections(orders []string) bool { + if len(orders) < 2 { + return false + } + for _, order := range orders[1:] { + if order != orders[0] { + return true + } + } + return false } // sortColumnsByType maps lowercased-SortBy -> repo-sort-key per item type (repos map logical fields diff --git a/server/jellyfin/items_test.go b/server/jellyfin/items_test.go index bdf0be253..87d2a624c 100644 --- a/server/jellyfin/items_test.go +++ b/server/jellyfin/items_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "math" "net/http" "net/http/httptest" "slices" @@ -14,6 +15,7 @@ import ( "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/server/jellyfin/dto" "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/utils/req" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -50,6 +52,72 @@ var _ = Describe("Items", func() { }) Describe("getItems", func() { + Describe("at the user root", func() { + libs := model.Libraries{{ID: 1, Name: "Music"}, {ID: 2, Name: "Audiobooks"}} + getRoot := func(query string, ctx context.Context) dto.QueryResult { + w := httptest.NewRecorder() + invoke(api.getItems, w, httptest.NewRequest("GET", "/Items?"+query, nil).WithContext(ctx)) + Expect(w.Code).To(Equal(http.StatusOK)) + var res dto.QueryResult + Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + return res + } + BeforeEach(func() { + ds.Library().(*tests.MockLibraryRepo).SetData(libs) + ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + }) + + It("lists the user's libraries for an unfiltered, non-recursive query", func() { + res := getRoot("UserId="+testID("u1"), ctxUser()) + Expect(res.TotalRecordCount).To(Equal(1)) + Expect(res.Items).To(HaveLen(1)) + Expect(res.Items[0].Id).To(Equal(dto.EncodeLibraryID(1))) + Expect(res.Items[0].Type).To(Equal("CollectionFolder")) + Expect(res.Items[0].CollectionType).To(Equal("music")) + }) + + It("pages the libraries by StartIndex and Limit", func() { + res := getRoot("StartIndex=1&Limit=1", ctxUserWithLibraries(libs)) + Expect(res.TotalRecordCount).To(Equal(2)) + Expect(res.StartIndex).To(Equal(1)) + Expect(res.Items).To(HaveLen(1)) + Expect(res.Items[0].Id).To(Equal(dto.EncodeLibraryID(2))) + }) + + DescribeTable("sorts the libraries before paging them", + func(query string, wantID int) { + res := getRoot(query, ctxUserWithLibraries(libs)) + Expect(res.TotalRecordCount).To(Equal(2)) + Expect(res.Items).To(HaveLen(1)) + Expect(res.Items[0].Id).To(Equal(dto.EncodeLibraryID(wantID))) + }, + Entry("by name ascending", "SortBy=SortName&Limit=1", 2), + Entry("by name descending", "SortBy=SortName&SortOrder=Descending&Limit=1", 1), + Entry("descending, second page", "SortBy=Name&SortOrder=Descending&StartIndex=1&Limit=1", 2), + Entry("unknown key keeps the repository order", "SortBy=Bogus&Limit=1", 1), + Entry("SortOrder pairs with SortBy by index", "SortBy=DateCreated,SortName&SortOrder=Ascending,Descending&Limit=1", 1), + ) + + It("treats an unknown IncludeItemTypes as absent", func() { + res := getRoot("IncludeItemTypes=music", ctxUser()) + Expect(res.Items).To(HaveLen(1)) + Expect(res.Items[0].Type).To(Equal("CollectionFolder")) + }) + + DescribeTable("queries the library contents when the request is recursive or filtered", + func(query string) { + res := getRoot(query, ctxUser()) + Expect(res.Items).To(HaveLen(1)) + Expect(res.Items[0].Type).To(Equal("MusicAlbum")) + }, + Entry("Recursive=true", "Recursive=true"), + Entry("IncludeItemTypes", "IncludeItemTypes=MusicAlbum"), + Entry("SearchTerm", "SearchTerm=one"), + Entry("Filters", "Filters=IsUnplayed"), + Entry("Years", "Years=2020"), + ) + }) + It("lists albums when IncludeItemTypes=MusicAlbum", func() { ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}}) w := httptest.NewRecorder() @@ -288,6 +356,37 @@ var _ = Describe("Items", func() { Expect(res.TotalRecordCount).To(Equal(2)) }) + // @jellyfin/sdk (Jellify) sends array params as repeated keys. + It("merges results from every repeated IncludeItemTypes key", func() { + ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "Salt"}}) + ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Salt"}}) + ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "Salt"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/Items?SearchTerm=Salt&IncludeItemTypes=MusicArtist&IncludeItemTypes=Audio&IncludeItemTypes=MusicAlbum", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + var res dto.QueryResult + Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + Expect(res.Items).To(HaveLen(3)) + types := []string{res.Items[0].Type, res.Items[1].Type, res.Items[2].Type} + Expect(types).To(ConsistOf("MusicArtist", "Audio", "MusicAlbum")) + Expect(res.TotalRecordCount).To(Equal(3)) + }) + + It("mixes a repeated IncludeItemTypes key with a comma-separated one", func() { + ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "Salt"}}) + ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Salt"}}) + ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "Salt"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicArtist&IncludeItemTypes=Audio,MusicAlbum", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + var res dto.QueryResult + Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + types := []string{res.Items[0].Type, res.Items[1].Type, res.Items[2].Type} + Expect(types).To(ConsistOf("MusicArtist", "Audio", "MusicAlbum")) + }) + It("merges favorite songs, albums, and playlists", func() { mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) @@ -313,6 +412,19 @@ var _ = Describe("Items", func() { Expect(playlistSQL).To(ContainSubstring("starred")) }) + It("applies every repeated Filters key", func() { + albumRepo := ds.Album().(*tests.MockAlbumRepo) + albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicAlbum&Filters=IsFavorite&Filters=IsPlayed", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + sql, _, err := albumRepo.Options.Filters.ToSql() + Expect(err).NotTo(HaveOccurred()) + Expect(sql).To(ContainSubstring("starred")) + Expect(sql).To(ContainSubstring("play_count")) + }) + It("applies StartIndex/Limit to the merged multi-type result set", func() { ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}, {ID: testID("s2"), Title: "Song2"}}) ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}}) @@ -341,6 +453,39 @@ var _ = Describe("Items", func() { Expect(albumRepo.Options.Max).To(Equal(3)) }) + It("treats a negative StartIndex as 0 on the multi-type merge instead of panicking", func() { + mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) + mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}, {ID: testID("s2"), Title: "Song2"}}) + albumRepo := ds.Album().(*tests.MockAlbumRepo) + albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio,MusicAlbum&StartIndex=-1&Limit=2", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + var res dto.QueryResult + Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + Expect(res.StartIndex).To(Equal(0)) + Expect(res.Items).To(HaveLen(2)) + Expect(res.TotalRecordCount).To(Equal(4)) + // The clamped offset must feed the per-type window too: 0+Limit, not -1+Limit. + Expect(mfRepo.Options.Max).To(Equal(2)) + Expect(albumRepo.Options.Max).To(Equal(2)) + }) + + It("clamps a negative StartIndex to 0 on the single-type path", func() { + albumRepo := ds.Album().(*tests.MockAlbumRepo) + albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicAlbum&StartIndex=-1&Limit=10", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(albumRepo.Options.Offset).To(Equal(0)) + var res dto.QueryResult + Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + Expect(res.StartIndex).To(Equal(0)) + Expect(res.Items).To(HaveLen(1)) + }) + DescribeTable("translates the Filters list and its standalone equivalents", func(query string, wantSQL, notWantSQL []string) { albumRepo := ds.Album().(*tests.MockAlbumRepo) @@ -487,18 +632,22 @@ var _ = Describe("Items", func() { Expect(res.TotalRecordCount).To(BeNumerically(">", 10)) }) - It("bounds the multi-type search window however large StartIndex is", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=500000&Limit=1", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - // Without the bound this asks each type for ~500001 rows. - Expect(albumRepo.Options.Max).To(Equal(maxSearchLimit + 1)) - }) + DescribeTable("bounds the multi-type search window however large StartIndex is", + func(startIndex int) { + albumRepo := ds.Album().(*tests.MockAlbumRepo) + albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", fmt.Sprintf("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=%d&Limit=1", startIndex), nil). + WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(albumRepo.Options.Max).To(Equal(maxSearchLimit + 1)) + }, + Entry("large", 500000), + // StartIndex+Limit would wrap negative and slice out of range in a worker goroutine. + Entry("near the int limit", math.MaxInt), + ) It("stops a multi-type search at the ceiling rather than serving another type's rows", func() { // Bounding the per-type window is what keeps StartIndex from driving it without limit, and @@ -708,9 +857,8 @@ var _ = Describe("Items", func() { Entry("nothing recognized leaves the repo default", "MusicAlbum", "SeriesSortName", ""), ) - // Jellyfin allows a per-key SortOrder list; we cannot express that through one Order, so - // we honor the first value for all keys, matching Jellyfin's fallback for extra keys. - DescribeTable("reads the first SortOrder value for the whole sort", + // Jellyfin reuses the first SortOrder for keys past the end of the list. + DescribeTable("applies one SortOrder to every sort key", func(sortOrder, want string) { albumRepo := ds.Album().(*tests.MockAlbumRepo) albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) @@ -719,13 +867,50 @@ var _ = Describe("Items", func() { "/Items?IncludeItemTypes=MusicAlbum&SortBy=Runtime,SortName&SortOrder="+sortOrder, nil).WithContext(ctxUser()) invoke(api.getItems, w, r) Expect(w.Code).To(Equal(http.StatusOK)) + Expect(albumRepo.Options.Sort).To(Equal("duration, name")) Expect(albumRepo.Options.Order).To(Equal(want)) + Expect(albumRepo.Options.SortOrders).To(BeEmpty()) }, Entry("ascending", "Ascending", ""), Entry("descending", "Descending", "desc"), - Entry("descending leading a list", "Descending,Ascending", "desc"), - Entry("ascending leading a list", "Ascending,Descending", ""), ) + + It("pairs each SortOrder with its SortBy key", func() { + albumRepo := ds.Album().(*tests.MockAlbumRepo) + albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", + "/Items?IncludeItemTypes=MusicAlbum&SortBy=Runtime,SortName,PlayCount&SortOrder=Descending,Ascending", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(albumRepo.Options.Sort).To(Equal("duration, name, play_count")) + Expect(albumRepo.Options.Order).To(BeEmpty()) + Expect(albumRepo.Options.SortOrders).To(Equal([]string{"desc", "asc", "desc"})) + }) + + It("keeps every key of a repeated SortBy", func() { + albumRepo := ds.Album().(*tests.MockAlbumRepo) + albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", + "/Items?IncludeItemTypes=MusicAlbum&SortBy=Runtime&SortBy=SortName", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(albumRepo.Options.Sort).To(Equal("duration, name")) + }) + + It("pairs a repeated SortOrder key with its SortBy key", func() { + albumRepo := ds.Album().(*tests.MockAlbumRepo) + albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", + "/Items?IncludeItemTypes=MusicAlbum&SortBy=Runtime,SortName&SortOrder=Ascending&SortOrder=Descending", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(albumRepo.Options.Sort).To(Equal("duration, name")) + Expect(albumRepo.Options.Order).To(BeEmpty()) + Expect(albumRepo.Options.SortOrders).To(Equal([]string{"asc", "desc"})) + }) }) Describe("library scoping", func() { @@ -849,6 +1034,56 @@ var _ = Describe("Items", func() { Expect(w.Code).To(Equal(http.StatusNotFound)) }) + It("404s when a later repeated ArtistIds value is malformed", func() { + ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", + "/Items?IncludeItemTypes=Audio&ArtistIds="+dto.EncodeID(testID("ar1"))+"&ArtistIds=not-a-valid-id", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusNotFound)) + }) + + It("filters songs by every repeated ArtistIds key", func() { + mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) + mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", + "/Items?IncludeItemTypes=Audio&ArtistIds="+dto.EncodeID(testID("ar1"))+"&ArtistIds="+dto.EncodeID(testID("ar2")), nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + _, args, err := mfRepo.Options.Filters.ToSql() + Expect(err).NotTo(HaveOccurred()) + Expect(args).To(ContainElements(testID("ar1"), testID("ar2"))) + }) + + It("filters albums by every artist in a comma-separated AlbumArtistIds", func() { + albumRepo := ds.Album().(*tests.MockAlbumRepo) + albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", + "/Items?IncludeItemTypes=MusicAlbum&AlbumArtistIds="+dto.EncodeID(testID("ar1"))+","+dto.EncodeID(testID("ar2")), nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + _, args, err := albumRepo.Options.Filters.ToSql() + Expect(err).NotTo(HaveOccurred()) + Expect(args).To(ContainElements(testID("ar1"), testID("ar2"))) + }) + + It("excludes an album artist from a multi-id contributingArtistIds Featured On filter", func() { + albumRepo := ds.Album().(*tests.MockAlbumRepo) + albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", + "/Items?IncludeItemTypes=MusicAlbum&contributingArtistIds="+dto.EncodeID(testID("ar1"))+","+dto.EncodeID(testID("ar2")), nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + sql, args, err := albumRepo.Options.Filters.ToSql() + Expect(err).NotTo(HaveOccurred()) + Expect(sql).To(ContainSubstring("NOT IN")) + Expect(args).To(ContainElements(testID("ar1"), testID("ar2"))) + Expect(strings.Count(sql, "album_artists")).To(Equal(2)) + }) + It("still applies the artist filter (rather than dropping it) for a well-formed but unknown AlbumArtistIds", func() { albumRepo := ds.Album().(*tests.MockAlbumRepo) albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) @@ -1154,6 +1389,17 @@ var _ = Describe("Items", func() { Expect(knownItemKinds("music, audio,MUSICVIDEO")).To(Equal("audio,MUSICVIDEO")) }) + It("keeps entries from every value of a repeated param", func() { + repeated := func(rawURL string) string { + r := httptest.NewRequest("GET", rawURL, nil) + return knownItemKinds(joinedStrings(req.Params(r), "includeitemtypes")) + } + Expect(repeated("/Items?includeitemtypes=MusicArtist&includeitemtypes=Audio&includeitemtypes=MusicAlbum")). + To(Equal("MusicArtist,Audio,MusicAlbum")) + Expect(repeated("/Items?includeitemtypes=Nonsense&includeitemtypes=music")).To(BeEmpty()) + Expect(repeated("/Items")).To(BeEmpty()) + }) + It("defaults to albums only when IncludeItemTypes is absent", func() { Expect(parseTypes("")).To(Equal([]string{"MusicAlbum"})) Expect(parseTypes("Nonsense")).To(BeEmpty()) diff --git a/server/jellyfin/jellyfin_suite_test.go b/server/jellyfin/jellyfin_suite_test.go index 2ae7da6e2..530b55c36 100644 --- a/server/jellyfin/jellyfin_suite_test.go +++ b/server/jellyfin/jellyfin_suite_test.go @@ -4,6 +4,7 @@ import ( "net/http" "testing" + "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model/id" "github.com/navidrome/navidrome/tests" @@ -18,6 +19,8 @@ func TestJellyfinApi(t *testing.T) { RunSpecs(t, "Jellyfin API Suite") } +var _ = configtest.RestoreAfterEachSpec() + // testID maps a readable label to a deterministic canonical id, so fixtures exercise the same // id shape production uses. func testID(label string) string { return id.NewHash("jellyfin-test", label) } diff --git a/server/jellyfin/playlists.go b/server/jellyfin/playlists.go index 5569f4f83..20375f19e 100644 --- a/server/jellyfin/playlists.go +++ b/server/jellyfin/playlists.go @@ -216,7 +216,8 @@ func (api *Router) getPlaylistItems(w http.ResponseWriter, r *http.Request) { } p := req.Params(r) fields := dto.ParseFields(p.Strings("fields")...) - res, err := api.playlistTrackPage(ctx, repo, fields, p.IntOr("startindex", 0), p.IntOr("limit", 0)) + offset, limit := pageParams(p) + res, err := api.playlistTrackPage(ctx, repo, fields, offset, limit) if err != nil { api.internalError(w, r, err) return diff --git a/server/jellyfin/playlists_test.go b/server/jellyfin/playlists_test.go index d38ef3b44..6c0e0a792 100644 --- a/server/jellyfin/playlists_test.go +++ b/server/jellyfin/playlists_test.go @@ -270,6 +270,27 @@ var _ = Describe("Playlists", func() { Expect(fp.tracksRepo.Options.Max).To(Equal(1)) }) + It("clamps a negative StartIndex to 0", func() { + fp.getPls = &model.Playlist{ + ID: testID("pl1"), + Tracks: model.PlaylistTracks{ + {ID: "1", MediaFileID: testID("s1"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s1")}}, + {ID: "2", MediaFileID: testID("s2"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s2")}}, + }, + } + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/Playlists/"+testID("pl1")+"/Items?StartIndex=-1&Limit=1", nil). + WithContext(context.Background()) + r = withChiURLParam(r, "playlistId", dto.EncodeID(testID("pl1"))) + invoke(api.getPlaylistItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + var res dto.QueryResult + Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + Expect(res.StartIndex).To(Equal(0)) + Expect(res.Items).To(HaveLen(1)) + Expect(fp.tracksRepo.Options.Offset).To(Equal(0)) + }) + It("returns 404 for a non-owned or absent playlist", func() { fp.getErr = model.ErrNotFound w := httptest.NewRecorder() diff --git a/server/jellyfin/quickconnect.go b/server/jellyfin/quickconnect.go index f7fa1b979..b56fa9df3 100644 --- a/server/jellyfin/quickconnect.go +++ b/server/jellyfin/quickconnect.go @@ -15,7 +15,7 @@ import ( func requireQuickConnect(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !conf.Server.Jellyfin.QuickConnect { + if !conf.Server().Jellyfin.QuickConnect { http.Error(w, "Quick connect is disabled", http.StatusUnauthorized) return } @@ -24,7 +24,7 @@ func requireQuickConnect(next http.Handler) http.Handler { } func (api *Router) quickConnectEnabled(w http.ResponseWriter, r *http.Request) { - api.ok(w, r, conf.Server.Jellyfin.QuickConnect) + api.ok(w, r, conf.Server().Jellyfin.QuickConnect) } // Initiate is unauthenticated and its fields are kept for minutes, so their size must be bounded. diff --git a/server/jellyfin/quickconnect_test.go b/server/jellyfin/quickconnect_test.go index 94573e6ff..b7e5bae23 100644 --- a/server/jellyfin/quickconnect_test.go +++ b/server/jellyfin/quickconnect_test.go @@ -8,7 +8,6 @@ import ( "strings" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/quickconnect" "github.com/navidrome/navidrome/model" @@ -37,8 +36,7 @@ var _ = Describe("QuickConnect", func() { ) BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Jellyfin.QuickConnect = true + conf.Update(func(c *conf.Options) { c.Jellyfin.QuickConnect = true }) ds = &tests.MockDataStore{} auth.Init(ds) ur := ds.User().(*tests.MockedUserRepo) @@ -61,7 +59,7 @@ var _ = Describe("QuickConnect", func() { Describe("GET /QuickConnect/Enabled", func() { DescribeTable("reports the config value", func(enabled bool, expected string) { - conf.Server.Jellyfin.QuickConnect = enabled + conf.Update(func(c *conf.Options) { c.Jellyfin.QuickConnect = enabled }) w := httptest.NewRecorder() api.quickConnectEnabled(w, httptest.NewRequest("GET", "/QuickConnect/Enabled", nil)) Expect(w.Code).To(Equal(http.StatusOK)) @@ -76,7 +74,7 @@ var _ = Describe("QuickConnect", func() { next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusTeapot) }) It("rejects requests with 401 when Quick Connect is disabled", func() { - conf.Server.Jellyfin.QuickConnect = false + conf.Update(func(c *conf.Options) { c.Jellyfin.QuickConnect = false }) w := httptest.NewRecorder() requireQuickConnect(next).ServeHTTP(w, httptest.NewRequest("POST", "/QuickConnect/Initiate", nil)) Expect(w.Code).To(Equal(http.StatusUnauthorized)) diff --git a/server/jellyfin/stream.go b/server/jellyfin/stream.go index 515a6fcb8..6ca2e11b2 100644 --- a/server/jellyfin/stream.go +++ b/server/jellyfin/stream.go @@ -107,7 +107,7 @@ func (api *Router) streamUniversal(w http.ResponseWriter, r *http.Request) { func universalClientInfo(p *req.Values) *stream.ClientInfo { ci := &stream.ClientInfo{Name: "jellyfin-universal", MaxAudioBitrate: bitRateParam(p)} - for entry := range strings.SplitSeq(p.StringOr("container", ""), ",") { + for entry := range strings.SplitSeq(joinedStrings(p, "container"), ",") { container, codec, _ := strings.Cut(strings.TrimSpace(entry), "|") if container == "" { continue diff --git a/server/jellyfin/stream_test.go b/server/jellyfin/stream_test.go index 7a1112f37..08357d14d 100644 --- a/server/jellyfin/stream_test.go +++ b/server/jellyfin/stream_test.go @@ -299,6 +299,14 @@ var _ = Describe("Stream", func() { Expect(decider.client.MaxTranscodingAudioBitrate).To(Equal(128)) }) + It("accepts repeated Container query parameters", func() { + universal("Container=mp3&Container=m4a|aac&TranscodingContainer=m4a&AudioCodec=aac") + Expect(decider.client.DirectPlayProfiles).To(Equal([]stream.DirectPlayProfile{ + {Containers: []string{"mp3"}, Protocols: []string{stream.ProtocolHTTP}}, + {Containers: []string{"m4a"}, AudioCodecs: []string{"aac"}, Protocols: []string{stream.ProtocolHTTP}}, + })) + }) + It("uses AudioCodec as the target when no TranscodingContainer is given", func() { universal("Container=mp3&AudioCodec=aac") Expect(decider.client.TranscodingProfiles).To(Equal([]stream.Profile{ diff --git a/server/jellyfin/system.go b/server/jellyfin/system.go index 2aae4c9c0..360d1595f 100644 --- a/server/jellyfin/system.go +++ b/server/jellyfin/system.go @@ -26,8 +26,8 @@ import ( const jellyfinVersion = "12.1.0" func serverName() string { - if conf.Server.Jellyfin.ServerName != "" { - return conf.Server.Jellyfin.ServerName + if conf.Server().Jellyfin.ServerName != "" { + return conf.Server().Jellyfin.ServerName } return fmt.Sprintf("Navidrome %s", consts.Version) } @@ -90,7 +90,7 @@ func (api *Router) publicInfo(r *http.Request) dto.PublicSystemInfo { // its server base URL; without it its SDK api instance is undefined and sign-in crashes. func localAddress(r *http.Request) string { scheme, host := server.ServerAddress(r) - return scheme + "://" + host + path.Join(conf.Server.BasePath, consts.URLPathJellyfinAPI) + return scheme + "://" + host + path.Join(conf.Server().BasePath, consts.URLPathJellyfinAPI) } func (api *Router) getPublicSystemInfo(w http.ResponseWriter, r *http.Request) { diff --git a/server/jellyfin/system_test.go b/server/jellyfin/system_test.go index d339043a7..13bd74b86 100644 --- a/server/jellyfin/system_test.go +++ b/server/jellyfin/system_test.go @@ -10,7 +10,6 @@ import ( "sync" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/server/jellyfin/dto" "github.com/navidrome/navidrome/tests" @@ -23,8 +22,7 @@ var _ = Describe("System", func() { BeforeEach(func() { api = &Router{} }) It("returns public system info without auth", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Jellyfin.ServerName = "" + conf.Update(func(c *conf.Options) { c.Jellyfin.ServerName = "" }) w := httptest.NewRecorder() r := httptest.NewRequest("GET", "/System/Info/Public", nil) @@ -41,8 +39,7 @@ var _ = Describe("System", func() { }) It("returns authenticated system info with the public fields plus library monitor support", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Jellyfin.ServerName = "" + conf.Update(func(c *conf.Options) { c.Jellyfin.ServerName = "" }) w := httptest.NewRecorder() r := httptest.NewRequest("GET", "/System/Info", nil) @@ -62,7 +59,6 @@ var _ = Describe("System", func() { }) It("advertises a LocalAddress with the request scheme, host and Jellyfin base path", func() { - DeferCleanup(configtest.SetupConfig()) w := httptest.NewRecorder() r := httptest.NewRequest("GET", "/System/Info/Public", nil) @@ -77,8 +73,7 @@ var _ = Describe("System", func() { }) It("responds to ping with the server name as plain text", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Jellyfin.ServerName = "" + conf.Update(func(c *conf.Options) { c.Jellyfin.ServerName = "" }) w := httptest.NewRecorder() r := httptest.NewRequest("GET", "/System/Ping", nil) diff --git a/server/jellyfin/users.go b/server/jellyfin/users.go index d0a54ee63..83cf6cd70 100644 --- a/server/jellyfin/users.go +++ b/server/jellyfin/users.go @@ -1,6 +1,7 @@ package jellyfin import ( + "context" "net/http" "strings" @@ -13,14 +14,21 @@ import ( // getUserViews returns one CollectionFolder view per accessible library, so clients browse each // library as its own top-level view rather than one aggregate. func (api *Router) getUserViews(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() + views, err := api.userViews(r.Context()) + if err != nil { + api.internalError(w, r, err) + return + } + api.ok(w, r, dto.QueryResult{Items: views, TotalRecordCount: len(views), StartIndex: 0}) +} + +func (api *Router) userViews(ctx context.Context) ([]dto.BaseItemDto, error) { u, _ := request.UserFrom(ctx) // u.Libraries comes from a projection without counts or stats, and clients hide a library that // looks empty, so the rows are re-read in full here. libs, err := api.ds.Library().GetAll(ctx) if err != nil { - api.internalError(w, r, err) - return + return nil, err } views := make([]dto.BaseItemDto, 0, len(libs)) for _, lib := range libs { @@ -28,7 +36,7 @@ func (api *Router) getUserViews(w http.ResponseWriter, r *http.Request) { views = append(views, dto.LibraryToBaseItem(lib)) } } - api.ok(w, r, dto.QueryResult{Items: views, TotalRecordCount: len(views), StartIndex: 0}) + return views, nil } func (api *Router) getCurrentUser(w http.ResponseWriter, r *http.Request) { @@ -45,7 +53,7 @@ func (api *Router) getPublicUsers(w http.ResponseWriter, r *http.Request) { serverID := api.serverID(ctx) seen := make(map[string]bool) users := []dto.UserDto{} - for name := range strings.SplitSeq(conf.Server.Jellyfin.ExposedPublicUsers, ",") { + for name := range strings.SplitSeq(conf.Server().Jellyfin.ExposedPublicUsers, ",") { name = strings.TrimSpace(name) if name == "" { continue diff --git a/server/jellyfin/users_test.go b/server/jellyfin/users_test.go index 793a64a29..d80ddc101 100644 --- a/server/jellyfin/users_test.go +++ b/server/jellyfin/users_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/server/jellyfin/dto" @@ -120,19 +119,18 @@ var _ = Describe("Users", func() { } BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) ur = api.ds.User().(*tests.MockedUserRepo) Expect(ur.Put(ctx, &model.User{ID: testID("u1"), UserName: "alice"})).To(Succeed()) Expect(ur.Put(ctx, &model.User{ID: testID("u2"), UserName: "bob"})).To(Succeed()) }) It("returns an empty list when the config is unset", func() { - conf.Server.Jellyfin.ExposedPublicUsers = "" + conf.Update(func(c *conf.Options) { c.Jellyfin.ExposedPublicUsers = "" }) Expect(publicUsers()).To(BeEmpty()) }) It("lists the configured users in order, without leaking policy", func() { - conf.Server.Jellyfin.ExposedPublicUsers = "bob, alice" + conf.Update(func(c *conf.Options) { c.Jellyfin.ExposedPublicUsers = "bob, alice" }) users := publicUsers() Expect(users).To(HaveLen(2)) Expect(users[0].Name).To(Equal("bob")) @@ -144,14 +142,14 @@ var _ = Describe("Users", func() { }) It("skips a configured username that does not exist", func() { - conf.Server.Jellyfin.ExposedPublicUsers = "alice,ghost" + conf.Update(func(c *conf.Options) { c.Jellyfin.ExposedPublicUsers = "alice,ghost" }) users := publicUsers() Expect(users).To(HaveLen(1)) Expect(users[0].Name).To(Equal("alice")) }) It("matches usernames case-insensitively and de-duplicates", func() { - conf.Server.Jellyfin.ExposedPublicUsers = "ALICE, alice" + conf.Update(func(c *conf.Options) { c.Jellyfin.ExposedPublicUsers = "ALICE, alice" }) users := publicUsers() Expect(users).To(HaveLen(1)) Expect(users[0].Name).To(Equal("alice")) diff --git a/server/middlewares.go b/server/middlewares.go index 149ddbfc3..25d70f1fa 100644 --- a/server/middlewares.go +++ b/server/middlewares.go @@ -110,7 +110,7 @@ func secureMiddleware() func(http.Handler) http.Handler { FrameDeny: true, ReferrerPolicy: "same-origin", PermissionsPolicy: "autoplay=(), camera=(), microphone=(), usb=()", - CustomFrameOptionsValue: conf.Server.HTTPHeaders.FrameOptions, + CustomFrameOptionsValue: conf.Server().HTTPHeaders.FrameOptions, //ContentSecurityPolicy: "script-src 'self' 'unsafe-inline'", }) return sec.Handler @@ -146,7 +146,7 @@ func clientUniqueIDMiddleware(next http.Handler) http.Handler { HttpOnly: true, Secure: true, SameSite: http.SameSiteStrictMode, - Path: cmp.Or(conf.Server.BasePath, "/"), + Path: cmp.Or(conf.Server().BasePath, "/"), } http.SetCookie(w, c) } else { @@ -174,7 +174,7 @@ func clientUniqueIDMiddleware(next http.Handler) http.Handler { // a client cannot pick its own identity and evade controls keyed on it. The peer address is kept // in the context as request.ReverseProxyIp. func realIPMiddleware(next http.Handler) http.Handler { - trusted := conf.Server.ExtAuth.TrustedSources + trusted := conf.Server().ExtAuth.TrustedSources fromPeer := middleware.ClientIPFromRemoteAddr(next) if trusted == "" { return fromPeer diff --git a/server/middlewares_test.go b/server/middlewares_test.go index 55f842914..f20600ad6 100644 --- a/server/middlewares_test.go +++ b/server/middlewares_test.go @@ -12,7 +12,6 @@ import ( "github.com/go-chi/chi/v5/middleware" "github.com/google/uuid" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/publicurl" "github.com/navidrome/navidrome/model" @@ -23,9 +22,6 @@ import ( ) var _ = Describe("middlewares", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) Describe("robotsTXT", func() { var nextCalled bool next := func(w http.ResponseWriter, r *http.Request) { @@ -211,7 +207,7 @@ var _ = Describe("middlewares", func() { Context("when the request header has the unique client ID", func() { BeforeEach(func() { req.Header.Set(consts.UIClientUniqueIDHeader, "123456") - conf.Server.BasePath = "/music" + conf.Update(func(c *conf.Options) { c.BasePath = "/music" }) }) It("sets the unique client ID as a cookie and adds it to the request context", func() { @@ -471,7 +467,7 @@ var _ = Describe("middlewares", func() { Context("with a trusted proxy", func() { BeforeEach(func() { - conf.Server.ExtAuth.TrustedSources = "10.0.0.0/8" + conf.Update(func(c *conf.Options) { c.ExtAuth.TrustedSources = "10.0.0.0/8" }) }) It("uses the forwarded client IP when the peer is a trusted proxy", func() { call("10.0.0.1:1234", map[string]string{"X-Forwarded-For": "203.0.113.5, 10.0.0.1"}) @@ -557,7 +553,7 @@ var _ = Describe("middlewares", func() { Context("behind a trusted proxy", func() { BeforeEach(func() { - conf.Server.ExtAuth.TrustedSources = "10.0.0.0/8" + conf.Update(func(c *conf.Options) { c.ExtAuth.TrustedSources = "10.0.0.0/8" }) }) It("gives each real client its own bucket", func() { Expect(attempt("10.0.0.1:1", "X-Forwarded-For", "203.0.113.1")).To(Equal(http.StatusOK)) diff --git a/server/nativeapi/config.go b/server/nativeapi/config.go index cfecfa663..350d4947e 100644 --- a/server/nativeapi/config.go +++ b/server/nativeapi/config.go @@ -97,7 +97,7 @@ func getConfig(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // Marshal the actual configuration struct to preserve original field names - configBytes, err := json.Marshal(conf.Server) + configBytes, err := json.Marshal(conf.Server()) if err != nil { log.Error(ctx, "Error marshaling config", err) http.Error(w, "Internal server error", http.StatusInternalServerError) @@ -118,7 +118,7 @@ func getConfig(w http.ResponseWriter, r *http.Request) { resp := configResponse{ ID: "config", - ConfigFile: conf.Server.ConfigFile, + ConfigFile: conf.Server().ConfigFile, Config: configMap, } diff --git a/server/nativeapi/config_test.go b/server/nativeapi/config_test.go index 6ac41f07a..aefa507b1 100644 --- a/server/nativeapi/config_test.go +++ b/server/nativeapi/config_test.go @@ -8,7 +8,6 @@ import ( "net/http/httptest" "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/core/playlists" @@ -27,9 +26,10 @@ var _ = Describe("Config API", func() { BeforeEach(func() { ctx = GinkgoT().Context() - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableSharing = false - conf.Server.DevUIShowConfig = true // Enable config endpoint for tests + conf.Update(func(c *conf.Options) { + c.EnableSharing = false + c.DevUIShowConfig = true + }) // Enable config endpoint for tests ds = &tests.MockDataStore{} auth.Init(ds) nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil) @@ -76,15 +76,17 @@ var _ = Describe("Config API", func() { var resp configResponse Expect(json.Unmarshal(w.Body.Bytes(), &resp)).To(Succeed()) Expect(resp.ID).To(Equal("config")) - Expect(resp.ConfigFile).To(Equal(conf.Server.ConfigFile)) + Expect(resp.ConfigFile).To(Equal(conf.Server().ConfigFile)) Expect(resp.Config).ToNot(BeEmpty()) }) It("redacts sensitive fields", func() { - conf.Server.LastFM.ApiKey = "secretapikey123" - conf.Server.PasswordEncryptionKey = "encryptionkey789" - conf.Server.DevAutoCreateAdminPassword = "adminpassword123" - conf.Server.Prometheus.Password = "prometheuspass" + conf.Update(func(c *conf.Options) { + c.LastFM.ApiKey = "secretapikey123" + c.PasswordEncryptionKey = "encryptionkey789" + c.DevAutoCreateAdminPassword = "adminpassword123" + c.Prometheus.Password = "prometheuspass" + }) req := createAuthenticatedConfigRequest(adminToken) w := httptest.NewRecorder() @@ -113,8 +115,10 @@ var _ = Describe("Config API", func() { }) It("handles empty sensitive values", func() { - conf.Server.LastFM.ApiKey = "" - conf.Server.PasswordEncryptionKey = "" + conf.Update(func(c *conf.Options) { + c.LastFM.ApiKey = "" + c.PasswordEncryptionKey = "" + }) req := createAuthenticatedConfigRequest(adminToken) w := httptest.NewRecorder() diff --git a/server/nativeapi/image_upload.go b/server/nativeapi/image_upload.go index c4ff62e42..6bde3dcd5 100644 --- a/server/nativeapi/image_upload.go +++ b/server/nativeapi/image_upload.go @@ -23,7 +23,7 @@ import ( func checkImageUploadPermission(w http.ResponseWriter, r *http.Request) bool { user, _ := request.UserFrom(r.Context()) - if !conf.Server.EnableArtworkUpload && !user.IsAdmin { + if !conf.Server().EnableArtworkUpload && !user.IsAdmin { http.Error(w, "artwork upload is disabled", http.StatusForbidden) return false } diff --git a/server/nativeapi/library_test.go b/server/nativeapi/library_test.go index cc05a30e5..3e6bea910 100644 --- a/server/nativeapi/library_test.go +++ b/server/nativeapi/library_test.go @@ -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/auth" "github.com/navidrome/navidrome/core/playlists" @@ -30,8 +29,7 @@ var _ = Describe("Library API", func() { BeforeEach(func() { ctx = GinkgoT().Context() - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableSharing = false + conf.Update(func(c *conf.Options) { c.EnableSharing = false }) ds = &tests.MockDataStore{} auth.Init(ds) nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil) diff --git a/server/nativeapi/metadata_test.go b/server/nativeapi/metadata_test.go index 294a26efe..42add6667 100644 --- a/server/nativeapi/metadata_test.go +++ b/server/nativeapi/metadata_test.go @@ -8,7 +8,6 @@ import ( "sync" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/external" "github.com/navidrome/navidrome/core/playlists" @@ -50,8 +49,7 @@ var _ = Describe("Metadata API", func() { BeforeEach(func() { ctx = GinkgoT().Context() - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableSharing = false + conf.Update(func(c *conf.Options) { c.EnableSharing = false }) artRepo = tests.CreateMockArtworkRepo() queueRepo = tests.CreateMockArtworkQueueRepo() albumRepo = tests.CreateMockAlbumRepo() diff --git a/server/nativeapi/missing_test.go b/server/nativeapi/missing_test.go index a53f13fc3..b41dd4b5c 100644 --- a/server/nativeapi/missing_test.go +++ b/server/nativeapi/missing_test.go @@ -7,7 +7,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/playlists" "github.com/navidrome/navidrome/model" @@ -22,9 +21,10 @@ var _ = Describe("Missing Files Endpoint", func() { var token string BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.SessionTimeout = time.Minute - conf.Server.EnableSharing = false + conf.Update(func(c *conf.Options) { + c.SessionTimeout = time.Minute + c.EnableSharing = false + }) mfRepo := tests.CreateMockMediaFileRepo() mfRepo.SetData(model.MediaFiles{ diff --git a/server/nativeapi/native_api.go b/server/nativeapi/native_api.go index 97ad14be2..5d8ac9539 100644 --- a/server/nativeapi/native_api.go +++ b/server/nativeapi/native_api.go @@ -73,11 +73,11 @@ func (api *Router) routes() http.Handler { api.addArtistRoute(r) rx(r, "/genre", api.ds.Genre(), false) rx(r, "/player", api.ds.Player(), true) - rx(r, "/transcoding", api.ds.Transcoding(), conf.Server.EnableTranscodingConfig) + rx(r, "/transcoding", api.ds.Transcoding(), conf.Server().EnableTranscodingConfig) api.addRadioRoute(r) rx(r, "/tag", api.ds.Tag(), false) rx(r, "/scrobble", api.ds.Scrobble(), false) - if conf.Server.EnableSharing { + if conf.Server().EnableSharing { rx(r, "/share", api.share.Repository(), true) } @@ -211,13 +211,13 @@ func writeDeleteManyResponse(w http.ResponseWriter, r *http.Request, ids []strin } func (api *Router) addInspectRoute(r chi.Router) { - if conf.Server.Inspect.Enabled { + if conf.Server().Inspect.Enabled { r.Group(func(r chi.Router) { - if conf.Server.Inspect.MaxRequests > 0 { - log.Debug("Throttling inspect", "maxRequests", conf.Server.Inspect.MaxRequests, - "backlogLimit", conf.Server.Inspect.BacklogLimit, "backlogTimeout", - conf.Server.Inspect.BacklogTimeout) - r.Use(middleware.ThrottleBacklog(conf.Server.Inspect.MaxRequests, conf.Server.Inspect.BacklogLimit, time.Duration(conf.Server.Inspect.BacklogTimeout))) + if conf.Server().Inspect.MaxRequests > 0 { + log.Debug("Throttling inspect", "maxRequests", conf.Server().Inspect.MaxRequests, + "backlogLimit", conf.Server().Inspect.BacklogLimit, "backlogTimeout", + conf.Server().Inspect.BacklogTimeout) + r.Use(middleware.ThrottleBacklog(conf.Server().Inspect.MaxRequests, conf.Server().Inspect.BacklogLimit, time.Duration(conf.Server().Inspect.BacklogTimeout))) } r.Get("/inspect", inspect(api.ds)) }) @@ -225,7 +225,7 @@ func (api *Router) addInspectRoute(r chi.Router) { } func (api *Router) addConfigRoute(r chi.Router) { - if conf.Server.DevUIShowConfig { + if conf.Server().DevUIShowConfig { r.Get("/config/*", getConfig) } } @@ -239,7 +239,7 @@ func (api *Router) addKeepAliveRoute(r chi.Router) { func (api *Router) addInsightsRoute(r chi.Router) { r.Get("/insights/*", func(w http.ResponseWriter, r *http.Request) { last, success := api.insights.LastRun(r.Context()) - if conf.Server.EnableInsightsCollector { + if conf.Server().EnableInsightsCollector { _, _ = w.Write([]byte(`{"id":"insights_status", "lastRun":"` + last.Format("2006-01-02 15:04:05") + `", "success":` + strconv.FormatBool(success) + `}`)) //nolint:gosec } else { _, _ = w.Write([]byte(`{"id":"insights_status", "lastRun":"disabled", "success":false}`)) diff --git a/server/nativeapi/native_api_song_test.go b/server/nativeapi/native_api_song_test.go index f151b1d72..a6f0aec14 100644 --- a/server/nativeapi/native_api_song_test.go +++ b/server/nativeapi/native_api_song_test.go @@ -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/auth" "github.com/navidrome/navidrome/core/playlists" @@ -35,9 +34,10 @@ var _ = Describe("Song Endpoints", func() { BeforeEach(func() { ctx = GinkgoT().Context() - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableSharing = false - conf.Server.SessionTimeout = time.Minute + conf.Update(func(c *conf.Options) { + c.EnableSharing = false + c.SessionTimeout = time.Minute + }) // Setup mock repositories mfRepo = tests.CreateMockMediaFileRepo() diff --git a/server/nativeapi/native_api_suite_test.go b/server/nativeapi/native_api_suite_test.go index 70cd7b288..3ea5a1701 100644 --- a/server/nativeapi/native_api_suite_test.go +++ b/server/nativeapi/native_api_suite_test.go @@ -3,6 +3,7 @@ package nativeapi 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 TestNativeApi(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Native RESTful API Suite") } + +var _ = configtest.RestoreAfterEachSpec() diff --git a/server/nativeapi/playlists_test.go b/server/nativeapi/playlists_test.go index 82e3bc86a..2b6449dab 100644 --- a/server/nativeapi/playlists_test.go +++ b/server/nativeapi/playlists_test.go @@ -11,7 +11,6 @@ import ( "github.com/deluan/rest" "github.com/go-chi/chi/v5" "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/core/playlists" @@ -24,13 +23,10 @@ import ( ) var _ = Describe("Playlist Image Endpoints", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) DescribeTable("uploadPlaylistImage guard", func(enableArtworkUpload, isAdmin bool, expectedStatus int) { - conf.Server.EnableArtworkUpload = enableArtworkUpload + conf.Update(func(c *conf.Options) { c.EnableArtworkUpload = enableArtworkUpload }) handler := uploadPlaylistImage(&mockPlaylistsService{}) req := httptest.NewRequest("POST", "/playlist/pls-1/image", nil) @@ -49,7 +45,7 @@ var _ = Describe("Playlist Image Endpoints", func() { DescribeTable("deletePlaylistImage guard", func(enableArtworkUpload, isAdmin bool, expectedStatus int) { - conf.Server.EnableArtworkUpload = enableArtworkUpload + conf.Update(func(c *conf.Options) { c.EnableArtworkUpload = enableArtworkUpload }) handler := deletePlaylistImage(&mockPlaylistsService{}) req := httptest.NewRequest("DELETE", "/playlist/pls-1/image", nil) @@ -76,9 +72,10 @@ var _ = Describe("Playlist Tracks Endpoint", func() { ) BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableSharing = false - conf.Server.SessionTimeout = time.Minute + conf.Update(func(c *conf.Options) { + c.EnableSharing = false + c.SessionTimeout = time.Minute + }) plsSvc = &mockPlaylistsService{} userRepo = tests.CreateMockUserRepo() diff --git a/server/nativeapi/plugin.go b/server/nativeapi/plugin.go index d34bf23fc..1c067f6e2 100644 --- a/server/nativeapi/plugin.go +++ b/server/nativeapi/plugin.go @@ -44,7 +44,7 @@ func (api *Router) rescanPlugins(w http.ResponseWriter, r *http.Request) { // Middleware to check if plugins feature is enabled func pluginsEnabledMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !conf.Server.Plugins.Enabled { + if !conf.Server().Plugins.Enabled { http.Error(w, "Not found", http.StatusNotFound) return } diff --git a/server/nativeapi/plugin_test.go b/server/nativeapi/plugin_test.go index c18d61e65..632a8bd2b 100644 --- a/server/nativeapi/plugin_test.go +++ b/server/nativeapi/plugin_test.go @@ -9,7 +9,6 @@ import ( "net/http/httptest" "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/core/playlists" @@ -31,9 +30,10 @@ var _ = Describe("Plugin API", func() { BeforeEach(func() { ctx = GinkgoT().Context() - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableSharing = false - conf.Server.Plugins.Enabled = true + conf.Update(func(c *conf.Options) { + c.EnableSharing = false + c.Plugins.Enabled = true + }) ds = &tests.MockDataStore{} mockManager = &tests.MockPluginManager{} auth.Init(ds) @@ -80,7 +80,7 @@ var _ = Describe("Plugin API", func() { Context("when plugins are disabled", func() { BeforeEach(func() { - conf.Server.Plugins.Enabled = false + conf.Update(func(c *conf.Options) { c.Plugins.Enabled = false }) }) It("returns 404 for all plugin endpoints", func() { diff --git a/server/nativeapi/quickconnect.go b/server/nativeapi/quickconnect.go index 61d402cc5..e2ce39161 100644 --- a/server/nativeapi/quickconnect.go +++ b/server/nativeapi/quickconnect.go @@ -26,8 +26,8 @@ func (api *Router) addQuickConnectRoute(r chi.Router) { } r.Route("/quickconnect", func(r chi.Router) { // Throttled like login so a signed-in user cannot enumerate other people's pending codes. - if conf.Server.AuthRequestLimit > 0 { - r.Use(server.ClientIPRateLimiter(conf.Server.AuthRequestLimit, conf.Server.AuthWindowLength)) + if conf.Server().AuthRequestLimit > 0 { + r.Use(server.ClientIPRateLimiter(conf.Server().AuthRequestLimit, conf.Server().AuthWindowLength)) } r.Get("/", lookupQuickConnect(api.quickConnect)) r.Post("/authorize", authorizeQuickConnect(api.quickConnect)) diff --git a/server/nativeapi/quickconnect_test.go b/server/nativeapi/quickconnect_test.go index f2f06f0f3..a36f7d24d 100644 --- a/server/nativeapi/quickconnect_test.go +++ b/server/nativeapi/quickconnect_test.go @@ -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/core/quickconnect" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -109,9 +108,10 @@ var _ = Describe("Quick Connect endpoints", func() { } BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Jellyfin.Enabled = true - conf.Server.Jellyfin.QuickConnect = true + conf.Update(func(c *conf.Options) { + c.Jellyfin.Enabled = true + c.Jellyfin.QuickConnect = true + }) }) It("mounts the routes when Jellyfin Quick Connect is on", func() { @@ -119,8 +119,10 @@ var _ = Describe("Quick Connect endpoints", func() { }) It("rate-limits code attempts when a login limit is configured", func() { - conf.Server.AuthRequestLimit = 2 - conf.Server.AuthWindowLength = time.Minute + conf.Update(func(c *conf.Options) { + c.AuthRequestLimit = 2 + c.AuthWindowLength = time.Minute + }) r := chi.NewRouter() (&Router{quickConnect: qc}).addQuickConnectRoute(r) attempt := func() int { @@ -136,12 +138,12 @@ var _ = Describe("Quick Connect endpoints", func() { }) It("skips the routes when the Jellyfin API is off", func() { - conf.Server.Jellyfin.Enabled = false + conf.Update(func(c *conf.Options) { c.Jellyfin.Enabled = false }) Expect(serve()).To(Equal(http.StatusNotFound)) }) It("skips the routes when Quick Connect is off", func() { - conf.Server.Jellyfin.QuickConnect = false + conf.Update(func(c *conf.Options) { c.Jellyfin.QuickConnect = false }) Expect(serve()).To(Equal(http.StatusNotFound)) }) }) diff --git a/server/nativeapi/user_password_token_refresh_test.go b/server/nativeapi/user_password_token_refresh_test.go index 81f28893f..ddd19f49c 100644 --- a/server/nativeapi/user_password_token_refresh_test.go +++ b/server/nativeapi/user_password_token_refresh_test.go @@ -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" "github.com/navidrome/navidrome/core/auth" @@ -36,12 +35,13 @@ var _ = Describe("PUT /user/{id}: token refresh on self password change", func() BeforeEach(func() { ctx = GinkgoT().Context() + conf.Update(func(c *conf.Options) { + c.EnableUserEditing = true + c.EnableSharing = false + c.SessionTimeout = time.Hour + c.DbPath = filepath.Join(GinkgoT().TempDir(), "nativeapi-user-refresh.db") + "?_journal_mode=WAL" + }) // db.Db() is a process-wide singleton that this DeferCleanup closes for the whole binary; keep this the only real-DB spec in this package. - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableUserEditing = true - conf.Server.EnableSharing = false - conf.Server.SessionTimeout = time.Hour - conf.Server.DbPath = filepath.Join(GinkgoT().TempDir(), "nativeapi-user-refresh.db") + "?_journal_mode=WAL" DeferCleanup(db.Init(GinkgoT().Context())) ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} diff --git a/server/public/handle_shares.go b/server/public/handle_shares.go index 367bff501..6fc329fd8 100644 --- a/server/public/handle_shares.go +++ b/server/public/handle_shares.go @@ -82,7 +82,7 @@ func checkShareError(ctx context.Context, w http.ResponseWriter, err error, id s func (pub *Router) mapShareInfo(r *http.Request, s model.Share) *model.Share { s.URL = ShareURL(r.Context(), s.ID) - s.ImageURL = publicurl.ImageURL(r.Context(), s.CoverArtID(), conf.Server.UICoverArtSize) + s.ImageURL = publicurl.ImageURL(r.Context(), s.CoverArtID(), conf.Server().UICoverArtSize) for i := range s.Tracks { s.Tracks[i].ID = encodeMediafileShare(s, s.Tracks[i].ID) } diff --git a/server/public/handle_streams_test.go b/server/public/handle_streams_test.go index 965bc7e05..e8badbae8 100644 --- a/server/public/handle_streams_test.go +++ b/server/public/handle_streams_test.go @@ -3,8 +3,10 @@ package public import ( "context" "errors" + "io" "net/http" "net/http/httptest" + "strings" "time" "github.com/go-chi/jwtauth/v5" @@ -17,13 +19,17 @@ import ( ) type mockStreamer struct { - req stream.Request - called bool + req stream.Request + called bool + newStream func(*model.MediaFile) *stream.Stream } -func (m *mockStreamer) NewStream(_ context.Context, _ *model.MediaFile, r stream.Request) (*stream.Stream, error) { +func (m *mockStreamer) NewStream(_ context.Context, mf *model.MediaFile, r stream.Request) (*stream.Stream, error) { m.called = true m.req = r + if m.newStream != nil { + return m.newStream(mf), nil + } return nil, errors.New("mock: not implemented") } @@ -211,6 +217,24 @@ var _ = Describe("handleStream", func() { Expect(streamer.called).To(BeTrue()) }) + It("returns 200 on HEAD for a transcode that is not cached yet", func() { + shareOwnedBy( + model.User{ID: "owner1", UserName: "owner1", IsAdmin: true}, + model.MediaFile{ID: "mf-123", Title: "Test Song"}, + ) + streamer.newStream = func(mf *model.MediaFile) *stream.Stream { + return stream.NewStream(mf, "mp3", 192, io.NopCloser(strings.NewReader("transcoded audio"))) + } + + claims := auth.Claims{ID: "mf-123", Format: "mp3", BitRate: 192, ShareID: "share123"} + token, _ := auth.CreateExpiringPublicToken(time.Now().Add(time.Hour), claims) + r := httptest.NewRequest(http.MethodHead, "/public/s/token?%3Aid="+token, nil) + w := httptest.NewRecorder() + pub.handleStream(w, r) + + Expect(w.Code).To(Equal(http.StatusOK)) + }) + It("returns 400 for an expired token", func() { claims := auth.Claims{ID: "mf-123", ShareID: "share123"} token, _ := auth.CreateExpiringPublicToken(time.Now().Add(-time.Hour), claims) diff --git a/server/public/public.go b/server/public/public.go index 8239ef927..a5f10e87f 100644 --- a/server/public/public.go +++ b/server/public/public.go @@ -30,7 +30,7 @@ type Router struct { func New(ds model.DataStore, artwork artwork.Artwork, streamer stream.MediaStreamer, decider stream.TranscodeDecider, share core.Share, archiver core.Archiver) *Router { p := &Router{ds: ds, artwork: artwork, streamer: streamer, decider: decider, share: share, archiver: archiver} - shareRoot := path.Join(conf.Server.BasePath, consts.URLPathPublic) + shareRoot := path.Join(conf.Server().BasePath, consts.URLPathPublic) p.assetsHandler = http.StripPrefix(shareRoot, http.FileServer(http.FS(ui.BuildAssets()))) p.Handler = p.routes() @@ -43,13 +43,13 @@ func (pub *Router) routes() http.Handler { r.Group(func(r chi.Router) { r.Use(server.URLParamsMiddleware) r.Group(func(r chi.Router) { - r.Use(server.ThrottleBacklog(conf.Server.DevArtworkMaxRequests, conf.Server.DevArtworkThrottleBacklogLimit, - conf.Server.DevArtworkThrottleBacklogTimeout)) + r.Use(server.ThrottleBacklog(conf.Server().DevArtworkMaxRequests, conf.Server().DevArtworkThrottleBacklogLimit, + conf.Server().DevArtworkThrottleBacklogTimeout)) r.HandleFunc("/img/{id}", pub.handleImages) }) - if conf.Server.EnableSharing { + if conf.Server().EnableSharing { r.HandleFunc("/s/{id}", pub.handleStream) - if conf.Server.EnableDownloads { + if conf.Server().EnableDownloads { r.HandleFunc("/d/{id}", pub.handleDownloads) } r.HandleFunc("/{id}/m3u", pub.handleM3U) diff --git a/server/serve_index.go b/server/serve_index.go index 167197403..4552a76ec 100644 --- a/server/serve_index.go +++ b/server/serve_index.go @@ -44,49 +44,49 @@ func serveIndex(ds model.DataStore, fs fs.FS, shareInfo *model.Share) http.Handl "version": consts.Version, "firstTime": firstTime, "variousArtistsId": consts.VariousArtistsID, - "baseURL": str.SanitizeText(strings.TrimSuffix(conf.Server.BasePath, "/")), - "loginBackgroundURL": str.SanitizeText(conf.Server.UILoginBackgroundURL), - "welcomeMessage": str.SanitizeHTML(conf.Server.UIWelcomeMessage), - "maxSidebarPlaylists": conf.Server.MaxSidebarPlaylists, - "enableTranscodingConfig": conf.Server.EnableTranscodingConfig, - "enableDownloads": conf.Server.EnableDownloads, - "enableFavourites": conf.Server.EnableFavourites, - "enableStarRating": conf.Server.EnableStarRating, - "defaultTheme": conf.Server.DefaultTheme, - "defaultLanguage": conf.Server.DefaultLanguage, - "defaultUIVolume": conf.Server.DefaultUIVolume, - "uiSearchDebounceMs": conf.Server.UISearchDebounceMs, - "uiCoverArtSize": conf.Server.UICoverArtSize, - "enableCoverAnimation": conf.Server.EnableCoverAnimation, - "pidAlbum": conf.Server.PID.Album, - "pidTrack": conf.Server.PID.Track, - "enableNowPlaying": conf.Server.EnableNowPlaying, - "playbackReportIntervalMs": conf.Server.UIPlaybackReportInterval.Milliseconds(), - "gaTrackingId": conf.Server.GATrackingID, + "baseURL": str.SanitizeText(strings.TrimSuffix(conf.Server().BasePath, "/")), + "loginBackgroundURL": str.SanitizeText(conf.Server().UILoginBackgroundURL), + "welcomeMessage": str.SanitizeHTML(conf.Server().UIWelcomeMessage), + "maxSidebarPlaylists": conf.Server().MaxSidebarPlaylists, + "enableTranscodingConfig": conf.Server().EnableTranscodingConfig, + "enableDownloads": conf.Server().EnableDownloads, + "enableFavourites": conf.Server().EnableFavourites, + "enableStarRating": conf.Server().EnableStarRating, + "defaultTheme": conf.Server().DefaultTheme, + "defaultLanguage": conf.Server().DefaultLanguage, + "defaultUIVolume": conf.Server().DefaultUIVolume, + "uiSearchDebounceMs": conf.Server().UISearchDebounceMs, + "uiCoverArtSize": conf.Server().UICoverArtSize, + "enableCoverAnimation": conf.Server().EnableCoverAnimation, + "pidAlbum": conf.Server().PID.Album, + "pidTrack": conf.Server().PID.Track, + "enableNowPlaying": conf.Server().EnableNowPlaying, + "playbackReportIntervalMs": conf.Server().UIPlaybackReportInterval.Milliseconds(), + "gaTrackingId": conf.Server().GATrackingID, "losslessFormats": strings.ToUpper(strings.Join(mime.LosslessFormats, ",")), - "devActivityPanel": conf.Server.DevActivityPanel, - "enableUserEditing": conf.Server.EnableUserEditing, - "enableArtworkUpload": conf.Server.EnableArtworkUpload, - "enableSharing": conf.Server.EnableSharing, - "shareURL": conf.Server.ShareURL, - "defaultDownloadableShare": conf.Server.DefaultDownloadableShare, - "devSidebarPlaylists": conf.Server.DevSidebarPlaylists, - "lastFMEnabled": conf.Server.LastFM.Enabled, - "devShowArtistPage": conf.Server.DevShowArtistPage, - "devUIShowConfig": conf.Server.DevUIShowConfig, - "devNewEventStream": conf.Server.DevNewEventStream, - "listenBrainzEnabled": conf.Server.ListenBrainz.Enabled, - "enableExternalServices": conf.Server.EnableExternalServices, - "enableReplayGain": conf.Server.EnableReplayGain, + "devActivityPanel": conf.Server().DevActivityPanel, + "enableUserEditing": conf.Server().EnableUserEditing, + "enableArtworkUpload": conf.Server().EnableArtworkUpload, + "enableSharing": conf.Server().EnableSharing, + "shareURL": conf.Server().ShareURL, + "defaultDownloadableShare": conf.Server().DefaultDownloadableShare, + "devSidebarPlaylists": conf.Server().DevSidebarPlaylists, + "lastFMEnabled": conf.Server().LastFM.Enabled, + "devShowArtistPage": conf.Server().DevShowArtistPage, + "devUIShowConfig": conf.Server().DevUIShowConfig, + "devNewEventStream": conf.Server().DevNewEventStream, + "listenBrainzEnabled": conf.Server().ListenBrainz.Enabled, + "enableExternalServices": conf.Server().EnableExternalServices, + "enableReplayGain": conf.Server().EnableReplayGain, "enableQuickConnect": quickconnect.Enabled(), - "defaultDownsamplingFormat": conf.Server.DefaultDownsamplingFormat, + "defaultDownsamplingFormat": conf.Server().DefaultDownsamplingFormat, "separator": string(os.PathSeparator), - "enableInspect": conf.Server.Inspect.Enabled, - "pluginsEnabled": conf.Server.Plugins.Enabled, - "extAuthLogoutURL": conf.Server.ExtAuth.LogoutURL, + "enableInspect": conf.Server().Inspect.Enabled, + "pluginsEnabled": conf.Server().Plugins.Enabled, + "extAuthLogoutURL": conf.Server().ExtAuth.LogoutURL, } - if strings.HasPrefix(conf.Server.UILoginBackgroundURL, "/") { - appConfig["loginBackgroundURL"] = path.Join(conf.Server.BasePath, conf.Server.UILoginBackgroundURL) + if strings.HasPrefix(conf.Server().UILoginBackgroundURL, "/") { + appConfig["loginBackgroundURL"] = path.Join(conf.Server().BasePath, conf.Server().UILoginBackgroundURL) } auth := handleLoginFromHeaders(ds, r) if auth != nil { diff --git a/server/serve_index_test.go b/server/serve_index_test.go index 277513768..b84738d22 100644 --- a/server/serve_index_test.go +++ b/server/serve_index_test.go @@ -13,7 +13,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/conf/mime" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/model" @@ -29,7 +28,6 @@ var _ = Describe("serveIndex", func() { BeforeEach(func() { ds = &tests.MockDataStore{MockedUser: mockUser} - DeferCleanup(configtest.SetupConfig()) }) It("adds app_config to index.html", func() { @@ -66,8 +64,8 @@ var _ = Describe("serveIndex", func() { }) DescribeTable("sets configuration values", - func(configSetter func(), configKey string, expectedValue any) { - configSetter() + func(configSetter func(*conf.Options), configKey string, expectedValue any) { + conf.Update(configSetter) r := httptest.NewRequest("GET", "/index.html", nil) w := httptest.NewRecorder() @@ -76,46 +74,48 @@ var _ = Describe("serveIndex", func() { config := extractAppConfig(w.Body.String()) Expect(config).To(HaveKeyWithValue(configKey, expectedValue)) }, - Entry("baseURL", func() { conf.Server.BasePath = "base_url_test" }, "baseURL", "base_url_test"), - Entry("welcomeMessage", func() { conf.Server.UIWelcomeMessage = "Hello" }, "welcomeMessage", "Hello"), - Entry("maxSidebarPlaylists", func() { conf.Server.MaxSidebarPlaylists = 42 }, "maxSidebarPlaylists", float64(42)), - Entry("enableTranscodingConfig", func() { conf.Server.EnableTranscodingConfig = true }, "enableTranscodingConfig", true), - Entry("enableDownloads", func() { conf.Server.EnableDownloads = true }, "enableDownloads", true), - Entry("enableFavourites", func() { conf.Server.EnableFavourites = true }, "enableFavourites", true), - Entry("enableStarRating", func() { conf.Server.EnableStarRating = true }, "enableStarRating", true), - Entry("defaultTheme", func() { conf.Server.DefaultTheme = "Light" }, "defaultTheme", "Light"), - Entry("defaultLanguage", func() { conf.Server.DefaultLanguage = "pt" }, "defaultLanguage", "pt"), - Entry("defaultUIVolume", func() { conf.Server.DefaultUIVolume = 45 }, "defaultUIVolume", float64(45)), - Entry("uiSearchDebounceMs", func() { conf.Server.UISearchDebounceMs = 500 }, "uiSearchDebounceMs", float64(500)), - Entry("uiCoverArtSize", func() { conf.Server.UICoverArtSize = 300 }, "uiCoverArtSize", float64(300)), - Entry("enableCoverAnimation", func() { conf.Server.EnableCoverAnimation = true }, "enableCoverAnimation", true), - Entry("pidAlbum", func() { conf.Server.PID.Album = "folder" }, "pidAlbum", "folder"), - Entry("pidTrack", func() { conf.Server.PID.Track = "title" }, "pidTrack", "title"), - Entry("enableNowPlaying", func() { conf.Server.EnableNowPlaying = true }, "enableNowPlaying", true), - Entry("gaTrackingId", func() { conf.Server.GATrackingID = "UA-12345" }, "gaTrackingId", "UA-12345"), - Entry("defaultDownloadableShare", func() { conf.Server.DefaultDownloadableShare = true }, "defaultDownloadableShare", true), - Entry("devSidebarPlaylists", func() { conf.Server.DevSidebarPlaylists = true }, "devSidebarPlaylists", true), - Entry("lastFMEnabled", func() { conf.Server.LastFM.Enabled = true }, "lastFMEnabled", true), - Entry("devShowArtistPage", func() { conf.Server.DevShowArtistPage = true }, "devShowArtistPage", true), - Entry("devUIShowConfig", func() { conf.Server.DevUIShowConfig = true }, "devUIShowConfig", true), - Entry("listenBrainzEnabled", func() { conf.Server.ListenBrainz.Enabled = true }, "listenBrainzEnabled", true), - Entry("enableReplayGain", func() { conf.Server.EnableReplayGain = true }, "enableReplayGain", true), - Entry("enableQuickConnect", func() { conf.Server.Jellyfin.Enabled = true; conf.Server.Jellyfin.QuickConnect = true }, "enableQuickConnect", true), - Entry("enableQuickConnect without the Jellyfin API", func() { conf.Server.Jellyfin.Enabled = false; conf.Server.Jellyfin.QuickConnect = true }, "enableQuickConnect", false), - Entry("enableExternalServices", func() { conf.Server.EnableExternalServices = true }, "enableExternalServices", true), - Entry("devActivityPanel", func() { conf.Server.DevActivityPanel = true }, "devActivityPanel", true), - Entry("shareURL", func() { conf.Server.ShareURL = "https://share.example.com" }, "shareURL", "https://share.example.com"), - Entry("enableInspect", func() { conf.Server.Inspect.Enabled = true }, "enableInspect", true), - Entry("defaultDownsamplingFormat", func() { conf.Server.DefaultDownsamplingFormat = "mp3" }, "defaultDownsamplingFormat", "mp3"), - Entry("enableUserEditing", func() { conf.Server.EnableUserEditing = false }, "enableUserEditing", false), - Entry("enableSharing", func() { conf.Server.EnableSharing = true }, "enableSharing", true), - Entry("devNewEventStream", func() { conf.Server.DevNewEventStream = true }, "devNewEventStream", true), - Entry("extAuthLogoutURL", func() { conf.Server.ExtAuth.LogoutURL = "https://auth.example.com/logout" }, "extAuthLogoutURL", "https://auth.example.com/logout"), - Entry("playbackReportIntervalMs", func() { conf.Server.UIPlaybackReportInterval = 30 * time.Second }, "playbackReportIntervalMs", float64(30000)), + Entry("baseURL", func(c *conf.Options) { c.BasePath = "base_url_test" }, "baseURL", "base_url_test"), + Entry("welcomeMessage", func(c *conf.Options) { c.UIWelcomeMessage = "Hello" }, "welcomeMessage", "Hello"), + Entry("maxSidebarPlaylists", func(c *conf.Options) { c.MaxSidebarPlaylists = 42 }, "maxSidebarPlaylists", float64(42)), + Entry("enableTranscodingConfig", func(c *conf.Options) { c.EnableTranscodingConfig = true }, "enableTranscodingConfig", true), + Entry("enableDownloads", func(c *conf.Options) { c.EnableDownloads = true }, "enableDownloads", true), + Entry("enableFavourites", func(c *conf.Options) { c.EnableFavourites = true }, "enableFavourites", true), + Entry("enableStarRating", func(c *conf.Options) { c.EnableStarRating = true }, "enableStarRating", true), + Entry("defaultTheme", func(c *conf.Options) { c.DefaultTheme = "Light" }, "defaultTheme", "Light"), + Entry("defaultLanguage", func(c *conf.Options) { c.DefaultLanguage = "pt" }, "defaultLanguage", "pt"), + Entry("defaultUIVolume", func(c *conf.Options) { c.DefaultUIVolume = 45 }, "defaultUIVolume", float64(45)), + Entry("uiSearchDebounceMs", func(c *conf.Options) { c.UISearchDebounceMs = 500 }, "uiSearchDebounceMs", float64(500)), + Entry("uiCoverArtSize", func(c *conf.Options) { c.UICoverArtSize = 300 }, "uiCoverArtSize", float64(300)), + Entry("enableCoverAnimation", func(c *conf.Options) { c.EnableCoverAnimation = true }, "enableCoverAnimation", true), + Entry("pidAlbum", func(c *conf.Options) { c.PID.Album = "folder" }, "pidAlbum", "folder"), + Entry("pidTrack", func(c *conf.Options) { c.PID.Track = "title" }, "pidTrack", "title"), + Entry("enableNowPlaying", func(c *conf.Options) { c.EnableNowPlaying = true }, "enableNowPlaying", true), + Entry("gaTrackingId", func(c *conf.Options) { c.GATrackingID = "UA-12345" }, "gaTrackingId", "UA-12345"), + Entry("defaultDownloadableShare", func(c *conf.Options) { c.DefaultDownloadableShare = true }, "defaultDownloadableShare", true), + Entry("devSidebarPlaylists", func(c *conf.Options) { c.DevSidebarPlaylists = true }, "devSidebarPlaylists", true), + Entry("lastFMEnabled", func(c *conf.Options) { c.LastFM.Enabled = true }, "lastFMEnabled", true), + Entry("devShowArtistPage", func(c *conf.Options) { c.DevShowArtistPage = true }, "devShowArtistPage", true), + Entry("devUIShowConfig", func(c *conf.Options) { c.DevUIShowConfig = true }, "devUIShowConfig", true), + Entry("listenBrainzEnabled", func(c *conf.Options) { c.ListenBrainz.Enabled = true }, "listenBrainzEnabled", true), + Entry("enableReplayGain", func(c *conf.Options) { c.EnableReplayGain = true }, "enableReplayGain", true), + Entry("enableQuickConnect", func(c *conf.Options) { c.Jellyfin.Enabled = true; c.Jellyfin.QuickConnect = true }, "enableQuickConnect", true), + Entry("enableQuickConnect without the Jellyfin API", func(c *conf.Options) { c.Jellyfin.Enabled = false; c.Jellyfin.QuickConnect = true }, "enableQuickConnect", false), + Entry("enableExternalServices", func(c *conf.Options) { c.EnableExternalServices = true }, "enableExternalServices", true), + Entry("devActivityPanel", func(c *conf.Options) { c.DevActivityPanel = true }, "devActivityPanel", true), + Entry("shareURL", func(c *conf.Options) { c.ShareURL = "https://share.example.com" }, "shareURL", "https://share.example.com"), + Entry("enableInspect", func(c *conf.Options) { c.Inspect.Enabled = true }, "enableInspect", true), + Entry("defaultDownsamplingFormat", func(c *conf.Options) { c.DefaultDownsamplingFormat = "mp3" }, "defaultDownsamplingFormat", "mp3"), + Entry("enableUserEditing", func(c *conf.Options) { c.EnableUserEditing = false }, "enableUserEditing", false), + Entry("enableSharing", func(c *conf.Options) { c.EnableSharing = true }, "enableSharing", true), + Entry("devNewEventStream", func(c *conf.Options) { c.DevNewEventStream = true }, "devNewEventStream", true), + Entry("extAuthLogoutURL", func(c *conf.Options) { c.ExtAuth.LogoutURL = "https://auth.example.com/logout" }, "extAuthLogoutURL", "https://auth.example.com/logout"), + Entry("playbackReportIntervalMs", func(c *conf.Options) { c.UIPlaybackReportInterval = 30 * time.Second }, "playbackReportIntervalMs", float64(30000)), ) It("sanitizes entity-encoded welcomeMessage as html", func() { - conf.Server.UIWelcomeMessage = `<img src=x onerror=alert(1)><b>Hello</b>` + conf.Update(func(c *conf.Options) { + c.UIWelcomeMessage = `<img src=x onerror=alert(1)><b>Hello</b>` + }) r := httptest.NewRequest("GET", "/index.html", nil) w := httptest.NewRecorder() @@ -147,11 +147,11 @@ var _ = Describe("serveIndex", func() { Describe("loginBackgroundURL", func() { Context("empty BaseURL", func() { BeforeEach(func() { - conf.Server.BasePath = "/" + conf.Update(func(c *conf.Options) { c.BasePath = "/" }) }) When("it is the default URL", func() { It("points to the default URL", func() { - conf.Server.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURL + conf.Update(func(c *conf.Options) { c.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURL }) r := httptest.NewRequest("GET", "/index.html", nil) w := httptest.NewRecorder() @@ -163,7 +163,7 @@ var _ = Describe("serveIndex", func() { }) When("it is the default offline URL", func() { It("points to the offline URL", func() { - conf.Server.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURLOffline + conf.Update(func(c *conf.Options) { c.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURLOffline }) r := httptest.NewRequest("GET", "/index.html", nil) w := httptest.NewRecorder() @@ -175,7 +175,7 @@ var _ = Describe("serveIndex", func() { }) When("it is a custom URL", func() { It("points to the offline URL", func() { - conf.Server.UILoginBackgroundURL = "https://example.com/images/1.jpg" + conf.Update(func(c *conf.Options) { c.UILoginBackgroundURL = "https://example.com/images/1.jpg" }) r := httptest.NewRequest("GET", "/index.html", nil) w := httptest.NewRecorder() @@ -188,11 +188,11 @@ var _ = Describe("serveIndex", func() { }) Context("with a BaseURL", func() { BeforeEach(func() { - conf.Server.BasePath = "/music" + conf.Update(func(c *conf.Options) { c.BasePath = "/music" }) }) When("it is the default URL", func() { It("points to the default URL with BaseURL prefix", func() { - conf.Server.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURL + conf.Update(func(c *conf.Options) { c.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURL }) r := httptest.NewRequest("GET", "/index.html", nil) w := httptest.NewRecorder() @@ -204,7 +204,7 @@ var _ = Describe("serveIndex", func() { }) When("it is the default offline URL", func() { It("points to the offline URL", func() { - conf.Server.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURLOffline + conf.Update(func(c *conf.Options) { c.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURLOffline }) r := httptest.NewRequest("GET", "/index.html", nil) w := httptest.NewRecorder() @@ -216,7 +216,7 @@ var _ = Describe("serveIndex", func() { }) When("it is a custom URL", func() { It("points to the offline URL", func() { - conf.Server.UILoginBackgroundURL = "https://example.com/images/1.jpg" + conf.Update(func(c *conf.Options) { c.UILoginBackgroundURL = "https://example.com/images/1.jpg" }) r := httptest.NewRequest("GET", "/index.html", nil) w := httptest.NewRecorder() diff --git a/server/server.go b/server/server.go index 7e7e2f6bd..e9b6d20cf 100644 --- a/server/server.go +++ b/server/server.go @@ -48,7 +48,7 @@ func New(ds model.DataStore, broker events.Broker, insights metrics.Insights) *S } func (s *Server) MountRouter(description, urlPath string, subRouter http.Handler) { - urlPath = path.Join(conf.Server.BasePath, urlPath) + urlPath = path.Join(conf.Server().BasePath, urlPath) log.Info(fmt.Sprintf("Mounting %s routes", description), "path", urlPath) s.router.Group(func(r chi.Router) { r.Mount(urlPath, subRouter) @@ -81,7 +81,7 @@ func (s *Server) Run(ctx context.Context, addr string, port int, tlsCert string, var err error if after, ok := strings.CutPrefix(addr, "unix:"); ok { socketPath := after - listener, err = createUnixSocketFile(socketPath, conf.Server.UnixSocketPerm) + listener, err = createUnixSocketFile(socketPath, conf.Server().UnixSocketPerm) if err != nil { return err } @@ -164,7 +164,7 @@ func createUnixSocketFile(socketPath string, socketPerm string) (net.Listener, e } func (s *Server) initRoutes() { - s.appRoot = path.Join(conf.Server.BasePath, consts.URLPathUI) + s.appRoot = path.Join(conf.Server().BasePath, consts.URLPathUI) r := chi.NewRouter() @@ -184,12 +184,12 @@ func (s *Server) initRoutes() { } // Mount the Native API /events endpoint with all default middlewares, adding the authentication middlewares - if conf.Server.DevActivityPanel { + if conf.Server().DevActivityPanel { r.Group(func(r chi.Router) { r.Use(defaultMiddlewares...) r.Use(Authenticator(s.ds)) r.Use(JWTRefresher) - r.Handle(path.Join(conf.Server.BasePath, consts.URLPathNativeAPI, "events"), s.broker) + r.Handle(path.Join(conf.Server().BasePath, consts.URLPathNativeAPI, "events"), s.broker) }) } @@ -203,13 +203,13 @@ func (s *Server) initRoutes() { func (s *Server) mountAuthenticationRoutes() chi.Router { r := s.router - return r.Route(path.Join(conf.Server.BasePath, "/auth"), func(r chi.Router) { + return r.Route(path.Join(conf.Server().BasePath, "/auth"), func(r chi.Router) { r.Use(LimitLoginBody) - if conf.Server.AuthRequestLimit > 0 { - log.Info("Login rate limit set", "requestLimit", conf.Server.AuthRequestLimit, - "windowLength", conf.Server.AuthWindowLength) + if conf.Server().AuthRequestLimit > 0 { + log.Info("Login rate limit set", "requestLimit", conf.Server().AuthRequestLimit, + "windowLength", conf.Server().AuthWindowLength) - rateLimiter := ClientIPRateLimiter(conf.Server.AuthRequestLimit, conf.Server.AuthWindowLength) + rateLimiter := ClientIPRateLimiter(conf.Server().AuthRequestLimit, conf.Server().AuthWindowLength) r.With(rateLimiter).Post("/login", login(s.ds)) } else { log.Warn("Login rate limit is disabled! Consider enabling it to be protected against brute-force attacks") diff --git a/server/server_suite_test.go b/server/server_suite_test.go index 761983efa..b72905b32 100644 --- a/server/server_suite_test.go +++ b/server/server_suite_test.go @@ -3,6 +3,7 @@ package server 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 TestServer(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Server Suite") } + +var _ = configtest.RestoreAfterEachSpec() diff --git a/server/server_test.go b/server/server_test.go index 178c0015a..c2ee31ec8 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -11,7 +11,6 @@ import ( "path/filepath" "time" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -145,7 +144,6 @@ var _ = Describe("TLS support", func() { When("server is started with valid TLS certificates", func() { It("accepts HTTPS connections", func() { - DeferCleanup(configtest.SetupConfig()) // Create server with mock dependencies ds := &tests.MockDataStore{} diff --git a/server/subsonic/api.go b/server/subsonic/api.go index fe724741c..4cb1f2c4c 100644 --- a/server/subsonic/api.go +++ b/server/subsonic/api.go @@ -87,7 +87,7 @@ func New(ds model.DataStore, artwork artwork.Artwork, streamer stream.MediaStrea func (api *Router) routes() http.Handler { r := chi.NewRouter() - if conf.Server.Prometheus.Enabled { + if conf.Server().Prometheus.Enabled { r.Use(recordStats(api.metrics)) } @@ -191,8 +191,8 @@ func (api *Router) routes() http.Handler { hr(r, "getTranscodeStream", api.GetTranscodeStream) }) r.Group(func(r chi.Router) { - r.Use(server.ThrottleBacklog(conf.Server.DevArtworkMaxRequests, conf.Server.DevArtworkThrottleBacklogLimit, - conf.Server.DevArtworkThrottleBacklogTimeout)) + r.Use(server.ThrottleBacklog(conf.Server().DevArtworkMaxRequests, conf.Server().DevArtworkThrottleBacklogLimit, + conf.Server().DevArtworkThrottleBacklogTimeout)) hr(r, "getCoverArt", api.GetCoverArt) }) r.Group(func(r chi.Router) { @@ -205,7 +205,7 @@ func (api *Router) routes() http.Handler { h(r, "updateInternetRadioStation", api.UpdateInternetRadio) }) }) - if conf.Server.EnableSharing { + if conf.Server().EnableSharing { r.Group(func(r chi.Router) { r.Use(getPlayer(api.players)) h(r, "getShares", api.GetShares) @@ -217,7 +217,7 @@ func (api *Router) routes() http.Handler { h501(r, "getShares", "createShare", "updateShare", "deleteShare") } - if conf.Server.Jukebox.Enabled { + if conf.Server().Jukebox.Enabled { r.Group(func(r chi.Router) { r.Use(getPlayer(api.players)) h(r, "jukeboxControl", api.JukeboxControl) diff --git a/server/subsonic/api_suite_test.go b/server/subsonic/api_suite_test.go index 485daca58..92d6f26fd 100644 --- a/server/subsonic/api_suite_test.go +++ b/server/subsonic/api_suite_test.go @@ -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 TestSubsonicApi(t *testing.T) { RunSpecs(t, "Subsonic API Suite") } +var _ = configtest.RestoreAfterEachSpec() + // newLocalStorage fatals if the default extractor is not registered. // Register a no-op so storage.For works in sidecar-lyrics tests. var _ = BeforeSuite(func() { diff --git a/server/subsonic/browsing.go b/server/subsonic/browsing.go index d74468940..f4e6d578e 100644 --- a/server/subsonic/browsing.go +++ b/server/subsonic/browsing.go @@ -66,7 +66,7 @@ func (api *Router) getArtistIndex(r *http.Request, libIds []int, ifModifiedSince } res := &responses.Indexes{ - IgnoredArticles: conf.Server.IgnoredArticles, + IgnoredArticles: conf.Server().IgnoredArticles, LastModified: modified, } @@ -85,7 +85,7 @@ func (api *Router) getArtistIndexID3(r *http.Request, libIds []int, ifModifiedSi } res := &responses.Artists{ - IgnoredArticles: conf.Server.IgnoredArticles, + IgnoredArticles: conf.Server().IgnoredArticles, LastModified: modified, } @@ -414,7 +414,7 @@ func (api *Router) buildArtistDirectory(ctx context.Context, artist *model.Artis } dir.AlbumCount = getArtistAlbumCount(artist) dir.UserRating = int32(artist.Rating) - if conf.Server.Subsonic.EnableAverageRating { + if conf.Server().Subsonic.EnableAverageRating { dir.AverageRating = artist.AverageRating } if artist.Starred { @@ -454,7 +454,7 @@ func (api *Router) buildAlbumDirectory(ctx context.Context, album *model.Album) dir.Played = album.PlayDate } dir.UserRating = int32(album.Rating) - if conf.Server.Subsonic.EnableAverageRating { + if conf.Server().Subsonic.EnableAverageRating { dir.AverageRating = album.AverageRating } dir.SongCount = int32(album.SongCount) diff --git a/server/subsonic/e2e/doc.go b/server/subsonic/e2e/doc.go index 9435d1f60..e83dfdd09 100644 --- a/server/subsonic/e2e/doc.go +++ b/server/subsonic/e2e/doc.go @@ -53,7 +53,7 @@ // // - noopArtwork: returns [model.ErrNotFound] for all artwork requests. // - noopStreamer: returns [model.ErrNotFound] for all stream requests. -// - noopArchiver: returns [model.ErrNotFound] for all archive requests. +// - core.NewArchiver: the real archiver, streaming tracks through the streamer spy. // - noopProvider: returns empty results for all external metadata lookups. // - noopPlayTracker: silently discards all scrobble events. // diff --git a/server/subsonic/e2e/e2e_suite_test.go b/server/subsonic/e2e/e2e_suite_test.go index fdfb562fd..a81e44597 100644 --- a/server/subsonic/e2e/e2e_suite_test.go +++ b/server/subsonic/e2e/e2e_suite_test.go @@ -50,6 +50,8 @@ func TestSubsonicE2E(t *testing.T) { RunSpecs(t, "Subsonic API E2E Suite") } +var _ = configtest.RestoreAfterEachSpec() + // Easy aliases for the storagetest package type _t = map[string]any @@ -212,6 +214,23 @@ func buildTestFS() storagetest.FakeFS { }) } +// setPlayerForcedFormat forces the test-client player to transcode to format until the current spec ends. +func setPlayerForcedFormat(format string) { + doReq("ping") + player, err := ds.Player().FindMatch(ctx, adminUser.ID, "test-client", "") + Expect(err).ToNot(HaveOccurred()) + trc, err := ds.Transcoding().FindByFormat(ctx, format) + Expect(err).ToNot(HaveOccurred()) + player.TranscodingId = trc.ID + Expect(ds.Player().Put(ctx, player)).To(Succeed()) + DeferCleanup(func() { + player, err := ds.Player().FindMatch(ctx, adminUser.ID, "test-client", "") + Expect(err).ToNot(HaveOccurred()) + player.TranscodingId = "" + Expect(ds.Player().Put(ctx, player)).To(Succeed()) + }) +} + // createUser creates a user in the database with the given properties, assigns them to the test // library, and returns the fully-loaded user (with Libraries populated). func createUser(id, username, name string, isAdmin bool) model.User { @@ -371,9 +390,11 @@ var ( var _ = BeforeSuite(func() { ctx = request.WithUser(GinkgoT().Context(), adminUser) - conf.Server.MusicFolder = "fake:///music" - conf.Server.LyricsPriority = "embedded,.lrc,.srt,.yaml" - conf.Server.DevExternalScanner = false + conf.Update(func(c *conf.Options) { + c.MusicFolder = "fake:///music" + c.LyricsPriority = "embedded,.lrc,.srt,.yaml" + c.DevExternalScanner = false + }) buildTestFS() goldenDB = harness.SetupDB(ctx, &adminUser, ®ularUser) @@ -393,15 +414,17 @@ var _ = AfterSuite(func() { func setupTestDB() { ctx = request.WithUser(GinkgoT().Context(), adminUser) - DeferCleanup(configtest.SetupConfig()) + DeferCleanup(conf.SnapshotConfig()) DeferCleanup(func() { // Wait for any background scan (e.g. from startScan endpoint) to finish - // before config cleanup runs, to avoid a data race on conf.Server. + // before the next spec starts. Eventually(scanner.IsScanning).Should(BeFalse()) }) - conf.Server.MusicFolder = "fake:///music" - conf.Server.DevExternalScanner = false - conf.Server.DevEnableMediaFileProbe = false + conf.Update(func(c *conf.Options) { + c.MusicFolder = "fake:///music" + c.DevExternalScanner = false + c.DevEnableMediaFileProbe = false + }) // Restore DB to golden state (no scan needed) goldenDB.Restore() @@ -409,7 +432,7 @@ func setupTestDB() { ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} auth.Init(ds) - // Create the Subsonic Router with real DS, streamer spy, and real Decider + // Create the Subsonic Router with real DS, streamer spy, and real Decider and Archiver streamerSpy = &harness.SpyStreamer{} decider := stream.NewTranscodeDecider(ds, harness.NoopFFmpeg{}) s := scanner.New(ctx, ds, events.NoopBroker(), @@ -418,7 +441,7 @@ func setupTestDB() { ds, noopArtwork{}, streamerSpy, - noopArchiver{}, + core.NewArchiver(streamerSpy, decider, ds, core.NewShare(ds), noopArtwork{}), core.NewPlayers(ds), noopProvider{}, s, diff --git a/server/subsonic/e2e/subsonic_artwork_test.go b/server/subsonic/e2e/subsonic_artwork_test.go index 530588759..19fc40fd2 100644 --- a/server/subsonic/e2e/subsonic_artwork_test.go +++ b/server/subsonic/e2e/subsonic_artwork_test.go @@ -13,7 +13,6 @@ import ( "github.com/Masterminds/squirrel" _ "github.com/navidrome/navidrome/adapters/gotaglib" // registers the "taglib" local-storage extractor "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core" "github.com/navidrome/navidrome/core/agents" @@ -79,7 +78,7 @@ var _ = Describe("Artwork Serving", Ordered, func() { } BeforeAll(func() { - DeferCleanup(configtest.SetupConfig()) + DeferCleanup(conf.SnapshotConfig()) DeferCleanup(func() { Eventually(scanner.IsScanning).Should(BeFalse()) }) ctx = request.WithUser(GinkgoT().Context(), adminUser) @@ -87,18 +86,20 @@ var _ = Describe("Artwork Serving", Ordered, func() { writeArtworkTrack(musicDir, "Artful Artist", "Artful Album", "01 - Come Together", true) writeArtworkTrack(musicDir, "Artless Artist", "Artless Album", "01 - Lonely", false) - conf.Server.MusicFolder = musicDir - conf.Server.DevExternalScanner = false - conf.Server.DevEnableMediaFileProbe = false - conf.Server.CoverArtPriority = "cover.jpg" - conf.Server.ArtistArtPriority = "artist.png" // offline: artists resolve absent, out of scope here - conf.Server.EnableMediaFileCoverArt = false - conf.Server.DevArtworkWorkerConcurrency = 1 - conf.Server.CacheFolder = conf.NewDir(GinkgoT().TempDir()) - conf.Server.EnableSharing = true - conf.Server.DevArtworkMaxRequests = 100 - conf.Server.DevArtworkThrottleBacklogLimit = 100 - conf.Server.DevArtworkThrottleBacklogTimeout = time.Minute + conf.Update(func(c *conf.Options) { + c.MusicFolder = musicDir + c.DevExternalScanner = false + c.DevEnableMediaFileProbe = false + c.CoverArtPriority = "cover.jpg" + c.ArtistArtPriority = "artist.png" // offline: artists resolve absent, out of scope here + c.EnableMediaFileCoverArt = false + c.DevArtworkWorkerConcurrency = 1 + c.CacheFolder = conf.NewDir(GinkgoT().TempDir()) + c.EnableSharing = true + c.DevArtworkMaxRequests = 100 + c.DevArtworkThrottleBacklogLimit = 100 + c.DevArtworkThrottleBacklogTimeout = time.Minute + }) goldenDB.Restore() ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} diff --git a/server/subsonic/e2e/subsonic_media_retrieval_test.go b/server/subsonic/e2e/subsonic_media_retrieval_test.go index b0ef4fd72..27e4b568d 100644 --- a/server/subsonic/e2e/subsonic_media_retrieval_test.go +++ b/server/subsonic/e2e/subsonic_media_retrieval_test.go @@ -1,10 +1,11 @@ package e2e import ( + "archive/zip" + "bytes" "net/http" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/server/subsonic/responses" . "github.com/onsi/ginkgo/v2" @@ -57,8 +58,8 @@ var _ = Describe("Media Retrieval Endpoints", Ordered, func() { }) It("downsamples when only maxBitRate is specified (lower than source)", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DefaultDownsamplingFormat = "opus" + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "opus" }) w := doRawReq("stream", "id", trackID, "maxBitRate", "128") @@ -106,7 +107,7 @@ var _ = Describe("Media Retrieval Endpoints", Ordered, func() { }) Describe("Download", func() { - var trackID, trackTitle string + var trackID, trackTitle, albumID string BeforeAll(func() { // All test tracks are mp3 at 320kbps @@ -115,6 +116,7 @@ var _ = Describe("Media Retrieval Endpoints", Ordered, func() { Expect(songs).ToNot(BeEmpty()) trackID = songs[0].ID trackTitle = songs[0].Title + albumID = songs[0].AlbumID }) It("returns error when id parameter is missing", func() { @@ -125,9 +127,11 @@ var _ = Describe("Media Retrieval Endpoints", Ordered, func() { }) It("downloads raw when no format specified and AutoTranscodeDownload is false", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableDownloads = true - conf.Server.AutoTranscodeDownload = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { + c.EnableDownloads = true + c.AutoTranscodeDownload = false + }) w := doRawReq("download", "id", trackID) @@ -136,8 +140,8 @@ var _ = Describe("Media Retrieval Endpoints", Ordered, func() { }) It("downloads with explicit format and bitrate", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableDownloads = true + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { c.EnableDownloads = true }) w := doRawReq("download", "id", trackID, "format", "opus", "bitrate", "128") @@ -148,13 +152,50 @@ var _ = Describe("Media Retrieval Endpoints", Ordered, func() { }) It("returns error when downloads are disabled", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.EnableDownloads = false + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { c.EnableDownloads = false }) resp := doReq("download", "id", trackID) Expect(resp.Status).To(Equal(responses.StatusFailed)) }) + + Context("when the player has a forced transcoding", func() { + BeforeEach(func() { + DeferCleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { c.EnableDownloads = true }) + setPlayerForcedFormat("opus") + }) + + It("uses the explicitly requested format", func() { + w := doRawReq("download", "id", trackID, "format", "aac", "bitrate", "128") + + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(streamerSpy.LastRequest.Format).To(Equal("aac")) + Expect(streamerSpy.LastRequest.BitRate).To(Equal(128)) + }) + + It("uses the explicitly requested format for album zips", func() { + w := doRawReq("download", "id", albumID, "format", "aac", "bitrate", "128") + + Expect(w.Code).To(Equal(http.StatusOK)) + z, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len())) + Expect(err).ToNot(HaveOccurred()) + Expect(z.File).ToNot(BeEmpty()) + for _, f := range z.File { + Expect(f.Name).To(HaveSuffix(".aac")) + } + }) + + It("uses the player's format when no format is requested and AutoTranscodeDownload is true", func() { + conf.Update(func(c *conf.Options) { c.AutoTranscodeDownload = true }) + + w := doRawReq("download", "id", trackID) + + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(streamerSpy.LastRequest.Format).To(Equal("opus")) + }) + }) }) Describe("GetCoverArt", func() { diff --git a/server/subsonic/e2e/subsonic_multilibrary_test.go b/server/subsonic/e2e/subsonic_multilibrary_test.go index 8158be1de..8797a7a0e 100644 --- a/server/subsonic/e2e/subsonic_multilibrary_test.go +++ b/server/subsonic/e2e/subsonic_multilibrary_test.go @@ -24,7 +24,7 @@ var _ = Describe("Multi-Library Support", Ordered, func() { var userLib1Only model.User // non-admin with lib1 access only BeforeAll(func() { - conf.Server.EnableSharing = true + conf.Update(func(c *conf.Options) { c.EnableSharing = true }) setupTestDB() // Create a second FakeFS with Classical music content diff --git a/server/subsonic/e2e/subsonic_playlists_test.go b/server/subsonic/e2e/subsonic_playlists_test.go index 7a6d7df5d..b797bf2af 100644 --- a/server/subsonic/e2e/subsonic_playlists_test.go +++ b/server/subsonic/e2e/subsonic_playlists_test.go @@ -461,7 +461,7 @@ var _ = Describe("Playlist Endpoints", Ordered, func() { Expect(resp.Playlist.Name).To(Equal("Smart Playlist")) Expect(resp.Playlist.OpenSubsonicPlaylist).ToNot(BeNil()) Expect(resp.Playlist.OpenSubsonicPlaylist.Readonly).To(BeTrue()) - expectedValidUntil := time.Now().Add(conf.Server.SmartPlaylistRefreshDelay) + expectedValidUntil := time.Now().Add(conf.Server().SmartPlaylistRefreshDelay) Expect(*resp.Playlist.OpenSubsonicPlaylist.ValidUntil).To(BeTemporally("~", expectedValidUntil, time.Second)) }) @@ -535,7 +535,7 @@ var _ = Describe("Playlist Endpoints", Ordered, func() { Expect(resp.Status).To(Equal(responses.StatusOK)) // Force immediate refresh for all smart playlists - conf.Server.SmartPlaylistRefreshDelay = -1 * time.Second + conf.Update(func(c *conf.Options) { c.SmartPlaylistRefreshDelay = -1 * time.Second }) // Create smart playlist with boolean true boolPls := &model.Playlist{ diff --git a/server/subsonic/e2e/subsonic_searching_test.go b/server/subsonic/e2e/subsonic_searching_test.go index 00b60ad6f..d83d9930b 100644 --- a/server/subsonic/e2e/subsonic_searching_test.go +++ b/server/subsonic/e2e/subsonic_searching_test.go @@ -3,7 +3,6 @@ package e2e import ( "github.com/google/uuid" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/server/subsonic/responses" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -251,8 +250,7 @@ var _ = Describe("Search Endpoints", func() { Describe("Legacy backend", func() { It("returns results using legacy LIKE-based search when configured", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Search.Backend = "legacy" + conf.Update(func(c *conf.Options) { c.Search.Backend = "legacy" }) resp := doReq("search3", "query", "Beatles") diff --git a/server/subsonic/e2e/subsonic_sharing_test.go b/server/subsonic/e2e/subsonic_sharing_test.go index cf3e55d74..5fd6d70bf 100644 --- a/server/subsonic/e2e/subsonic_sharing_test.go +++ b/server/subsonic/e2e/subsonic_sharing_test.go @@ -15,7 +15,7 @@ var _ = Describe("Sharing Endpoints", Ordered, func() { var songID string BeforeAll(func() { - conf.Server.EnableSharing = true + conf.Update(func(c *conf.Options) { c.EnableSharing = true }) setupTestDB() albums, err := ds.Album().GetAll(ctx, model.QueryOptions{ @@ -133,7 +133,7 @@ var _ = Describe("Sharing Cross-User Isolation", Ordered, func() { var albumID string BeforeAll(func() { - conf.Server.EnableSharing = true + conf.Update(func(c *conf.Options) { c.EnableSharing = true }) setupTestDB() userA = createUser("share-user-a", "share-user-a", "Share User A", false) @@ -210,9 +210,9 @@ var _ = Describe("Sharing Downloadable Default", func() { var albumID string BeforeEach(func() { - conf.Server.EnableSharing = true + conf.Update(func(c *conf.Options) { c.EnableSharing = true }) setupTestDB() - conf.Server.EnableDownloads = true + conf.Update(func(c *conf.Options) { c.EnableDownloads = true }) albumID = albumIDByName("Abbey Road") }) @@ -228,8 +228,10 @@ var _ = Describe("Sharing Downloadable Default", func() { DescribeTable("createShare resolves downloadable", func(defaultDownloadable, enableDownloads bool, params []string, expected bool) { - conf.Server.DefaultDownloadableShare = defaultDownloadable - conf.Server.EnableDownloads = enableDownloads + conf.Update(func(c *conf.Options) { + c.DefaultDownloadableShare = defaultDownloadable + c.EnableDownloads = enableDownloads + }) Expect(createShare(params...).Downloadable).To(Equal(expected)) }, @@ -241,7 +243,7 @@ var _ = Describe("Sharing Downloadable Default", func() { ) It("updateShare keeps the current downloadable when the param is absent", func() { - conf.Server.DefaultDownloadableShare = true + conf.Update(func(c *conf.Options) { c.DefaultDownloadableShare = true }) share := createShare() Expect(share.Downloadable).To(BeTrue()) @@ -255,7 +257,7 @@ var _ = Describe("Sharing Downloadable Default", func() { }) It("updateShare applies an explicit downloadable and keeps the description", func() { - conf.Server.DefaultDownloadableShare = true + conf.Update(func(c *conf.Options) { c.DefaultDownloadableShare = true }) share := createShare("description", "Keep me") resp := doReq("updateShare", "id", share.ID, "downloadable", "false") diff --git a/server/subsonic/e2e/subsonic_stream_test.go b/server/subsonic/e2e/subsonic_stream_test.go index 81998760f..0e0a8cb2e 100644 --- a/server/subsonic/e2e/subsonic_stream_test.go +++ b/server/subsonic/e2e/subsonic_stream_test.go @@ -115,7 +115,7 @@ var _ = Describe("stream.view (legacy streaming)", Ordered, func() { Describe("downsampling with maxBitRate only", func() { It("transcodes using default downsampling format when maxBitRate < source bitrate", func() { - conf.Server.DefaultDownsamplingFormat = "opus" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "opus" }) w := doRawReq("stream", "id", flacTrackID, "maxBitRate", "192") Expect(w.Code).To(Equal(http.StatusOK)) Expect(streamerSpy.LastRequest.Format).To(Equal("opus")) @@ -123,7 +123,7 @@ var _ = Describe("stream.view (legacy streaming)", Ordered, func() { }) It("streams raw when maxBitRate >= source bitrate (no downsampling needed)", func() { - conf.Server.DefaultDownsamplingFormat = "opus" + conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "opus" }) w := doRawReq("stream", "id", mp3TrackID, "maxBitRate", "320") Expect(w.Code).To(Equal(http.StatusOK)) Expect(streamerSpy.LastRequest.Format).To(BeElementOf("raw", "")) @@ -157,7 +157,7 @@ var _ = Describe("stream.view (legacy streaming)", Ordered, func() { }) It("returns a Subsonic error for download endpoint", func() { - conf.Server.EnableDownloads = true + conf.Update(func(c *conf.Options) { c.EnableDownloads = true }) w := doRawReq("download", "id", flacTrackID, "format", "opus") Expect(w.Code).To(Equal(http.StatusOK)) @@ -183,7 +183,7 @@ var _ = Describe("stream.view (legacy streaming)", Ordered, func() { }) It("returns 200 with empty body for download endpoint", func() { - conf.Server.EnableDownloads = true + conf.Update(func(c *conf.Options) { c.EnableDownloads = true }) w := doRawReq("download", "id", flacTrackID, "format", "opus") Expect(w.Code).To(Equal(http.StatusOK)) Expect(w.Body.Len()).To(Equal(0)) diff --git a/server/subsonic/e2e/subsonic_transcode_test.go b/server/subsonic/e2e/subsonic_transcode_test.go index 313066938..ab7655dd0 100644 --- a/server/subsonic/e2e/subsonic_transcode_test.go +++ b/server/subsonic/e2e/subsonic_transcode_test.go @@ -159,22 +159,11 @@ var _ = Describe("Transcode Endpoints", Ordered, func() { Expect(ds.Player().Put(ctx, player)).To(Succeed()) } - setPlayerForcedFormat := func(format string) { - doReq("ping") - player, err := ds.Player().FindMatch(ctx, adminUser.ID, "test-client", "") - Expect(err).ToNot(HaveOccurred()) - trc, err := ds.Transcoding().FindByFormat(ctx, format) - Expect(err).ToNot(HaveOccurred()) - player.TranscodingId = trc.ID - Expect(ds.Player().Put(ctx, player)).To(Succeed()) - } - AfterEach(func() { // Reset player MaxBitRate to 0 after each test player, err := ds.Player().FindMatch(ctx, adminUser.ID, "test-client", "") if err == nil { player.MaxBitRate = 0 - player.TranscodingId = "" _ = ds.Player().Put(ctx, player) } }) @@ -340,8 +329,8 @@ var _ = Describe("Transcode Endpoints", Ordered, func() { Expect(resp.TranscodeDecision.CanTranscode).To(BeTrue()) Expect(resp.TranscodeDecision.TranscodeStream).ToNot(BeNil()) Expect(resp.TranscodeDecision.TranscodeStream.Codec).To(Equal("flac")) - // DSD sample rate normalized: 2822400 / 8 = 352800 - Expect(resp.TranscodeDecision.TranscodeStream.AudioSamplerate).To(Equal(int32(352800))) + // DSD sample rate normalized: 2822400 / 8 = 352800, capped at 88200 + Expect(resp.TranscodeDecision.TranscodeStream.AudioSamplerate).To(Equal(int32(88200))) // DSD 1-bit → 24-bit PCM Expect(resp.TranscodeDecision.TranscodeStream.AudioBitdepth).To(Equal(int32(24))) }) diff --git a/server/subsonic/helpers.go b/server/subsonic/helpers.go index 55b1b213e..c98e44192 100644 --- a/server/subsonic/helpers.go +++ b/server/subsonic/helpers.go @@ -72,7 +72,7 @@ func getUser(ctx context.Context) model.User { } func sortName(sortName, orderName string) string { - if conf.Server.PreferSortTags { + if conf.Server().PreferSortTags { return cmp.Or( sortName, orderName, @@ -86,7 +86,7 @@ func getArtistAlbumCount(a *model.Artist) int32 { // where the artist is an album artist OR artist. Use the custom stat // main credit for this calculation. // Otherwise, return just the roles as album artist (precise) - if conf.Server.Subsonic.ArtistParticipations { + if conf.Server().Subsonic.ArtistParticipations { mainCreditStats := a.Stats[model.RoleMainCredit] return int32(mainCreditStats.AlbumCount) } else { @@ -114,7 +114,7 @@ func toArtist(r *http.Request, a model.Artist) responses.Artist { if !a.ImageAbsent { artist.ArtistImageUrl = publicurl.ImageURL(r.Context(), a.CoverArtID(), 600) } - if conf.Server.Subsonic.EnableAverageRating { + if conf.Server().Subsonic.EnableAverageRating { artist.AverageRating = a.AverageRating } if a.Starred { @@ -134,7 +134,7 @@ func toArtistID3(r *http.Request, a model.Artist) responses.ArtistID3 { if !a.ImageAbsent { artist.ArtistImageUrl = publicurl.ImageURL(r.Context(), a.CoverArtID(), 600) } - if conf.Server.Subsonic.EnableAverageRating { + if conf.Server().Subsonic.EnableAverageRating { artist.AverageRating = a.AverageRating } if a.Starred { @@ -146,7 +146,7 @@ func toArtistID3(r *http.Request, a model.Artist) responses.ArtistID3 { func toOSArtistID3(ctx context.Context, a model.Artist) *responses.OpenSubsonicArtistID3 { player, _ := request.PlayerFrom(ctx) - if strings.Contains(conf.Server.Subsonic.LegacyClients, player.Client) { + if strings.Contains(conf.Server().Subsonic.LegacyClients, player.Client) { return nil } artist := responses.OpenSubsonicArtistID3{ @@ -207,7 +207,7 @@ func childFromMediaFile(ctx context.Context, mf model.MediaFile) responses.Child child.IsDir = false player, ok := request.PlayerFrom(ctx) - if ok && isClientInList(conf.Server.Subsonic.MinimalClients, player.Client) { + if ok && isClientInList(conf.Server().Subsonic.MinimalClients, player.Client) { return child } @@ -239,7 +239,7 @@ func childFromMediaFile(ctx context.Context, mf model.MediaFile) responses.Child child.Starred = mf.StarredAt } child.UserRating = int32(mf.Rating) - if conf.Server.Subsonic.EnableAverageRating { + if conf.Server().Subsonic.EnableAverageRating { child.AverageRating = mf.AverageRating } @@ -255,7 +255,7 @@ func childFromMediaFile(ctx context.Context, mf model.MediaFile) responses.Child func osChildFromMediaFile(ctx context.Context, mf model.MediaFile) *responses.OpenSubsonicChild { player, ok := request.PlayerFrom(ctx) - if ok && isClientInList(conf.Server.Subsonic.LegacyClients, player.Client) { + if ok && isClientInList(conf.Server().Subsonic.LegacyClients, player.Client) { return nil } child := responses.OpenSubsonicChild{} @@ -345,7 +345,7 @@ func sanitizeSlashes(target string) string { // fallbacks for legacy rows; returns zero only when all three are unset. func albumCreatedAt(al model.Album) time.Time { candidates := []time.Time{al.CreatedAt, al.UpdatedAt, al.ImportedAt} - if conf.Server.RecentlyAddedByModTime { + if conf.Server().RecentlyAddedByModTime { candidates = []time.Time{al.UpdatedAt, al.CreatedAt, al.ImportedAt} } for _, t := range candidates { @@ -360,7 +360,7 @@ func albumCreatedAt(al model.Album) time.Time { // mediaFileRecentlyAddedSort; BirthTime is the legacy fallback. func mediaFileCreatedAt(mf model.MediaFile) time.Time { candidates := []time.Time{mf.CreatedAt, mf.UpdatedAt, mf.BirthTime} - if conf.Server.RecentlyAddedByModTime { + if conf.Server().RecentlyAddedByModTime { candidates = []time.Time{mf.UpdatedAt, mf.CreatedAt, mf.BirthTime} } for _, t := range candidates { @@ -393,7 +393,7 @@ func childFromAlbum(ctx context.Context, al model.Album) responses.Child { } child.PlayCount = al.PlayCount child.UserRating = int32(al.Rating) - if conf.Server.Subsonic.EnableAverageRating { + if conf.Server().Subsonic.EnableAverageRating { child.AverageRating = al.AverageRating } child.OpenSubsonicChild = osChildFromAlbum(ctx, al) @@ -402,7 +402,7 @@ func childFromAlbum(ctx context.Context, al model.Album) responses.Child { func osChildFromAlbum(ctx context.Context, al model.Album) *responses.OpenSubsonicChild { player, _ := request.PlayerFrom(ctx) - if strings.Contains(conf.Server.Subsonic.LegacyClients, player.Client) { + if strings.Contains(conf.Server().Subsonic.LegacyClients, player.Client) { return nil } child := responses.OpenSubsonicChild{} @@ -489,7 +489,7 @@ func buildAlbumID3(ctx context.Context, album model.Album) responses.AlbumID3 { func buildOSAlbumID3(ctx context.Context, album model.Album) *responses.OpenSubsonicAlbumID3 { player, _ := request.PlayerFrom(ctx) - if strings.Contains(conf.Server.Subsonic.LegacyClients, player.Client) { + if strings.Contains(conf.Server().Subsonic.LegacyClients, player.Client) { return nil } dir := responses.OpenSubsonicAlbumID3{} @@ -497,7 +497,7 @@ func buildOSAlbumID3(ctx context.Context, album model.Album) *responses.OpenSubs dir.Played = album.PlayDate } dir.UserRating = int32(album.Rating) - if conf.Server.Subsonic.EnableAverageRating { + if conf.Server().Subsonic.EnableAverageRating { dir.AverageRating = album.AverageRating } dir.RecordLabels = slice.Map(album.Tags.Values(model.TagRecordLabel), func(s string) responses.RecordLabel { diff --git a/server/subsonic/helpers_test.go b/server/subsonic/helpers_test.go index 69fda4681..9aa7b470c 100644 --- a/server/subsonic/helpers_test.go +++ b/server/subsonic/helpers_test.go @@ -8,7 +8,6 @@ import ( "github.com/go-chi/jwtauth/v5" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -20,7 +19,6 @@ import ( var _ = Describe("helpers", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) auth.TokenAuth = jwtauth.New("HS256", []byte("test secret"), nil) auth.PublicTokenAuth = jwtauth.New("HS256", []byte("test public secret"), nil) }) @@ -60,12 +58,9 @@ var _ = Describe("helpers", func() { }) Describe("sortName", func() { - BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - }) When("PreferSortTags is false", func() { BeforeEach(func() { - conf.Server.PreferSortTags = false + conf.Update(func(c *conf.Options) { c.PreferSortTags = false }) }) It("returns the order name even if sort name is provided", func() { Expect(sortName("Sort Album Name", "Order Album Name")).To(Equal("Order Album Name")) @@ -76,7 +71,7 @@ var _ = Describe("helpers", func() { }) When("PreferSortTags is true", func() { BeforeEach(func() { - conf.Server.PreferSortTags = true + conf.Update(func(c *conf.Options) { c.PreferSortTags = true }) }) It("returns the sort name if provided", func() { Expect(sortName("Sort Album Name", "Order Album Name")).To(Equal("Sort Album Name")) @@ -179,13 +174,13 @@ var _ = Describe("helpers", func() { } It("Handles album count without artist participations", func() { - conf.Server.Subsonic.ArtistParticipations = false + conf.Update(func(c *conf.Options) { c.Subsonic.ArtistParticipations = false }) result := getArtistAlbumCount(&artist) Expect(result).To(Equal(int32(3))) }) It("Handles album count without with participations", func() { - conf.Server.Subsonic.ArtistParticipations = true + conf.Update(func(c *conf.Options) { c.Subsonic.ArtistParticipations = true }) result := getArtistAlbumCount(&artist) Expect(result).To(Equal(int32(4))) }) @@ -232,7 +227,7 @@ var _ = Describe("helpers", func() { Context("with minimal client", func() { BeforeEach(func() { - conf.Server.Subsonic.MinimalClients = "minimal-client" + conf.Update(func(c *conf.Options) { c.Subsonic.MinimalClients = "minimal-client" }) player := model.Player{Client: "minimal-client"} ctx = request.WithPlayer(ctx, player) }) @@ -267,7 +262,7 @@ var _ = Describe("helpers", func() { Context("with non-minimal client", func() { BeforeEach(func() { - conf.Server.Subsonic.MinimalClients = "minimal-client" + conf.Update(func(c *conf.Options) { c.Subsonic.MinimalClients = "minimal-client" }) player := model.Player{Client: "regular-client"} ctx = request.WithPlayer(ctx, player) }) @@ -292,7 +287,7 @@ var _ = Describe("helpers", func() { Context("when minimal clients list is empty", func() { BeforeEach(func() { - conf.Server.Subsonic.MinimalClients = "" + conf.Update(func(c *conf.Options) { c.Subsonic.MinimalClients = "" }) player := model.Player{Client: "any-client"} ctx = request.WithPlayer(ctx, player) }) @@ -413,7 +408,7 @@ var _ = Describe("helpers", func() { Context("with legacy client", func() { BeforeEach(func() { - conf.Server.Subsonic.LegacyClients = "legacy-client" + conf.Update(func(c *conf.Options) { c.Subsonic.LegacyClients = "legacy-client" }) player := model.Player{Client: "legacy-client"} ctx = request.WithPlayer(ctx, player) }) @@ -426,7 +421,7 @@ var _ = Describe("helpers", func() { Context("with non-legacy client", func() { BeforeEach(func() { - conf.Server.Subsonic.LegacyClients = "legacy-client" + conf.Update(func(c *conf.Options) { c.Subsonic.LegacyClients = "legacy-client" }) player := model.Player{Client: "regular-client"} ctx = request.WithPlayer(ctx, player) }) @@ -486,7 +481,7 @@ var _ = Describe("helpers", func() { Context("when legacy clients list is empty", func() { BeforeEach(func() { - conf.Server.Subsonic.LegacyClients = "" + conf.Update(func(c *conf.Options) { c.Subsonic.LegacyClients = "" }) player := model.Player{Client: "any-client"} ctx = request.WithPlayer(ctx, player) }) @@ -614,7 +609,7 @@ var _ = Describe("helpers", func() { BeforeEach(func() { ctx = context.Background() - conf.Server.Subsonic.EnableAverageRating = true + conf.Update(func(c *conf.Options) { c.Subsonic.EnableAverageRating = true }) }) Describe("childFromMediaFile", func() { @@ -665,7 +660,7 @@ var _ = Describe("helpers", func() { Describe("toArtist", func() { It("includes averageRating when set", func() { - conf.Server.Subsonic.EnableAverageRating = true + conf.Update(func(c *conf.Options) { c.Subsonic.EnableAverageRating = true }) r := httptest.NewRequest("GET", "/test", nil) a := model.Artist{ ID: "ar-avg-1", @@ -681,7 +676,7 @@ var _ = Describe("helpers", func() { Describe("toArtistID3", func() { It("includes averageRating when set", func() { - conf.Server.Subsonic.EnableAverageRating = true + conf.Update(func(c *conf.Options) { c.Subsonic.EnableAverageRating = true }) r := httptest.NewRequest("GET", "/test", nil) a := model.Artist{ ID: "ar-avg-2", @@ -698,7 +693,7 @@ var _ = Describe("helpers", func() { Describe("buildAlbumID3 Created field", func() { When("RecentlyAddedByModTime is false", func() { BeforeEach(func() { - conf.Server.RecentlyAddedByModTime = false + conf.Update(func(c *conf.Options) { c.RecentlyAddedByModTime = false }) }) It("uses CreatedAt when set", func() { @@ -731,7 +726,7 @@ var _ = Describe("helpers", func() { When("RecentlyAddedByModTime is true", func() { BeforeEach(func() { - conf.Server.RecentlyAddedByModTime = true + conf.Update(func(c *conf.Options) { c.RecentlyAddedByModTime = true }) }) It("uses UpdatedAt even when CreatedAt is also set", func() { @@ -769,7 +764,7 @@ var _ = Describe("helpers", func() { When("RecentlyAddedByModTime is false", func() { BeforeEach(func() { - conf.Server.RecentlyAddedByModTime = false + conf.Update(func(c *conf.Options) { c.RecentlyAddedByModTime = false }) }) It("uses CreatedAt, not BirthTime", func() { @@ -795,7 +790,7 @@ var _ = Describe("helpers", func() { When("RecentlyAddedByModTime is true", func() { BeforeEach(func() { - conf.Server.RecentlyAddedByModTime = true + conf.Update(func(c *conf.Options) { c.RecentlyAddedByModTime = true }) }) It("uses UpdatedAt even when CreatedAt is also set", func() { @@ -817,7 +812,7 @@ var _ = Describe("helpers", func() { Describe("EnableAverageRating config", func() { It("excludes averageRating when disabled", func() { - conf.Server.Subsonic.EnableAverageRating = false + conf.Update(func(c *conf.Options) { c.Subsonic.EnableAverageRating = false }) mf := model.MediaFile{ ID: "mf-cfg-1", diff --git a/server/subsonic/jukebox.go b/server/subsonic/jukebox.go index d8bf53360..45d0308ae 100644 --- a/server/subsonic/jukebox.go +++ b/server/subsonic/jukebox.go @@ -31,11 +31,11 @@ func (api *Router) JukeboxControl(r *http.Request) (*responses.Subsonic, error) user := getUser(ctx) p := req.Params(r) - if !conf.Server.Jukebox.Enabled { + if !conf.Server().Jukebox.Enabled { return nil, newError(responses.ErrorGeneric, "Jukebox is disabled") } - if conf.Server.Jukebox.AdminOnly && !user.IsAdmin { + if conf.Server().Jukebox.AdminOnly && !user.IsAdmin { return nil, newError(responses.ErrorAuthorizationFail, "Jukebox is admin only") } diff --git a/server/subsonic/lyrics_test.go b/server/subsonic/lyrics_test.go index 8713b7a3b..993502273 100644 --- a/server/subsonic/lyrics_test.go +++ b/server/subsonic/lyrics_test.go @@ -5,7 +5,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/server/subsonic/responses" @@ -24,8 +23,7 @@ var _ = Describe("GetLyricsBySongId", func() { MockedMediaFile: mockRepo, } router = New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, lyrics.NewLyrics(ds, nil), nil, nil) - DeferCleanup(configtest.SetupConfig()) - conf.Server.LyricsPriority = "embedded,.lrc" + conf.Update(func(c *conf.Options) { c.LyricsPriority = "embedded,.lrc" }) }) const syncedLyrics = "[00:18.80]We're no strangers to love\n[00:22.801]You know the rules and so do I" @@ -200,7 +198,7 @@ var _ = Describe("GetLyricsBySongId", func() { }) It("should return multilingual TTML sidecar lyrics", func() { - conf.Server.LyricsPriority = ".ttml,embedded" + conf.Update(func(c *conf.Options) { c.LyricsPriority = ".ttml,embedded" }) r := newGetRequest("id=1") fixturesDir, err := filepath.Abs("tests/fixtures") @@ -256,7 +254,7 @@ var _ = Describe("GetLyricsBySongId", func() { }) It("should return metadata-linked translation and pronunciation tracks from TTML", func() { - conf.Server.LyricsPriority = ".ttml,embedded" + conf.Update(func(c *conf.Options) { c.LyricsPriority = ".ttml,embedded" }) r := newGetRequest("id=1&enhanced=true") fixturesDir, err := filepath.Abs("tests/fixtures") diff --git a/server/subsonic/media_retrieval.go b/server/subsonic/media_retrieval.go index f5e2ceb25..e2a447a04 100644 --- a/server/subsonic/media_retrieval.go +++ b/server/subsonic/media_retrieval.go @@ -20,7 +20,7 @@ import ( ) func (api *Router) GetAvatar(w http.ResponseWriter, r *http.Request) (*responses.Subsonic, error) { - if !conf.Server.EnableGravatar { + if !conf.Server().EnableGravatar { return api.getPlaceHolderAvatar(w, r) } p := req.Params(r) diff --git a/server/subsonic/media_retrieval_test.go b/server/subsonic/media_retrieval_test.go index ad193518d..3683e8c44 100644 --- a/server/subsonic/media_retrieval_test.go +++ b/server/subsonic/media_retrieval_test.go @@ -13,7 +13,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core/lyrics" "github.com/navidrome/navidrome/model" @@ -43,8 +42,7 @@ var _ = Describe("MediaRetrievalController", func() { artwork = &fakeArtwork{data: "image data"} router = New(ds, artwork, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, lyrics.NewLyrics(ds, nil), nil, nil) w = httptest.NewRecorder() - DeferCleanup(configtest.SetupConfig()) - conf.Server.LyricsPriority = "embedded,.lrc" + conf.Update(func(c *conf.Options) { c.LyricsPriority = "embedded,.lrc" }) }) Describe("GetCoverArt", func() { diff --git a/server/subsonic/middlewares.go b/server/subsonic/middlewares.go index fdb4af28d..4bffb4fa7 100644 --- a/server/subsonic/middlewares.go +++ b/server/subsonic/middlewares.go @@ -99,7 +99,7 @@ func checkRequiredParameters(next http.Handler) http.Handler { } func authenticate(ds model.DataStore) func(next http.Handler) http.Handler { - limiter := newAuthLimiter(conf.Server.AuthRequestLimit, conf.Server.AuthWindowLength) + limiter := newAuthLimiter(conf.Server().AuthRequestLimit, conf.Server().AuthWindowLength) return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() @@ -326,7 +326,7 @@ func getPlayer(players core.Players) func(next http.Handler) http.Handler { MaxAge: consts.CookieExpiry, HttpOnly: true, SameSite: http.SameSiteStrictMode, - Path: cmp.Or(conf.Server.BasePath, "/"), + Path: cmp.Or(conf.Server().BasePath, "/"), } http.SetCookie(w, cookie) } diff --git a/server/subsonic/middlewares_test.go b/server/subsonic/middlewares_test.go index b3ad972b7..d66fa5599 100644 --- a/server/subsonic/middlewares_test.go +++ b/server/subsonic/middlewares_test.go @@ -14,7 +14,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core" "github.com/navidrome/navidrome/core/auth" @@ -100,8 +99,10 @@ var _ = Describe("Middlewares", func() { }) It("passes when all required params are available (reverse-proxy case)", func() { - conf.Server.ExtAuth.TrustedSources = "127.0.0.234/32" - conf.Server.ExtAuth.UserHeader = "Remote-User" + conf.Update(func(c *conf.Options) { + c.ExtAuth.TrustedSources = "127.0.0.234/32" + c.ExtAuth.UserHeader = "Remote-User" + }) r := newGetRequest("v=1.15", "c=test") r.Header.Add("Remote-User", "user") @@ -234,8 +235,7 @@ var _ = Describe("Middlewares", func() { var validToken string BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.SessionTimeout = time.Minute + conf.Update(func(c *conf.Options) { c.SessionTimeout = time.Minute }) auth.Init(ds) }) @@ -266,9 +266,10 @@ var _ = Describe("Middlewares", func() { When("using reverse proxy authentication", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.ExtAuth.TrustedSources = "192.168.1.1/24" - conf.Server.ExtAuth.UserHeader = "Remote-User" + conf.Update(func(c *conf.Options) { + c.ExtAuth.TrustedSources = "192.168.1.1/24" + c.ExtAuth.UserHeader = "Remote-User" + }) }) It("passes authentication with correct IP and header", func() { @@ -419,9 +420,10 @@ var _ = Describe("Middlewares", func() { var cp http.Handler BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.AuthRequestLimit = 3 - conf.Server.AuthWindowLength = time.Minute + conf.Update(func(c *conf.Options) { + c.AuthRequestLimit = 3 + c.AuthWindowLength = time.Minute + }) cp = authenticate(ds)(next) }) @@ -513,8 +515,10 @@ var _ = Describe("Middlewares", func() { }) It("does not limit reverse proxy authentication", func() { - conf.Server.ExtAuth.TrustedSources = "192.168.1.1/24" - conf.Server.ExtAuth.UserHeader = "Remote-User" + conf.Update(func(c *conf.Options) { + c.ExtAuth.TrustedSources = "192.168.1.1/24" + c.ExtAuth.UserHeader = "Remote-User" + }) failTimes(3, "u=admin", "p=WRONG") r := newGetRequest() @@ -544,7 +548,7 @@ var _ = Describe("Middlewares", func() { }) It("is disabled when AuthRequestLimit is 0", func() { - conf.Server.AuthRequestLimit = 0 + conf.Update(func(c *conf.Options) { c.AuthRequestLimit = 0 }) cp = authenticate(ds)(next) failTimes(10, "u=admin", "p=WRONG") @@ -558,9 +562,10 @@ var _ = Describe("Middlewares", func() { var gatedDS model.DataStore BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.AuthRequestLimit = 5 - conf.Server.AuthWindowLength = time.Minute + conf.Update(func(c *conf.Options) { + c.AuthRequestLimit = 5 + c.AuthWindowLength = time.Minute + }) gate = &gatedUserRepo{ UserRepository: ds.User(), entered: make(chan struct{}, 64), @@ -583,7 +588,7 @@ var _ = Describe("Middlewares", func() { } }) } - for range conf.Server.AuthRequestLimit { + for range conf.Server().AuthRequestLimit { Eventually(gate.entered).Should(Receive()) } close(gate.proceed) @@ -601,7 +606,7 @@ var _ = Describe("Middlewares", func() { }) } - limit := int32(conf.Server.AuthRequestLimit) + limit := int32(conf.Server().AuthRequestLimit) Eventually(gate.lookups.Load).Should(Equal(limit)) Consistently(gate.lookups.Load, 100*time.Millisecond).Should(Equal(limit)) close(gate.proceed) @@ -790,8 +795,7 @@ var _ = Describe("Middlewares", func() { var validToken string BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.SessionTimeout = time.Minute + conf.Update(func(c *conf.Options) { c.SessionTimeout = time.Minute }) auth.Init(ds) usr = &model.User{UserName: "admin"} @@ -825,8 +829,7 @@ var _ = Describe("Middlewares", func() { var usr *model.User BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.SessionTimeout = time.Minute + conf.Update(func(c *conf.Options) { c.SessionTimeout = time.Minute }) auth.Init(ds) usr = &model.User{ID: "u1", UserName: "johndoe", TokenEpoch: 1} }) diff --git a/server/subsonic/playlists.go b/server/subsonic/playlists.go index e64fc9e82..9b0ddf45c 100644 --- a/server/subsonic/playlists.go +++ b/server/subsonic/playlists.go @@ -135,7 +135,7 @@ func (api *Router) buildPlaylist(ctx context.Context, p model.Playlist) response pls.Changed = p.UpdatedAt player, ok := request.PlayerFrom(ctx) - if ok && isClientInList(conf.Server.Subsonic.MinimalClients, player.Client) { + if ok && isClientInList(conf.Server().Subsonic.MinimalClients, player.Client) { return pls } @@ -150,7 +150,7 @@ func (api *Router) buildPlaylist(ctx context.Context, p model.Playlist) response func buildOSPlaylist(ctx context.Context, p model.Playlist) *responses.OpenSubsonicPlaylist { player, ok := request.PlayerFrom(ctx) - if ok && isClientInList(conf.Server.Subsonic.LegacyClients, player.Client) { + if ok && isClientInList(conf.Server().Subsonic.LegacyClients, player.Client) { return nil } pls := responses.OpenSubsonicPlaylist{} diff --git a/server/subsonic/playlists_test.go b/server/subsonic/playlists_test.go index c7775c0fa..7b0ebc3c9 100644 --- a/server/subsonic/playlists_test.go +++ b/server/subsonic/playlists_test.go @@ -50,7 +50,7 @@ var _ = Describe("buildPlaylist", func() { Context("with minimal client", func() { BeforeEach(func() { - conf.Server.Subsonic.MinimalClients = "minimal-client" + conf.Update(func(c *conf.Options) { c.Subsonic.MinimalClients = "minimal-client" }) player := model.Player{Client: "minimal-client"} ctx = request.WithPlayer(ctx, player) }) @@ -75,7 +75,7 @@ var _ = Describe("buildPlaylist", func() { Context("with non-minimal client", func() { BeforeEach(func() { - conf.Server.Subsonic.MinimalClients = "minimal-client" + conf.Update(func(c *conf.Options) { c.Subsonic.MinimalClients = "minimal-client" }) player := model.Player{Client: "regular-client"} ctx = request.WithPlayer(ctx, player) }) @@ -124,7 +124,7 @@ var _ = Describe("buildPlaylist", func() { Context("when minimal clients list is empty", func() { BeforeEach(func() { - conf.Server.Subsonic.MinimalClients = "" + conf.Update(func(c *conf.Options) { c.Subsonic.MinimalClients = "" }) player := model.Player{Client: "any-client"} ctx = request.WithPlayer(ctx, player) }) @@ -153,7 +153,7 @@ var _ = Describe("buildPlaylist", func() { Context("with legacy client", func() { BeforeEach(func() { - conf.Server.Subsonic.LegacyClients = "legacy-client" + conf.Update(func(c *conf.Options) { c.Subsonic.LegacyClients = "legacy-client" }) player := model.Player{Client: "legacy-client"} ctx = request.WithPlayer(ctx, player) }) @@ -207,7 +207,7 @@ var _ = Describe("buildPlaylist", func() { Context("with minimal client", func() { BeforeEach(func() { - conf.Server.Subsonic.MinimalClients = "minimal-client" + conf.Update(func(c *conf.Options) { c.Subsonic.MinimalClients = "minimal-client" }) player := model.Player{Client: "minimal-client"} ctx = request.WithPlayer(ctx, player) }) @@ -233,7 +233,7 @@ var _ = Describe("buildPlaylist", func() { Context("with non-minimal client", func() { BeforeEach(func() { - conf.Server.Subsonic.MinimalClients = "minimal-client" + conf.Update(func(c *conf.Options) { c.Subsonic.MinimalClients = "minimal-client" }) player := model.Player{Client: "regular-client"} ctx = request.WithPlayer(ctx, player) }) @@ -256,7 +256,7 @@ var _ = Describe("buildPlaylist", func() { Context("with legacy client", func() { BeforeEach(func() { - conf.Server.Subsonic.LegacyClients = "legacy-client" + conf.Update(func(c *conf.Options) { c.Subsonic.LegacyClients = "legacy-client" }) player := model.Player{Client: "legacy-client"} ctx = request.WithPlayer(ctx, player) }) diff --git a/server/subsonic/radio.go b/server/subsonic/radio.go index 2c4033467..19b0aa197 100644 --- a/server/subsonic/radio.go +++ b/server/subsonic/radio.go @@ -71,7 +71,7 @@ func (api *Router) GetInternetRadios(r *http.Request) (*responses.Subsonic, erro } player, _ := request.PlayerFrom(ctx) - if strings.Contains(conf.Server.Subsonic.LegacyClients, player.Client) { + if strings.Contains(conf.Server().Subsonic.LegacyClients, player.Client) { continue } // Add coverArt if not legacy client; only radios have an uploaded image as their sole art source diff --git a/server/subsonic/radio_test.go b/server/subsonic/radio_test.go index aa805abbf..cf53e1acd 100644 --- a/server/subsonic/radio_test.go +++ b/server/subsonic/radio_test.go @@ -5,7 +5,6 @@ import ( "net/http/httptest" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" @@ -56,8 +55,7 @@ var _ = Describe("Radio", func() { Context("with a non-legacy client", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Subsonic.LegacyClients = "legacy-client" + conf.Update(func(c *conf.Options) { c.Subsonic.LegacyClients = "legacy-client" }) player := model.Player{Client: "modern-client"} ctx = request.WithPlayer(ctx, player) }) @@ -94,8 +92,7 @@ var _ = Describe("Radio", func() { Context("with a legacy client", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Subsonic.LegacyClients = "legacy-client" + conf.Update(func(c *conf.Options) { c.Subsonic.LegacyClients = "legacy-client" }) player := model.Player{Client: "legacy-client"} ctx = request.WithPlayer(ctx, player) }) @@ -115,8 +112,7 @@ var _ = Describe("Radio", func() { Context("when no player in context", func() { It("does not include coverArt (empty client matches legacy list)", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Subsonic.LegacyClients = "legacy-client" + conf.Update(func(c *conf.Options) { c.Subsonic.LegacyClients = "legacy-client" }) r := httptest.NewRequest("GET", "/rest/getInternetRadios", nil) r = r.WithContext(ctx) @@ -130,8 +126,7 @@ var _ = Describe("Radio", func() { Context("when legacy clients list is empty", func() { BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.Subsonic.LegacyClients = "" + conf.Update(func(c *conf.Options) { c.Subsonic.LegacyClients = "" }) player := model.Player{Client: "any-client"} ctx = request.WithPlayer(ctx, player) }) diff --git a/server/subsonic/sharing.go b/server/subsonic/sharing.go index e5f4f2a54..85d9f9363 100644 --- a/server/subsonic/sharing.go +++ b/server/subsonic/sharing.go @@ -62,7 +62,7 @@ func (api *Router) CreateShare(r *http.Request) (*responses.Subsonic, error) { repo := api.share.Repository() share := &model.Share{ Description: description, - Downloadable: p.BoolOr("downloadable", conf.Server.DefaultDownloadableShare && conf.Server.EnableDownloads), + Downloadable: p.BoolOr("downloadable", conf.Server().DefaultDownloadableShare && conf.Server().EnableDownloads), ExpiresAt: new(p.TimeOr("expires", time.Time{})), ResourceIDs: strings.Join(ids, ","), } diff --git a/server/subsonic/stream.go b/server/subsonic/stream.go index fd26ccc4d..e0ae228c5 100644 --- a/server/subsonic/stream.go +++ b/server/subsonic/stream.go @@ -61,7 +61,7 @@ func (api *Router) Download(w http.ResponseWriter, r *http.Request) (*responses. return nil, err } - if !conf.Server.EnableDownloads { + if !conf.Server().EnableDownloads { log.Warn(ctx, "Downloads are disabled", "user", username, "id", id) return nil, newError(responses.ErrorAuthorizationFail, "downloads are disabled") } @@ -75,7 +75,7 @@ func (api *Router) Download(w http.ResponseWriter, r *http.Request) (*responses. format, _ := p.String("format") if format == "" { - if conf.Server.AutoTranscodeDownload { + if conf.Server().AutoTranscodeDownload { // if we are not provided a format, see if we have requested transcoding for this client // This must be enabled via a config option. For the UI, we are always given an option. // This will impact other clients which do not use the UI @@ -90,6 +90,9 @@ func (api *Router) Download(w http.ResponseWriter, r *http.Request) (*responses. } else { format = "raw" } + } else { + // An explicit download format must win over the player's forced transcoding + ctx = request.WithTranscoding(ctx, model.Transcoding{}) } setHeaders := func(name string) { diff --git a/server/subsonic/transcode_test.go b/server/subsonic/transcode_test.go index 1f2fdfcef..821fd423d 100644 --- a/server/subsonic/transcode_test.go +++ b/server/subsonic/transcode_test.go @@ -5,9 +5,11 @@ import ( "context" "errors" "fmt" + "io" "io/fs" "net/http" "net/http/httptest" + "strconv" "github.com/navidrome/navidrome/core/ffmpeg" "github.com/navidrome/navidrome/core/stream" @@ -546,6 +548,60 @@ var _ = Describe("Transcode endpoints", func() { Expect(fakeStreamer.captured.Channels).To(Equal(2)) Expect(fakeStreamer.captured.Offset).To(Equal(10)) }) + + Describe("serving the stream", func() { + transcoded := []byte("transcoded audio") + + serve := func(method string, newStream func(*model.MediaFile) *stream.Stream, params ...string) { + router = New(ds, nil, &fakeMediaStreamer{newStream: newStream}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, mockTD, nil) + mockMFRepo.SetData(model.MediaFiles{{ID: "song-1", Title: "Song", Duration: 10}}) + mockTD.resolvedReq = stream.Request{Format: "mp3", BitRate: 128} + r := newGetRequest(append([]string{"mediaId=song-1", "mediaType=song", "transcodeParams=valid-token"}, params...)...) + r.Method = method + _, _ = router.GetTranscodeStream(w, r) + } + inProgress := func(mf *model.MediaFile) *stream.Stream { + return stream.NewStream(mf, "mp3", 128, io.NopCloser(bytes.NewReader(transcoded))) + } + completed := func(mf *model.MediaFile) *stream.Stream { + rs := bytes.NewReader(transcoded) + s := stream.NewStream(mf, "mp3", 128, io.NopCloser(rs)) + s.Seeker = rs + return s + } + + It("returns 200 on HEAD for a transcode that is not cached yet", func() { + serve(http.MethodHead, inProgress) + + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(w.Header().Get("Content-Type")).To(Equal("audio/mpeg")) + Expect(w.Body.Len()).To(BeZero()) + }) + + It("declares the estimated length on HEAD for a transcode not cached yet, when asked", func() { + serve(http.MethodHead, inProgress, "estimateContentLength=true") + + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(w.Header().Get("Content-Length")).ToNot(BeEmpty()) + }) + + // Guards the seekable path, which must keep answering HEAD with 200 and the real length. + It("returns 200 with the real length on HEAD for a transcode completed in the cache", func() { + serve(http.MethodHead, completed) + + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(w.Header().Get("Content-Length")).To(Equal(strconv.Itoa(len(transcoded)))) + Expect(w.Header().Get("Accept-Ranges")).To(Equal("bytes")) + }) + + It("still returns 500 on GET when the transcoder produces no output", func() { + serve(http.MethodGet, func(mf *model.MediaFile) *stream.Stream { + return stream.NewStream(mf, "mp3", 128, io.NopCloser(bytes.NewReader(nil))) + }) + + Expect(w.Code).To(Equal(http.StatusInternalServerError)) + }) + }) }) Describe("bpsToKbps", func() { @@ -642,15 +698,20 @@ func (m *mockTranscodeDecision) ResolveRequestFromToken(_ context.Context, _ str return req, nil } -// fakeMediaStreamer captures the StreamRequest and returns a sentinel error, -// allowing tests to verify parameter passing without constructing a real Stream. +// fakeMediaStreamer captures the StreamRequest. Without newStream it returns a sentinel error, +// allowing tests to verify parameter passing without constructing a real Stream. With newStream +// it hands the handler a real Stream, so tests can check what Serve writes. var errStreamCaptured = errors.New("stream request captured") type fakeMediaStreamer struct { - captured *stream.Request + captured *stream.Request + newStream func(*model.MediaFile) *stream.Stream } -func (f *fakeMediaStreamer) NewStream(_ context.Context, _ *model.MediaFile, req stream.Request) (*stream.Stream, error) { +func (f *fakeMediaStreamer) NewStream(_ context.Context, mf *model.MediaFile, req stream.Request) (*stream.Stream, error) { f.captured = &req + if f.newStream != nil { + return f.newStream(mf), nil + } return nil, errStreamCaptured } diff --git a/server/subsonic/users.go b/server/subsonic/users.go index acf8de3e8..df18c2467 100644 --- a/server/subsonic/users.go +++ b/server/subsonic/users.go @@ -20,14 +20,14 @@ func buildUserResponse(user model.User) responses.User { Email: user.Email, StreamRole: true, ScrobblingEnabled: true, - DownloadRole: conf.Server.EnableDownloads, - ShareRole: conf.Server.EnableSharing, - CoverArtRole: conf.Server.EnableArtworkUpload || user.IsAdmin, + DownloadRole: conf.Server().EnableDownloads, + ShareRole: conf.Server().EnableSharing, + CoverArtRole: conf.Server().EnableArtworkUpload || user.IsAdmin, Folder: slice.Map(user.Libraries, func(lib model.Library) int32 { return int32(lib.ID) }), } - if conf.Server.Jukebox.Enabled { - userResponse.JukeboxRole = !conf.Server.Jukebox.AdminOnly || user.IsAdmin + if conf.Server().Jukebox.Enabled { + userResponse.JukeboxRole = !conf.Server().Jukebox.AdminOnly || user.IsAdmin } return userResponse diff --git a/server/subsonic/users_test.go b/server/subsonic/users_test.go index 2d08b3377..5767a4c0e 100644 --- a/server/subsonic/users_test.go +++ b/server/subsonic/users_test.go @@ -5,7 +5,6 @@ import ( "net/http/httptest" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/server/subsonic/responses" @@ -18,7 +17,6 @@ var _ = Describe("Users", func() { var testUser model.User BeforeEach(func() { - DeferCleanup(configtest.SetupConfig()) router = &Router{} testUser = model.User{ @@ -32,9 +30,11 @@ var _ = Describe("Users", func() { Describe("Happy path", func() { It("should return consistent user data in both GetUser and GetUsers", func() { - conf.Server.EnableDownloads = true - conf.Server.EnableSharing = true - conf.Server.Jukebox.Enabled = false + conf.Update(func(c *conf.Options) { + c.EnableDownloads = true + c.EnableSharing = true + c.Jukebox.Enabled = false + }) // Set up user with libraries testUser.Libraries = model.Libraries{ @@ -90,8 +90,10 @@ var _ = Describe("Users", func() { DescribeTable("Jukebox role permissions", func(jukeboxEnabled, adminOnly, isAdmin, expectedJukeboxRole bool) { - conf.Server.Jukebox.Enabled = jukeboxEnabled - conf.Server.Jukebox.AdminOnly = adminOnly + conf.Update(func(c *conf.Options) { + c.Jukebox.Enabled = jukeboxEnabled + c.Jukebox.AdminOnly = adminOnly + }) testUser.IsAdmin = isAdmin response := buildUserResponse(testUser) @@ -106,7 +108,7 @@ var _ = Describe("Users", func() { DescribeTable("CoverArt role permissions", func(enableArtworkUpload, isAdmin, expectedCoverArtRole bool) { - conf.Server.EnableArtworkUpload = enableArtworkUpload + conf.Update(func(c *conf.Options) { c.EnableArtworkUpload = enableArtworkUpload }) testUser.IsAdmin = isAdmin response := buildUserResponse(testUser) diff --git a/server/throttle_backlog.go b/server/throttle_backlog.go index 0d31d289e..f462ea085 100644 --- a/server/throttle_backlog.go +++ b/server/throttle_backlog.go @@ -38,7 +38,7 @@ func ThrottleBacklog(limit, backlogLimit int, backlogTimeout time.Duration) func if limit <= 0 { return func(next http.Handler) http.Handler { return next } } - if !conf.Server.DevArtworkThrottleBuffered { + if !conf.Server().DevArtworkThrottleBuffered { return middleware.ThrottleBacklog(limit, backlogLimit, backlogTimeout) } t := &requestThrottle{ diff --git a/server/throttle_backlog_test.go b/server/throttle_backlog_test.go index 4d8567db5..2a57422ca 100644 --- a/server/throttle_backlog_test.go +++ b/server/throttle_backlog_test.go @@ -13,7 +13,6 @@ import ( "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -190,8 +189,7 @@ var _ = Describe("ThrottleBacklog", func() { }) It("starves concurrent requests with Chi's original middleware", func() { - DeferCleanup(configtest.SetupConfig()) - conf.Server.DevArtworkThrottleBuffered = false + conf.Update(func(c *conf.Options) { c.DevArtworkThrottleBuffered = false }) router, unblocked, reqDone := slowClientTest(ThrottleBacklog(1, 1, 500*time.Millisecond)) diff --git a/tests/harness/harness.go b/tests/harness/harness.go index 67f3150a2..6e92fe763 100644 --- a/tests/harness/harness.go +++ b/tests/harness/harness.go @@ -47,13 +47,13 @@ func CreateFS(files fstest.MapFS) storagetest.FakeFS { // SetupDB boots the golden database: a temp SQLite file, the given users (password "password", // all with access to the seeded "Music Library"), a full scan of the registered fake FS, and a -// snapshot for per-test restore. Callers must set conf.Server.MusicFolder and register the FS +// snapshot for per-test restore. Callers must set MusicFolder and register the FS // first; each user's Libraries field is populated in place. func SetupDB(ctx context.Context, users ...*model.User) *DB { tmpDir := ginkgo.GinkgoT().TempDir() h := &DB{FilePath: filepath.Join(tmpDir, "test-e2e.db")} h.SnapshotPath = h.FilePath + ".snapshot" - conf.Server.DbPath = h.FilePath + "?_journal_mode=WAL" + conf.Update(func(c *conf.Options) { c.DbPath = h.FilePath + "?_journal_mode=WAL" }) db.Db().SetMaxOpenConns(1) db.Init(ctx) diff --git a/utils/cache/benchmark_test.go b/utils/cache/benchmark_test.go index 9ab07cf18..a25c2191c 100644 --- a/utils/cache/benchmark_test.go +++ b/utils/cache/benchmark_test.go @@ -11,7 +11,6 @@ import ( "testing" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" ) type benchItem struct { @@ -27,8 +26,8 @@ func setupBenchCache(b *testing.B, cacheSize string, getReader ReadFunc) (*fileC if err != nil { b.Fatal(err) } - b.Cleanup(configtest.SetupConfig()) - conf.Server.CacheFolder = conf.NewDir(tmpDir) + b.Cleanup(conf.SnapshotConfig()) + conf.Update(func(c *conf.Options) { c.CacheFolder = conf.NewDir(tmpDir) }) fc := NewFileCache("bench", cacheSize, "bench", 0, getReader).(*fileCache) diff --git a/utils/cache/cache_suite_test.go b/utils/cache/cache_suite_test.go index 8c0d28979..e3fefa6f1 100644 --- a/utils/cache/cache_suite_test.go +++ b/utils/cache/cache_suite_test.go @@ -3,6 +3,7 @@ package cache 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 TestCache(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Cache Suite") } + +var _ = configtest.RestoreAfterEachSpec() diff --git a/utils/cache/file_caches.go b/utils/cache/file_caches.go index 48cd135cb..43a0c70ff 100644 --- a/utils/cache/file_caches.go +++ b/utils/cache/file_caches.go @@ -298,7 +298,7 @@ func newFSCache(name, cacheSize, cacheFolder string, maxItems int) (fscache.Cach lru := NewFileHaunter(name, maxItems, size, consts.DefaultCacheCleanUpInterval) h := fscache.NewLRUHaunterStrategy(lru) - cacheFolder = filepath.Join(conf.Server.CacheFolder.MustPath(), cacheFolder) + cacheFolder = filepath.Join(conf.Server().CacheFolder.MustPath(), cacheFolder) var fs *spreadFS log.Info(fmt.Sprintf("Creating %s cache", name), "path", cacheFolder, "maxSize", humanize.Bytes(size)) diff --git a/utils/cache/file_caches_test.go b/utils/cache/file_caches_test.go index 3189de6b2..609a54d39 100644 --- a/utils/cache/file_caches_test.go +++ b/utils/cache/file_caches_test.go @@ -11,7 +11,6 @@ import ( "time" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/conf/configtest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -27,17 +26,16 @@ var _ = Describe("File Caches", func() { BeforeEach(func() { tmpDir, _ := os.MkdirTemp("", "file_caches") DeferCleanup(func() { - configtest.SetupConfig() _ = os.RemoveAll(tmpDir) }) - conf.Server.CacheFolder = conf.NewDir(tmpDir) + conf.Update(func(c *conf.Options) { c.CacheFolder = conf.NewDir(tmpDir) }) }) Describe("NewFileCache", func() { It("creates the cache folder", func() { Expect(callNewFileCache("test", "1k", "test", 0, nil)).ToNot(BeNil()) - _, err := os.Stat(filepath.Join(conf.Server.CacheFolder.String(), "test")) + _, err := os.Stat(filepath.Join(conf.Server().CacheFolder.String(), "test")) Expect(os.IsNotExist(err)).To(BeFalse()) }) @@ -218,7 +216,7 @@ var _ = Describe("File Caches", func() { _ = fc1 // Plant a partial file (no marker), simulating a killed process. - sfs, err := NewSpreadFS(filepath.Join(conf.Server.CacheFolder.String(), "test"), 0755) + sfs, err := NewSpreadFS(filepath.Join(conf.Server().CacheFolder.String(), "test"), 0755) Expect(err).To(BeNil()) partialPath := sfs.KeyMapper((&testArg{"track"}).Key()) Expect(os.MkdirAll(filepath.Dir(partialPath), 0755)).To(Succeed()) diff --git a/utils/str/sanitize_strings.go b/utils/str/sanitize_strings.go index 11f828270..09ae2d591 100644 --- a/utils/str/sanitize_strings.go +++ b/utils/str/sanitize_strings.go @@ -79,7 +79,7 @@ func SanitizeFieldForSortingNoArticle(originalValue string) string { } func RemoveArticle(name string) string { - articles := strings.SplitSeq(conf.Server.IgnoredArticles, " ") + articles := strings.SplitSeq(conf.Server().IgnoredArticles, " ") for a := range articles { n := strings.TrimPrefix(name, a+" ") if n != name { diff --git a/utils/str/sanitize_strings_test.go b/utils/str/sanitize_strings_test.go index 6527f326b..8280340b9 100644 --- a/utils/str/sanitize_strings_test.go +++ b/utils/str/sanitize_strings_test.go @@ -51,7 +51,7 @@ var _ = Describe("Sanitize Strings", func() { Describe("SanitizeFieldForSorting", func() { BeforeEach(func() { - conf.Server.IgnoredArticles = "The O" + conf.Update(func(c *conf.Options) { c.IgnoredArticles = "The O" }) }) It("sanitize accents", func() { Expect(str.SanitizeFieldForSorting("Céu")).To(Equal("ceu")) @@ -95,7 +95,7 @@ var _ = Describe("Sanitize Strings", func() { Describe("SanitizeFieldForSortingNoArticle", func() { BeforeEach(func() { - conf.Server.IgnoredArticles = "The O" + conf.Update(func(c *conf.Options) { c.IgnoredArticles = "The O" }) }) It("sanitize accents", func() { Expect(str.SanitizeFieldForSortingNoArticle("Céu")).To(Equal("ceu")) @@ -111,7 +111,7 @@ var _ = Describe("Sanitize Strings", func() { Describe("RemoveArticle", func() { Context("Empty articles list", func() { BeforeEach(func() { - conf.Server.IgnoredArticles = "" + conf.Update(func(c *conf.Options) { c.IgnoredArticles = "" }) }) It("returns empty if string is empty", func() { Expect(str.RemoveArticle("")).To(BeEmpty()) @@ -122,7 +122,7 @@ var _ = Describe("Sanitize Strings", func() { }) Context("Default articles", func() { BeforeEach(func() { - conf.Server.IgnoredArticles = "The El La Los Las Le Les Os As O A" + conf.Update(func(c *conf.Options) { c.IgnoredArticles = "The El La Los Las Le Les Os As O A" }) }) It("returns empty if string is empty", func() { Expect(str.RemoveArticle("")).To(BeEmpty()) diff --git a/utils/str/str_suite_test.go b/utils/str/str_suite_test.go index 15cb12783..5a9c9ac1f 100644 --- a/utils/str/str_suite_test.go +++ b/utils/str/str_suite_test.go @@ -3,6 +3,7 @@ package str_test import ( "testing" + "github.com/navidrome/navidrome/conf/configtest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -11,3 +12,5 @@ func TestStrClear(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Str Suite") } + +var _ = configtest.RestoreAfterEachSpec()