Compare commits

...

20 commits

Author SHA1 Message Date
Alanna
bc8e5df565
chore(deps): bump navidrome-music-player to 4.25.6 (#6510)
Includes navidrome/react-music-player#9, which ignores Media Session
play/pause actions that match the current playback state.


Claude-Session: https://claude.ai/code/session_01XFQeuxfonumXTAghZ2YDtg

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-19 14:27:48 -05:00
Deluan Quintão
90ae2b6640
fix(playlists): bound playlist request bodies and id lists (#6505) 2026-11-18 13:55:16 -05:00
Deluan Quintão
a0c0992b4a
Merge commit from fork
* fix(playlists): bound the M3U playlist upload size

Uploading an M3U to POST /api/playlist had no limit on body size or entry
count. Every entry, duplicates included, was kept in memory, copied into the
playlist, saved and written back in the response, so one large upload could
use enough memory to stop the server.

The upload body is now capped at 32 MiB and the import at 50,000 entries.
Both return 413 and nothing is saved. Read errors from the body are no longer
dropped by the line scanner, so a cut-off body does not save a partial
playlist. Playlists imported from disk by the scanner keep no entry cap,
because real on-disk playlists can be larger (90k+ tracks).

* refactor(playlists): map upload limit errors in writePlaylistError

The 413 mapping for oversized or too-long M3U uploads now lives in
writePlaylistError with the other playlist error statuses, so the upload
handler has a single error path. The bare 0 passed to parseM3U for on-disk
playlists is now the named noEntryLimit.

* fix(playlists): run M3U upload imports one at a time

One upload at the 50,000 entry limit can peak at a few hundred MB, so
several sent together could still use up a small server's memory. Upload
imports now take a single package-wide slot before reading the body. Other
uploads wait for it, or return when their request is cancelled. Measured on a
live server: three concurrent 50,000-entry uploads peaked at 1,030 MB before
this change and 553 MB after.
2026-11-18 12:33:16 -05:00
Deluan Quintão
ba717b7130
fix(persistence): give admins every library when loading users (#6503) 2026-11-18 12:07:12 -05:00
Deluan Quintão
6789f278c4
feat(ui): add UIAppendRemixers option to hide remixers from the Artist column (#6504) 2026-11-18 11:08:13 -05:00
Deluan Quintão
ebdf2dc693
fix(persistence): show all genres to admins without user_library rows (#6502) 2026-11-18 09:17:14 -05:00
Nenad
2f85c631bf
fix(server): don't update last access for internal plugin calls (#6501)
Plugin SubsonicAPI calls are served by the Subsonic router as the user, so UpdateLastAccessMiddleware marked every user a plugin reads for as active. These requests already carry request.WithInternalAuth; skip the update for them.

Fixes #6497

Signed-off-by: nenadjokic <nenad.jokic@me.com>
2026-11-18 08:40:43 -05:00
Deluan Quintão
a40f7b870f
chore(lint): enable perfsprint (#6492) 2026-11-17 21:18:14 -05:00
Deluan Quintão
3a9e88a0dd
chore(lint): enable usestdlibvars (#6491) 2026-11-17 20:58:17 -05:00
Deluan Quintão
798305ef09
chore(lint): enable godoclint start-with-name (#6498) 2026-11-17 20:38:14 -05:00
Deluan Quintão
110567aaca
chore(lint): enable ginkgolinter (#6489)
Enforces idiomatic Gomega matchers (HaveOccurred, Succeed, HaveLen, BeEmpty, BeTrue), time.Duration async
intervals, To/ToNot over Should/Not, and forbids focused containers. Fixes 388 sites, 381 by autofix.
Four sort-order checks in the genre and tag repository tests had no To() and never ran; the two genre ones
also used inverted comparators and are now corrected.
2026-11-16 23:38:07 -05:00
Deluan Quintão
1286fdfc9c
chore(lint): enable thelper (#6488)
thelper requires test helpers to call t.Helper() first, so failures point
at the caller, and keeps the testing param first. Fixed 7 sites by hand:
4 helpers now call Helper(), 3 subtest bodies inlined into t.Run.
The parameter name checks are off: renaming t to tb adds churn, not
better line numbers.
2026-11-16 23:38:07 -05:00
Deluan Quintão
3fca50b808
chore(lint): enable exhaustive (#6487)
Switches on our own enum types must list every value, even when a default
exists, so adding a new value fails lint at each switch that forgot it.
Listed the missing values in 7 switches, keeping behaviour identical.
reflect.Kind and taglib.FileFormat are ignored: they are third-party enums.
2026-11-16 23:38:06 -05:00
Deluan Quintão
986000db44
chore(lint): enable errchkjson (#6486)
errchkjson flags json.Marshal/MarshalIndent/Encoder.Encode calls whose error is discarded.
Fixed all 27 sites by hand: errors are returned where the caller already returns one, logged
in HTTP handlers and string-returning helpers, and asserted in tests.
check-error-free-encoding stays off so every encode error is handled, even for safe types.
report-no-exported is on, to catch structs that would silently encode as {}.
2026-11-16 23:18:26 -05:00
Deluan Quintão
e9c0efa446
chore(lint): enable staticcheck (#6485)
Enforces the default staticcheck SA, S, ST and QF checks; fixed 76 sites (54 autofixed quick fixes, 22 by hand).
Dot imports are allowed only for squirrel, the established query builder style in persistence.
SA1019 is excluded for the deprecated plugins/types.SongRef wire fields the host still reads and writes for older plugins.
Also fixes an off-by-one in the redactrus test levelThreshold helper that panicked one level past TraceLevel.
2026-11-16 22:48:42 -05:00
chris_debian
232a598e75
fix(playlists): map removal indexes onto the visible track list (#6468) 2026-11-16 18:17:16 -05:00
Deluan Quintão
f3e520d380
chore(lint): enable modernize and usetesting (#6484) 2026-11-16 16:59:51 -05:00
Deluan Quintão
644ecf88ee
fix(playqueue): keep the current track when earlier tracks are missing (#6299) 2026-11-16 16:23:01 -05:00
Deluan Quintão
35948d566d
fix(transcoding): honor an explicitly requested lossless format for lossy files (#6472) 2026-11-16 14:53:13 -05:00
Deluan Quintão
9b959c5404
feat(ui): add a volume control to the share player (#6451) 2026-11-16 14:29:33 -05:00
332 changed files with 3715 additions and 1907 deletions

View file

@ -14,21 +14,29 @@ linters:
- depguard - depguard
- dogsled - dogsled
- durationcheck - durationcheck
- errchkjson
- errorlint - errorlint
- exhaustive
- forbidigo - forbidigo
- ginkgolinter
- gocritic - gocritic
- gocyclo - gocyclo
- godoclint
- goprintffuncname - goprintffuncname
- gosec - gosec
- misspell - misspell
- modernize
- nakedret - nakedret
- nilerr - nilerr
- nolintlint - nolintlint
- perfsprint
- rowserrcheck - rowserrcheck
- unconvert
- whitespace
disable:
- staticcheck - staticcheck
- thelper
- unconvert
- usestdlibvars
- usetesting
- whitespace
settings: settings:
depguard: depguard:
rules: rules:
@ -123,6 +131,22 @@ linters:
errcheck: errcheck:
exclude-functions: exclude-functions:
- (*github.com/zeebo/xxh3.Hasher).Write - (*github.com/zeebo/xxh3.Hasher).Write
errchkjson:
report-no-exported: true
ginkgolinter:
forbid-focus-container: true
force-expect-to: true
force-succeed: true
force-tonot: true
validate-async-intervals: true
godoclint:
# a doc comment that names another symbol (left behind by a move or a paste) is a bug
default: none
enable:
- start-with-name
options:
start-with-name:
include-unexported: true
gocritic: gocritic:
disable-all: true disable-all: true
enabled-checks: enabled-checks:
@ -133,6 +157,9 @@ linters:
- G401 - G401
- G505 - G505
- G115 - G115
exhaustive:
# third-party enums: listing every value only adds noise; our own enums must be listed in full
ignore-enum-types: ^(reflect\.Kind|go\.senan\.xyz/taglib\.FileFormat)$
forbidigo: forbidigo:
forbid: forbid:
- pattern: 'tx\.Exec$' - pattern: 'tx\.Exec$'
@ -151,6 +178,19 @@ linters:
govet: govet:
enable: enable:
- nilness - nilness
staticcheck:
dot-import-whitelist:
- github.com/Masterminds/squirrel
thelper:
# Helper() is what fixes failure line numbers; the t/tb/b/f parameter name does not
test:
name: false
benchmark:
name: false
tb:
name: false
fuzz:
name: false
exclusions: exclusions:
rules: rules:
- linters: - linters:
@ -169,6 +209,11 @@ linters:
linters: linters:
- forbidigo - forbidigo
text: "in tests use" text: "in tests use"
# the host must keep reading and writing these deprecated fields for older plugins
- path: ^plugins/
linters:
- staticcheck
text: 'SA1019: \(github\.com/navidrome/navidrome/plugins/types\.SongRef\)\.(Artist|ArtistMBID|Duration) is deprecated'
generated: lax generated: lax
presets: presets:
- comments - comments

View file

@ -54,7 +54,7 @@ func (c *client) searchArtists(ctx context.Context, name string, limit int) ([]A
params.Add("q", name) params.Add("q", name)
params.Add("order", "RANKING") params.Add("order", "RANKING")
params.Add("limit", strconv.Itoa(limit)) params.Add("limit", strconv.Itoa(limit))
req, err := http.NewRequestWithContext(ctx, "GET", apiBaseURL+"/search/artist", nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiBaseURL+"/search/artist", nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -90,7 +90,7 @@ func (c *client) makeRequest(req *http.Request, response any) error {
if err := parseBodyError(data); err != nil { if err := parseBodyError(data); err != nil {
return err return err
} }
if resp.StatusCode != 200 { if resp.StatusCode != http.StatusOK {
return fmt.Errorf("deezer http status: (%d)", resp.StatusCode) return fmt.Errorf("deezer http status: (%d)", resp.StatusCode)
} }
@ -113,7 +113,7 @@ func parseBodyError(data []byte) error {
} }
func (c *client) getRelatedArtists(ctx context.Context, artistID int) ([]Artist, error) { func (c *client) getRelatedArtists(ctx context.Context, artistID int) ([]Artist, error) {
req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("%s/artist/%d/related", apiBaseURL, artistID), nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s/artist/%d/related", apiBaseURL, artistID), nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -130,7 +130,7 @@ func (c *client) getRelatedArtists(ctx context.Context, artistID int) ([]Artist,
func (c *client) getTopTracks(ctx context.Context, artistID int, limit int) ([]Track, error) { func (c *client) getTopTracks(ctx context.Context, artistID int, limit int) ([]Track, error) {
params := url.Values{} params := url.Values{}
params.Add("limit", strconv.Itoa(limit)) params.Add("limit", strconv.Itoa(limit))
req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("%s/artist/%d/top", apiBaseURL, artistID), nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s/artist/%d/top", apiBaseURL, artistID), nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -174,7 +174,7 @@ func (c *client) getArtistBio(ctx context.Context, artistID int, lang string) (s
return "", err return "", err
} }
req, err := http.NewRequestWithContext(ctx, "POST", pipeAPIURL, bytes.NewReader(body)) req, err := http.NewRequestWithContext(ctx, http.MethodPost, pipeAPIURL, bytes.NewReader(body))
if err != nil { if err != nil {
return "", err return "", err
} }
@ -190,7 +190,7 @@ func (c *client) getArtistBio(ctx context.Context, artistID int, lang string) (s
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != 200 { if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("deezer: failed to fetch biography: %s", resp.Status) return "", fmt.Errorf("deezer: failed to fetch biography: %s", resp.Status)
} }

View file

@ -43,7 +43,7 @@ func (c *client) getJWT(ctx context.Context) (string, error) {
} }
// Fetch a new anonymous token // Fetch a new anonymous token
req, err := http.NewRequestWithContext(ctx, "GET", authBaseURL+"/login/anonymous?jo=p&rto=c", nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, authBaseURL+"/login/anonymous?jo=p&rto=c", nil)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -55,7 +55,7 @@ func (c *client) getJWT(ctx context.Context) (string, error) {
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != 200 { if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("deezer: failed to get JWT token: %s", resp.Status) return "", fmt.Errorf("deezer: failed to get JWT token: %s", resp.Status)
} }

View file

@ -30,32 +30,32 @@ var _ = Describe("JWT Authentication", func() {
It("successfully fetches and caches a JWT token", func() { It("successfully fetches and caches a JWT token", func() {
testJWT := createTestJWT(5 * time.Minute) testJWT := createTestJWT(5 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
}) })
token, err := client.getJWT(ctx) token, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token).To(Equal(testJWT)) Expect(token).To(Equal(testJWT))
}) })
It("returns the cached token on subsequent calls", func() { It("returns the cached token on subsequent calls", func() {
testJWT := createTestJWT(5 * time.Minute) testJWT := createTestJWT(5 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
}) })
// First call should fetch from API // First call should fetch from API
token1, err := client.getJWT(ctx) token1, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token1).To(Equal(testJWT)) Expect(token1).To(Equal(testJWT))
Expect(httpClient.lastRequest.URL.Path).To(Equal("/login/anonymous")) Expect(httpClient.lastRequest.URL.Path).To(Equal("/login/anonymous"))
// Second call should return cached token without hitting API // Second call should return cached token without hitting API
httpClient.lastRequest = nil // Clear last request to verify no new request is made httpClient.lastRequest = nil // Clear last request to verify no new request is made
token2, err := client.getJWT(ctx) token2, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token2).To(Equal(testJWT)) Expect(token2).To(Equal(testJWT))
Expect(httpClient.lastRequest).To(BeNil()) // No new request made Expect(httpClient.lastRequest).To(BeNil()) // No new request made
}) })
@ -65,17 +65,17 @@ var _ = Describe("JWT Authentication", func() {
testToken, err := jwt.NewBuilder(). testToken, err := jwt.NewBuilder().
Expiration(expectedExpiration). Expiration(expectedExpiration).
Build() Build()
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature()) testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))),
}) })
token, err := client.getJWT(ctx) token, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token).ToNot(BeEmpty()) Expect(token).ToNot(BeEmpty())
// Verify the token is cached until close to expiration // Verify the token is cached until close to expiration
@ -90,7 +90,7 @@ var _ = Describe("JWT Authentication", func() {
// Create a token that expires in 30 seconds (less than 1-minute buffer) // Create a token that expires in 30 seconds (less than 1-minute buffer)
testJWT := createTestJWT(30 * time.Second) testJWT := createTestJWT(30 * time.Second)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
}) })
@ -103,7 +103,7 @@ var _ = Describe("JWT Authentication", func() {
// Create a token that expired 1 minute ago // Create a token that expired 1 minute ago
testJWT := createTestJWT(-1 * time.Minute) testJWT := createTestJWT(-1 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
}) })
@ -116,12 +116,12 @@ var _ = Describe("JWT Authentication", func() {
// Create a token that expires in 2 minutes (just over the 1-minute buffer) // Create a token that expires in 2 minutes (just over the 1-minute buffer)
testJWT := createTestJWT(2 * time.Minute) testJWT := createTestJWT(2 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
}) })
token, err := client.getJWT(ctx) token, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token).ToNot(BeEmpty()) Expect(token).ToNot(BeEmpty())
}) })
}) })
@ -129,7 +129,7 @@ var _ = Describe("JWT Authentication", func() {
Context("with invalid responses", func() { Context("with invalid responses", func() {
It("handles HTTP error responses", func() { It("handles HTTP error responses", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 500, StatusCode: http.StatusInternalServerError,
Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)),
}) })
@ -140,7 +140,7 @@ var _ = Describe("JWT Authentication", func() {
It("handles malformed JSON responses", func() { It("handles malformed JSON responses", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{invalid json}`)), Body: io.NopCloser(bytes.NewBufferString(`{invalid json}`)),
}) })
@ -151,7 +151,7 @@ var _ = Describe("JWT Authentication", func() {
It("handles responses with empty JWT field", func() { It("handles responses with empty JWT field", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"jwt":""}`)), Body: io.NopCloser(bytes.NewBufferString(`{"jwt":""}`)),
}) })
@ -162,7 +162,7 @@ var _ = Describe("JWT Authentication", func() {
It("handles invalid JWT tokens", func() { It("handles invalid JWT tokens", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"jwt":"not-a-valid-jwt"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"jwt":"not-a-valid-jwt"}`)),
}) })
@ -176,17 +176,17 @@ var _ = Describe("JWT Authentication", func() {
testToken, err := jwt.NewBuilder(). testToken, err := jwt.NewBuilder().
Claim("custom", "value"). Claim("custom", "value").
Build() Build()
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
// Verify token has no expiration // Verify token has no expiration
_, hasExp := testToken.Expiration() _, hasExp := testToken.Expiration()
Expect(hasExp).To(BeFalse()) Expect(hasExp).To(BeFalse())
testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature()) testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))),
}) })
@ -201,12 +201,12 @@ var _ = Describe("JWT Authentication", func() {
// First token expires in 5 minutes // First token expires in 5 minutes
firstJWT := createTestJWT(5 * time.Minute) firstJWT := createTestJWT(5 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, firstJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, firstJWT))),
}) })
token1, err := client.getJWT(ctx) token1, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token1).To(Equal(firstJWT)) Expect(token1).To(Equal(firstJWT))
// Manually expire the cached token // Manually expire the cached token
@ -215,12 +215,12 @@ var _ = Describe("JWT Authentication", func() {
// Second token with different expiration (10 minutes) // Second token with different expiration (10 minutes)
secondJWT := createTestJWT(10 * time.Minute) secondJWT := createTestJWT(10 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, secondJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, secondJWT))),
}) })
token2, err := client.getJWT(ctx) token2, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token2).To(Equal(secondJWT)) Expect(token2).To(Equal(secondJWT))
Expect(token2).ToNot(Equal(token1)) Expect(token2).ToNot(Equal(token1))
}) })

View file

@ -26,11 +26,11 @@ var _ = Describe("client", func() {
Describe("ArtistImages", func() { Describe("ArtistImages", func() {
It("returns artist images from a successful request", func() { It("returns artist images from a successful request", func() {
f, err := os.Open("tests/fixtures/deezer.search.artist.json") f, err := os.Open("tests/fixtures/deezer.search.artist.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: 200}) httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: http.StatusOK})
artists, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20) artists, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(artists).To(HaveLen(17)) Expect(artists).To(HaveLen(17))
Expect(artists[0].Name).To(Equal("Michael Jackson")) Expect(artists[0].Name).To(Equal("Michael Jackson"))
Expect(artists[0].PictureXl).To(Equal("https://cdn-images.dzcdn.net/images/artist/97fae13b2b30e4aec2e8c9e0c7839d92/1000x1000-000000-80-0-0.jpg")) Expect(artists[0].PictureXl).To(Equal("https://cdn-images.dzcdn.net/images/artist/97fae13b2b30e4aec2e8c9e0c7839d92/1000x1000-000000-80-0-0.jpg"))
@ -38,7 +38,7 @@ var _ = Describe("client", func() {
It("fails if artist was not found", func() { It("fails if artist was not found", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)), Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
}) })
@ -49,7 +49,7 @@ var _ = Describe("client", func() {
// Deezer answers 200 with no rate-limit headers when throttling, so this body is the only signal. // Deezer answers 200 with no rate-limit headers when throttling, so this body is the only signal.
It("reports an exhausted quota as a retryable error, not as a missing artist", func() { It("reports an exhausted quota as a retryable error, not as a missing artist", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString( Body: io.NopCloser(bytes.NewBufferString(
`{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)), `{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)),
}) })
@ -64,7 +64,7 @@ var _ = Describe("client", func() {
It("reports a non-quota body error as a plain error", func() { It("reports a non-quota body error as a plain error", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString( Body: io.NopCloser(bytes.NewBufferString(
`{"error":{"type":"Exception","message":"Invalid query","code":100}}`)), `{"error":{"type":"Exception","message":"Invalid query","code":100}}`)),
}) })
@ -80,11 +80,11 @@ var _ = Describe("client", func() {
Describe("TopTracks", func() { Describe("TopTracks", func() {
It("returns top tracks with artist and album info from a successful request", func() { It("returns top tracks with artist and album info from a successful request", func() {
f, err := os.Open("tests/fixtures/deezer.artist.top.json") f, err := os.Open("tests/fixtures/deezer.artist.top.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: 200}) httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: http.StatusOK})
tracks, err := client.getTopTracks(GinkgoT().Context(), 27, 5) tracks, err := client.getTopTracks(GinkgoT().Context(), 27, 5)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(tracks).To(HaveLen(5)) Expect(tracks).To(HaveLen(5))
// Verify first track has all expected fields // Verify first track has all expected fields
@ -104,18 +104,18 @@ var _ = Describe("client", func() {
// Mock the JWT token endpoint with a valid JWT that expires in 5 minutes // Mock the JWT token endpoint with a valid JWT that expires in 5 minutes
testJWT := createTestJWT(5 * time.Minute) testJWT := createTestJWT(5 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))),
}) })
}) })
It("returns artist bio from a successful request", func() { It("returns artist bio from a successful request", func() {
f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json") f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200}) httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
bio, err := client.getArtistBio(GinkgoT().Context(), 27, "en") bio, err := client.getArtistBio(GinkgoT().Context(), 27, "en")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(bio).To(ContainSubstring("Schoolmates Thomas and Guy-Manuel")) Expect(bio).To(ContainSubstring("Schoolmates Thomas and Guy-Manuel"))
Expect(bio).ToNot(ContainSubstring("<p>")) Expect(bio).ToNot(ContainSubstring("<p>"))
Expect(bio).ToNot(ContainSubstring("</p>")) Expect(bio).ToNot(ContainSubstring("</p>"))
@ -123,21 +123,21 @@ var _ = Describe("client", func() {
It("uses the provided language", func() { It("uses the provided language", func() {
f, err := os.Open("tests/fixtures/deezer.artist.bio.fr.json") f, err := os.Open("tests/fixtures/deezer.artist.bio.fr.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200}) httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
_, err = client.getArtistBio(GinkgoT().Context(), 27, "fr") _, err = client.getArtistBio(GinkgoT().Context(), 27, "fr")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.lastRequest.Header.Get("Accept-Language")).To(Equal("fr")) Expect(httpClient.lastRequest.Header.Get("Accept-Language")).To(Equal("fr"))
}) })
It("includes the JWT token in the request", func() { It("includes the JWT token in the request", func() {
f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json") f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200}) httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
_, err = client.getArtistBio(GinkgoT().Context(), 27, "en") _, err = client.getArtistBio(GinkgoT().Context(), 27, "en")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
// Verify that the Authorization header has the Bearer token format // Verify that the Authorization header has the Bearer token format
authHeader := httpClient.lastRequest.Header.Get("Authorization") authHeader := httpClient.lastRequest.Header.Get("Authorization")
Expect(authHeader).To(HavePrefix("Bearer ")) Expect(authHeader).To(HavePrefix("Bearer "))
@ -163,7 +163,7 @@ var _ = Describe("client", func() {
] ]
}` }`
httpClient.mock("https://pipe.deezer.com/api", http.Response{ httpClient.mock("https://pipe.deezer.com/api", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(errorResponse)), Body: io.NopCloser(bytes.NewBufferString(errorResponse)),
}) })
@ -185,7 +185,7 @@ var _ = Describe("client", func() {
} }
}` }`
httpClient.mock("https://pipe.deezer.com/api", http.Response{ httpClient.mock("https://pipe.deezer.com/api", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(emptyBioResponse)), Body: io.NopCloser(bytes.NewBufferString(emptyBioResponse)),
}) })
@ -195,7 +195,7 @@ var _ = Describe("client", func() {
It("handles JWT token fetch failure", func() { It("handles JWT token fetch failure", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 500, StatusCode: http.StatusInternalServerError,
Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)),
}) })
@ -208,7 +208,7 @@ var _ = Describe("client", func() {
// Create a JWT that expires in 30 seconds (less than the 1-minute buffer) // Create a JWT that expires in 30 seconds (less than the 1-minute buffer)
expiredJWT := createTestJWT(30 * time.Second) expiredJWT := createTestJWT(30 * time.Second)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, expiredJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, expiredJWT))),
}) })

View file

@ -48,7 +48,7 @@ var _ = Describe("deezerAgent", func() {
It("picks the exact-name match with the most fans when several share the name", func() { It("picks the exact-name match with the most fans when several share the name", func() {
// Deezer RANKING order returns a low-popularity homonym first (see issue #5802) // Deezer RANKING order returns a low-popularity homonym first (see issue #5802)
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[ Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":61045802,"name":"Queen","nb_fan":75}, {"id":61045802,"name":"Queen","nb_fan":75},
{"id":141954732,"name":"Queen","nb_fan":397}, {"id":141954732,"name":"Queen","nb_fan":397},
@ -66,7 +66,7 @@ var _ = Describe("deezerAgent", func() {
It("matches the name case-insensitively", func() { It("matches the name case-insensitively", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[ Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":1,"name":"QUEEN","nb_fan":10}, {"id":1,"name":"QUEEN","nb_fan":10},
{"id":2,"name":"queen","nb_fan":20} {"id":2,"name":"queen","nb_fan":20}
@ -83,7 +83,7 @@ var _ = Describe("deezerAgent", func() {
// lookup reaching that here would record a permanent absence. // lookup reaching that here would record a permanent absence.
It("surfaces an exhausted quota instead of reporting the artist as not found", func() { It("surfaces an exhausted quota instead of reporting the artist as not found", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString( Body: io.NopCloser(bytes.NewBufferString(
`{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)), `{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)),
}) })
@ -97,7 +97,7 @@ var _ = Describe("deezerAgent", func() {
It("returns ErrNotFound when no result matches the name exactly", func() { It("returns ErrNotFound when no result matches the name exactly", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[ Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":1,"name":"Queens of the Stone Age","nb_fan":100} {"id":1,"name":"Queens of the Stone Age","nb_fan":100}
],"total":1}`)), ],"total":1}`)),
@ -123,7 +123,7 @@ var _ = Describe("deezerAgent", func() {
It("returns the real images when the artist has a picture", func() { It("returns the real images when the artist has a picture", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[ Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":412,"name":"Queen","nb_fan":12744378, {"id":412,"name":"Queen","nb_fan":12744378,
"picture_xl":"https://cdn-images.dzcdn.net/images/artist/abc/1000x1000-000000-80-0-0.jpg", "picture_xl":"https://cdn-images.dzcdn.net/images/artist/abc/1000x1000-000000-80-0-0.jpg",
@ -140,7 +140,7 @@ var _ = Describe("deezerAgent", func() {
It("returns ErrNotFound when the artist only has empty-id placeholder pictures", func() { It("returns ErrNotFound when the artist only has empty-id placeholder pictures", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[ Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":412,"name":"Queen","nb_fan":12744378, {"id":412,"name":"Queen","nb_fan":12744378,
"picture_xl":"https://cdn-images.dzcdn.net/images/artist//1000x1000-000000-80-0-0.jpg", "picture_xl":"https://cdn-images.dzcdn.net/images/artist//1000x1000-000000-80-0-0.jpg",
@ -166,12 +166,12 @@ var _ = Describe("deezerAgent", func() {
// Mock search artist (returns Michael Jackson) // Mock search artist (returns Michael Jackson)
fSearch, _ := os.Open("tests/fixtures/deezer.search.artist.json") fSearch, _ := os.Open("tests/fixtures/deezer.search.artist.json")
httpClient.searchResponse = &http.Response{Body: fSearch, StatusCode: 200} httpClient.searchResponse = &http.Response{Body: fSearch, StatusCode: http.StatusOK}
// Mock JWT token // Mock JWT token
testJWT := createTestJWT(5 * time.Minute) testJWT := createTestJWT(5 * time.Minute)
httpClient.jwtResponse = &http.Response{ httpClient.jwtResponse = &http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))),
} }
}) })
@ -190,7 +190,7 @@ var _ = Describe("deezerAgent", func() {
// French biography available // French biography available
fFr, _ := os.Open("tests/fixtures/deezer.artist.bio.fr.json") fFr, _ := os.Open("tests/fixtures/deezer.artist.bio.fr.json")
httpClient.bioResponses["fr"] = &http.Response{Body: fFr, StatusCode: 200} httpClient.bioResponses["fr"] = &http.Response{Body: fFr, StatusCode: http.StatusOK}
bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "") bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
@ -205,10 +205,10 @@ var _ = Describe("deezerAgent", func() {
// Japanese returns empty biography // Japanese returns empty biography
fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json") fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: 200} httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: http.StatusOK}
// English returns full biography // English returns full biography
fEn, _ := os.Open("tests/fixtures/deezer.artist.bio.en.json") fEn, _ := os.Open("tests/fixtures/deezer.artist.bio.en.json")
httpClient.bioResponses["en"] = &http.Response{Body: fEn, StatusCode: 200} httpClient.bioResponses["en"] = &http.Response{Body: fEn, StatusCode: http.StatusOK}
bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "") bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
@ -224,9 +224,9 @@ var _ = Describe("deezerAgent", func() {
// Both languages return empty biography // Both languages return empty biography
fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json") fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: 200} httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: http.StatusOK}
fXx, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json") fXx, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
httpClient.bioResponses["xx"] = &http.Response{Body: fXx, StatusCode: 200} httpClient.bioResponses["xx"] = &http.Response{Body: fXx, StatusCode: http.StatusOK}
_, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "") _, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
@ -259,7 +259,7 @@ func (c *langAwareHttpClient) Do(req *http.Request) (*http.Response, error) {
return c.searchResponse, nil return c.searchResponse, nil
} }
return &http.Response{ return &http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)), Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
}, nil }, nil
} }
@ -270,7 +270,7 @@ func (c *langAwareHttpClient) Do(req *http.Request) (*http.Response, error) {
return c.jwtResponse, nil return c.jwtResponse, nil
} }
return &http.Response{ return &http.Response{
StatusCode: 500, StatusCode: http.StatusInternalServerError,
Body: io.NopCloser(bytes.NewBufferString(`{"error":"no mock"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":"no mock"}`)),
}, nil }, nil
} }
@ -285,7 +285,7 @@ func (c *langAwareHttpClient) Do(req *http.Request) (*http.Response, error) {
} }
// Return empty bio by default // Return empty bio by default
return &http.Response{ return &http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":{"artist":{"bio":{"full":""}}}}`)), Body: io.NopCloser(bytes.NewBufferString(`{"data":{"artist":{"bio":{"full":""}}}}`)),
}, nil }, nil
} }

View file

@ -13,9 +13,9 @@ var _ = Describe("Responses", func() {
It("parses the artist search result correctly ", func() { It("parses the artist search result correctly ", func() {
var resp SearchArtistResults var resp SearchArtistResults
body, err := os.ReadFile("tests/fixtures/deezer.search.artist.json") body, err := os.ReadFile("tests/fixtures/deezer.search.artist.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
err = json.Unmarshal(body, &resp) err = json.Unmarshal(body, &resp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(resp.Data).To(HaveLen(17)) Expect(resp.Data).To(HaveLen(17))
michael := resp.Data[0] michael := resp.Data[0]
@ -29,7 +29,7 @@ var _ = Describe("Responses", func() {
var errorResp errorResponse var errorResp errorResponse
body := []byte(`{"error":{"type":"MissingParameterException","message":"Missing parameters: q","code":501}}`) body := []byte(`{"error":{"type":"MissingParameterException","message":"Missing parameters: q","code":501}}`)
err := json.Unmarshal(body, &errorResp) err := json.Unmarshal(body, &errorResp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(errorResp.Error.Code).To(Equal(501)) Expect(errorResp.Error.Code).To(Equal(501))
Expect(errorResp.Error.Message).To(Equal("Missing parameters: q")) Expect(errorResp.Error.Message).To(Equal("Missing parameters: q"))
@ -40,9 +40,9 @@ var _ = Describe("Responses", func() {
It("parses the related artists response correctly", func() { It("parses the related artists response correctly", func() {
var resp RelatedArtists var resp RelatedArtists
body, err := os.ReadFile("tests/fixtures/deezer.artist.related.json") body, err := os.ReadFile("tests/fixtures/deezer.artist.related.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
err = json.Unmarshal(body, &resp) err = json.Unmarshal(body, &resp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(resp.Data).To(HaveLen(20)) Expect(resp.Data).To(HaveLen(20))
justice := resp.Data[0] justice := resp.Data[0]
@ -55,9 +55,9 @@ var _ = Describe("Responses", func() {
It("parses the top tracks response correctly", func() { It("parses the top tracks response correctly", func() {
var resp TopTracks var resp TopTracks
body, err := os.ReadFile("tests/fixtures/deezer.artist.top.json") body, err := os.ReadFile("tests/fixtures/deezer.artist.top.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
err = json.Unmarshal(body, &resp) err = json.Unmarshal(body, &resp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(resp.Data).To(HaveLen(5)) Expect(resp.Data).To(HaveLen(5))
track := resp.Data[0] track := resp.Data[0]

View file

@ -20,13 +20,13 @@ func (t testFileInfo) BirthTime() time.Time {
if ts := times.Get(t.FileInfo); ts.HasBirthTime() { if ts := times.Get(t.FileInfo); ts.HasBirthTime() {
return ts.BirthTime() return ts.BirthTime()
} }
return t.FileInfo.ModTime() return t.ModTime()
} }
var _ = Describe("Extractor", func() { var _ = Describe("Extractor", func() {
toP := func(name, sortName, mbid string) model.Participant { toP := func(name, sortName, mbid string) model.Participant {
return model.Participant{ return model.Participant{
Artist: model.Artist{Name: name, SortArtistName: sortName, MbzArtistID: mbid}, Name: name, SortArtistName: sortName, MbzArtistID: mbid,
} }
} }
@ -156,7 +156,7 @@ var _ = Describe("Extractor", func() {
mf := parseTestFile("tests/fixtures/" + file) mf := parseTestFile("tests/fixtures/" + file)
lyrics, err := mf.StructuredLyrics() lyrics, err := mf.StructuredLyrics()
Expect(err).To(Not(HaveOccurred())) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(2)) Expect(lyrics).To(HaveLen(2))
unspec := makeLyrics("xxx", "unspecified") unspec := makeLyrics("xxx", "unspecified")
@ -250,7 +250,7 @@ var _ = Describe("Extractor", func() {
// WMA has no Arranger role // WMA has no Arranger role
if role == model.RoleArranger { if role == model.RoleArranger {
Expect(actual).To(HaveLen(0)) Expect(actual).To(BeEmpty())
continue continue
} }

View file

@ -246,7 +246,7 @@ func parseASFAttributes(rawAttrs map[string][]string, tags map[string][]string)
} }
} }
// These are the only roles we support, based on Picard's tag map: // tiplMapping lists the only roles we support, based on Picard's tag map:
// https://picard-docs.musicbrainz.org/downloads/MusicBrainz_Picard_Tag_Map.html // https://picard-docs.musicbrainz.org/downloads/MusicBrainz_Picard_Tag_Map.html
var tiplMapping = map[string]string{ var tiplMapping = map[string]string{
"arranger": "arranger", "arranger": "arranger",

View file

@ -78,7 +78,7 @@ var _ = Describe("Extractor", func() {
// Test OGG // Test OGG
m = mds["tests/fixtures/test.ogg"] m = mds["tests/fixtures/test.ogg"]
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(m.Tags).To(HaveKeyWithValue("fbpm", []string{"141.7"})) Expect(m.Tags).To(HaveKeyWithValue("fbpm", []string{"141.7"}))
// TagLib 1.12 returns 18, previous versions return 39. // TagLib 1.12 returns 18, previous versions return 39.

View file

@ -243,8 +243,8 @@ var (
artistOpenGraphQuery = cascadia.MustCompile(`html > head > meta[property="og:image"]`) artistOpenGraphQuery = cascadia.MustCompile(`html > head > meta[property="og:image"]`)
artistIgnoredImage = "2a96cbd8b46e442fc41c2b86b821562f" // Last.fm artist placeholder image name artistIgnoredImage = "2a96cbd8b46e442fc41c2b86b821562f" // Last.fm artist placeholder image name
// Not a RetryLaterError on purpose: parking the agent would also stall its API-backed // errNoArtistPage is not a RetryLaterError on purpose: parking the agent would also stall its
// methods, which the page block does not affect. // API-backed methods, which the page block does not affect.
errNoArtistPage = errors.New("no artist image in Last.fm page") errNoArtistPage = errors.New("no artist image in Last.fm page")
) )

View file

@ -76,7 +76,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns the biography", func() { It("returns the biography", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
Expect(agent.GetArtistBiography(ctx, "123", "U2", "")).To(Equal("U2 é uma das mais importantes bandas de rock de todos os tempos. Formada em 1976 em Dublin, composta por Bono (vocalista e guitarrista), The Edge (guitarrista, pianista e backing vocal), Adam Clayton (baixista), Larry Mullen, Jr. (baterista e percussionista).\n\nDesde a década de 80, U2 é uma das bandas mais populares no mundo. Seus shows são únicos e um verdadeiro festival de efeitos especiais, além de serem um dos que mais arrecadam anualmente.")) Expect(agent.GetArtistBiography(ctx, "123", "U2", "")).To(Equal("U2 é uma das mais importantes bandas de rock de todos os tempos. Formada em 1976 em Dublin, composta por Bono (vocalista e guitarrista), The Edge (guitarrista, pianista e backing vocal), Adam Clayton (baixista), Larry Mullen, Jr. (baterista e percussionista).\n\nDesde a década de 80, U2 é uma das bandas mais populares no mundo. Seus shows são únicos e um verdadeiro festival de efeitos especiais, além de serem um dos que mais arrecadam anualmente."))
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("U2")) Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("U2"))
@ -91,7 +91,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns an error if Last.fm call returns an error", func() { It("returns an error if Last.fm call returns an error", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
_, err := agent.GetArtistBiography(ctx, "123", "U2", "") _, err := agent.GetArtistBiography(ctx, "123", "U2", "")
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -101,7 +101,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() { It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
_, err := agent.GetArtistBiography(ctx, "123", "U2", "") _, err := agent.GetArtistBiography(ctx, "123", "U2", "")
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue()) Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
@ -124,7 +124,7 @@ var _ = Describe("lastfmAgent", func() {
// Portuguese biography available // Portuguese biography available
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
httpClient.responses["pt"] = http.Response{Body: f, StatusCode: 200} httpClient.responses["pt"] = http.Response{Body: f, StatusCode: http.StatusOK}
bio, err := agent.GetArtistBiography(ctx, "123", "U2", "") bio, err := agent.GetArtistBiography(ctx, "123", "U2", "")
@ -141,10 +141,10 @@ var _ = Describe("lastfmAgent", func() {
// Japanese returns empty/ignored biography (actual Last.fm response with just "Read more" link) // Japanese returns empty/ignored biography (actual Last.fm response with just "Read more" link)
fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json") fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200} httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: http.StatusOK}
// English returns full biography // English returns full biography
fEn, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.en.json") fEn, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.en.json")
httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: 200} httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: http.StatusOK}
bio, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "") bio, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "")
@ -162,10 +162,10 @@ var _ = Describe("lastfmAgent", func() {
// Both languages return empty/ignored biography (using actual Last.fm response format) // Both languages return empty/ignored biography (using actual Last.fm response format)
fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json") fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200} httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: http.StatusOK}
// Second language also returns empty // Second language also returns empty
fXx, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json") fXx, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: 200} httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: http.StatusOK}
_, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "") _, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "")
@ -189,10 +189,10 @@ var _ = Describe("lastfmAgent", func() {
// Japanese returns album without wiki/description (actual Last.fm response) // Japanese returns album without wiki/description (actual Last.fm response)
fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json") fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200} httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: http.StatusOK}
// English returns album with description // English returns album with description
fEn, _ := os.Open("tests/fixtures/lastfm.album.getinfo.en.json") fEn, _ := os.Open("tests/fixtures/lastfm.album.getinfo.en.json")
httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: 200} httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: http.StatusOK}
albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "") albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "")
@ -211,9 +211,9 @@ var _ = Describe("lastfmAgent", func() {
// Both languages return album without description // Both languages return album without description
fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json") fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200} httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: http.StatusOK}
fXx, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json") fXx, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: 200} httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: http.StatusOK}
albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "") albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "")
@ -237,7 +237,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns similar artists", func() { It("returns similar artists", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
Expect(agent.GetSimilarArtists(ctx, "123", "U2", "", 2)).To(Equal([]agents.Artist{ Expect(agent.GetSimilarArtists(ctx, "123", "U2", "", 2)).To(Equal([]agents.Artist{
{Name: "Passengers", MBID: "e110c11f-1c94-4471-a350-c38f46b29389"}, {Name: "Passengers", MBID: "e110c11f-1c94-4471-a350-c38f46b29389"},
{Name: "INXS", MBID: "481bf5f9-2e7c-4c44-b08a-05b32bc7c00d"}, {Name: "INXS", MBID: "481bf5f9-2e7c-4c44-b08a-05b32bc7c00d"},
@ -255,7 +255,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns an error if Last.fm call returns an error", func() { It("returns an error if Last.fm call returns an error", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
_, err := agent.GetSimilarArtists(ctx, "123", "U2", "", 2) _, err := agent.GetSimilarArtists(ctx, "123", "U2", "", 2)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -275,7 +275,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns top songs", func() { It("returns top songs", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json") f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
Expect(agent.GetArtistTopSongs(ctx, "123", "U2", "", 2)).To(Equal([]agents.Song{ Expect(agent.GetArtistTopSongs(ctx, "123", "U2", "", 2)).To(Equal([]agents.Song{
{Name: "Beautiful Day", MBID: "f7f264d0-a89b-4682-9cd7-a4e7c37637af"}, {Name: "Beautiful Day", MBID: "f7f264d0-a89b-4682-9cd7-a4e7c37637af"},
{Name: "With or Without You", MBID: "6b9a509f-6907-4a6e-9345-2f12da09ba4b"}, {Name: "With or Without You", MBID: "6b9a509f-6907-4a6e-9345-2f12da09ba4b"},
@ -293,7 +293,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns an error if Last.fm call returns an error", func() { It("returns an error if Last.fm call returns an error", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
_, err := agent.GetArtistTopSongs(ctx, "123", "U2", "", 2) _, err := agent.GetArtistTopSongs(ctx, "123", "U2", "", 2)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -313,7 +313,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns similar songs", func() { It("returns similar songs", func() {
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json") f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
Expect(agent.GetSimilarSongsByTrack(ctx, "123", "Just Can't Get Enough", "Depeche Mode", "", 5)).To(Equal([]agents.Song{ Expect(agent.GetSimilarSongsByTrack(ctx, "123", "Just Can't Get Enough", "Depeche Mode", "", 5)).To(Equal([]agents.Song{
{Name: "Dreaming of Me", MBID: "027b553e-7c74-3ed4-a95e-1d4fea51f174", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"}}}, {Name: "Dreaming of Me", MBID: "027b553e-7c74-3ed4-a95e-1d4fea51f174", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"}}},
{Name: "Everything Counts", MBID: "5a5a3ca4-bdb8-4641-a674-9b54b9b319a6", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"}}}, {Name: "Everything Counts", MBID: "5a5a3ca4-bdb8-4641-a674-9b54b9b319a6", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"}}},
@ -328,7 +328,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrNotFound when no similar songs found", func() { It("returns ErrNotFound when no similar songs found", func() {
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json") f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := agent.GetSimilarSongsByTrack(ctx, "123", "UnknownTrack", "UnknownArtist", "", 3) _, err := agent.GetSimilarSongsByTrack(ctx, "123", "UnknownTrack", "UnknownArtist", "", 3)
Expect(err).To(MatchError(agents.ErrNotFound)) Expect(err).To(MatchError(agents.ErrNotFound))
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -342,7 +342,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns an error if Last.fm call returns an error", func() { It("returns an error if Last.fm call returns an error", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
_, err := agent.GetSimilarSongsByTrack(ctx, "123", "Believe", "Cher", "", 3) _, err := agent.GetSimilarSongsByTrack(ctx, "123", "Believe", "Cher", "", 3)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -370,12 +370,12 @@ var _ = Describe("lastfmAgent", func() {
MbzRecordingID: "mbz-123", MbzRecordingID: "mbz-123",
Participants: map[model.Role]model.ParticipantList{ Participants: map[model.Role]model.ParticipantList{
model.RoleArtist: []model.Participant{ model.RoleArtist: []model.Participant{
{Artist: model.Artist{ID: "ar-1", Name: "First Artist"}}, {ID: "ar-1", Name: "First Artist"},
{Artist: model.Artist{ID: "ar-2", Name: "Second Artist"}}, {ID: "ar-2", Name: "Second Artist"},
}, },
model.RoleAlbumArtist: []model.Participant{ model.RoleAlbumArtist: []model.Participant{
{Artist: model.Artist{ID: "ar-1", Name: "First Album Artist"}}, {ID: "ar-1", Name: "First Album Artist"},
{Artist: model.Artist{ID: "ar-2", Name: "Second Album Artist"}}, {ID: "ar-2", Name: "Second Album Artist"},
}, },
}, },
} }
@ -383,7 +383,7 @@ var _ = Describe("lastfmAgent", func() {
Describe("NowPlaying", func() { Describe("NowPlaying", func() {
It("calls Last.fm with correct params", func() { It("calls Last.fm with correct params", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
err := agent.NowPlaying(ctx, "user-1", track, 0) err := agent.NowPlaying(ctx, "user-1", track, 0)
@ -413,7 +413,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("uses only the first artist", func() { It("uses only the first artist", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
err := agent.NowPlaying(ctx, "user-1", track, 0) err := agent.NowPlaying(ctx, "user-1", track, 0)
@ -429,7 +429,7 @@ var _ = Describe("lastfmAgent", func() {
Describe("scrobble", func() { Describe("scrobble", func() {
It("calls Last.fm with correct params", func() { It("calls Last.fm with correct params", func() {
ts := time.Now() ts := time.Now()
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: ts}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: ts})
@ -456,7 +456,7 @@ var _ = Describe("lastfmAgent", func() {
It("uses only the first artist", func() { It("uses only the first artist", func() {
ts := time.Now() ts := time.Now()
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: ts}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: ts})
@ -470,7 +470,7 @@ var _ = Describe("lastfmAgent", func() {
It("skips songs at the 30-second minimum", func() { It("skips songs at the 30-second minimum", func() {
track.Duration = 30 track.Duration = 30
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -480,7 +480,7 @@ var _ = Describe("lastfmAgent", func() {
It("sends the duration parameter for a 30.5-second song", func() { It("sends the duration parameter for a 30.5-second song", func() {
track.Duration = 30.5 track.Duration = 30.5
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"scrobbles":{"scrobble":{"ignoredMessage":{"code":"0"}},"@attr":{"accepted":1}}}`)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"scrobbles":{"scrobble":{"ignoredMessage":{"code":"0"}},"@attr":{"accepted":1}}}`)), StatusCode: http.StatusOK}
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -495,7 +495,7 @@ var _ = Describe("lastfmAgent", func() {
It("skips songs according to the configured minimum duration", func() { It("skips songs according to the configured minimum duration", func() {
conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 60 * time.Second }) conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 60 * time.Second })
track.Duration = 59 track.Duration = 59
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -506,7 +506,7 @@ var _ = Describe("lastfmAgent", func() {
It("does not skip short songs when the minimum duration is disabled", func() { It("does not skip short songs when the minimum duration is disabled", func() {
conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 0 }) conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 0 })
track.Duration = 29 track.Duration = 29
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -526,7 +526,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrRetryLater on error 11", func() { It("returns ErrRetryLater on error 11", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":11,"message":"Service Offline - This service is temporarily offline. Try again later."}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":11,"message":"Service Offline - This service is temporarily offline. Try again later."}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -536,7 +536,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrRetryLater on error 16", func() { It("returns ErrRetryLater on error 16", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":16,"message":"There was a temporary error processing your request. Please try again"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":16,"message":"There was a temporary error processing your request. Please try again"}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -546,7 +546,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() { It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -556,7 +556,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrRetryLater on http errors", func() { It("returns ErrRetryLater on http errors", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`internal server error`)), Body: io.NopCloser(bytes.NewBufferString(`internal server error`)),
StatusCode: 500, StatusCode: http.StatusInternalServerError,
} }
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -566,7 +566,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrUnrecoverable on other errors", func() { It("returns ErrUnrecoverable on other errors", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":8,"message":"Operation failed - Something else went wrong"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":8,"message":"Operation failed - Something else went wrong"}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -587,7 +587,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns the biography", func() { It("returns the biography", func() {
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
Expect(agent.GetAlbumInfo(ctx, "Believe", "Cher", "03c91c40-49a6-44a7-90e7-a700edf97a62")).To(Equal(&agents.AlbumInfo{ Expect(agent.GetAlbumInfo(ctx, "Believe", "Cher", "03c91c40-49a6-44a7-90e7-a700edf97a62")).To(Equal(&agents.AlbumInfo{
Name: "Believe", Name: "Believe",
MBID: "03c91c40-49a6-44a7-90e7-a700edf97a62", MBID: "03c91c40-49a6-44a7-90e7-a700edf97a62",
@ -603,7 +603,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns empty images if no images are available", func() { It("returns empty images if no images are available", func() {
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty_urls.json") f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty_urls.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
Expect(agent.GetAlbumInfo(ctx, "The Definitive Less Damage And More Joy", "The Jesus and Mary Chain", "")).To(Equal(&agents.AlbumInfo{ Expect(agent.GetAlbumInfo(ctx, "The Definitive Less Damage And More Joy", "The Jesus and Mary Chain", "")).To(Equal(&agents.AlbumInfo{
Name: "The Definitive Less Damage And More Joy", Name: "The Definitive Less Damage And More Joy",
URL: "https://www.last.fm/music/The+Jesus+and+Mary+Chain/The+Definitive+Less+Damage+And+More+Joy", URL: "https://www.last.fm/music/The+Jesus+and+Mary+Chain/The+Definitive+Less+Damage+And+More+Joy",
@ -621,7 +621,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns an error if Last.fm call returns an error", func() { It("returns an error if Last.fm call returns an error", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
_, err := agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234") _, err := agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234")
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -629,7 +629,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns an error when Last.fm returns an error 6 (album not found)", func() { It("returns an error when Last.fm returns an error 6 (album not found)", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: http.StatusOK}
_, err := agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234") _, err := agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234")
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
// A definitive not-found must satisfy the sentinel, or the artwork worker retries it. // A definitive not-found must satisfy the sentinel, or the artwork worker retries it.
@ -655,10 +655,10 @@ var _ = Describe("lastfmAgent", func() {
It("returns the artist image from the page", func() { It("returns the artist image from the page", func() {
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
apiClient.Res = http.Response{Body: fApi, StatusCode: 200} apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.html") fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.html")
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200} httpClient.Res = http.Response{Body: fScraper, StatusCode: http.StatusOK}
images, err := agent.GetArtistImages(ctx, "123", "U2", "") images, err := agent.GetArtistImages(ctx, "123", "U2", "")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -667,7 +667,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("maps a Last.fm error 6 (artist not found) to the shared not-found sentinel", func() { It("maps a Last.fm error 6 (artist not found) to the shared not-found sentinel", func() {
apiClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: 200} apiClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: http.StatusOK}
_, err := agent.GetArtistImages(ctx, "123", "Nonexistent Artist", "") _, err := agent.GetArtistImages(ctx, "123", "Nonexistent Artist", "")
// Not a fault: runs of missing artists must not trip the worker's circuit breaker. // Not a fault: runs of missing artists must not trip the worker's circuit breaker.
Expect(errors.Is(err, agents.ErrNotFound)).To(BeTrue()) Expect(errors.Is(err, agents.ErrNotFound)).To(BeTrue())
@ -675,10 +675,10 @@ var _ = Describe("lastfmAgent", func() {
It("returns empty list if image is the ignored default image", func() { It("returns empty list if image is the ignored default image", func() {
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
apiClient.Res = http.Response{Body: fApi, StatusCode: 200} apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.ignored.html") fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.ignored.html")
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200} httpClient.Res = http.Response{Body: fScraper, StatusCode: http.StatusOK}
images, err := agent.GetArtistImages(ctx, "123", "U2", "") images, err := agent.GetArtistImages(ctx, "123", "U2", "")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -687,10 +687,10 @@ var _ = Describe("lastfmAgent", func() {
It("errors when the page has no meta tags", func() { It("errors when the page has no meta tags", func() {
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
apiClient.Res = http.Response{Body: fApi, StatusCode: 200} apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.no_meta.html") fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.no_meta.html")
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200} httpClient.Res = http.Response{Body: fScraper, StatusCode: http.StatusOK}
_, err := agent.GetArtistImages(ctx, "123", "U2", "") _, err := agent.GetArtistImages(ctx, "123", "U2", "")
Expect(err).To(MatchError(errNoArtistPage)) Expect(err).To(MatchError(errNoArtistPage))
@ -698,10 +698,10 @@ var _ = Describe("lastfmAgent", func() {
It("errors when Last.fm serves a bot challenge page", func() { It("errors when Last.fm serves a bot challenge page", func() {
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
apiClient.Res = http.Response{Body: fApi, StatusCode: 200} apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.challenge.html") fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.challenge.html")
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200} httpClient.Res = http.Response{Body: fScraper, StatusCode: http.StatusOK}
images, err := agent.GetArtistImages(ctx, "123", "U2", "") images, err := agent.GetArtistImages(ctx, "123", "U2", "")
Expect(err).To(MatchError(errNoArtistPage)) Expect(err).To(MatchError(errNoArtistPage))
@ -711,10 +711,10 @@ var _ = Describe("lastfmAgent", func() {
It("does not park the agent: the failure is not a retry-later", func() { It("does not park the agent: the failure is not a retry-later", func() {
// A RetryLaterError would cool down the agent's API-backed methods too. // A RetryLaterError would cool down the agent's API-backed methods too.
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
apiClient.Res = http.Response{Body: fApi, StatusCode: 200} apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.challenge.html") fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.challenge.html")
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200} httpClient.Res = http.Response{Body: fScraper, StatusCode: http.StatusOK}
_, err := agent.GetArtistImages(ctx, "123", "U2", "") _, err := agent.GetArtistImages(ctx, "123", "U2", "")
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeFalse()) Expect(errors.Is(err, agents.ErrRetryLater)).To(BeFalse())
@ -729,7 +729,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns error if scraper call fails", func() { It("returns error if scraper call fails", func() {
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
apiClient.Res = http.Response{Body: fApi, StatusCode: 200} apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
httpClient.Err = errors.New("scraper error") httpClient.Err = errors.New("scraper error")
_, err := agent.GetArtistImages(ctx, "123", "U2", "") _, err := agent.GetArtistImages(ctx, "123", "U2", "")
@ -762,7 +762,7 @@ func (c *langAwareHttpClient) Do(req *http.Request) (*http.Response, error) {
} }
// Return default empty response if no specific response is configured // Return default empty response if no specific response is configured
return &http.Response{ return &http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{}`)), Body: io.NopCloser(bytes.NewBufferString(`{}`)),
}, nil }, nil
} }

View file

@ -57,7 +57,7 @@ var _ = Describe("auth_router", func() {
stubGetSessionOK := func(sessionKey string) { stubGetSessionOK := func(sessionKey string) {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"session":{"name":"Navidrome","key":"` + sessionKey + `","subscriber":0}}`)), Body: io.NopCloser(bytes.NewBufferString(`{"session":{"name":"Navidrome","key":"` + sessionKey + `","subscriber":0}}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
} }
@ -74,7 +74,7 @@ var _ = Describe("auth_router", func() {
var body map[string]any var body map[string]any
Expect(json.Unmarshal(rec.Body.Bytes(), &body)).To(Succeed()) Expect(json.Unmarshal(rec.Body.Bytes(), &body)).To(Succeed())
Expect(body["apiKey"]).To(Equal("API_KEY")) Expect(body["apiKey"]).To(Equal("API_KEY"))
Expect(body["status"]).To(Equal(false)) Expect(body["status"]).To(BeFalse())
token, ok := body["linkToken"].(string) token, ok := body["linkToken"].(string)
Expect(ok).To(BeTrue()) Expect(ok).To(BeTrue())
Expect(token).ToNot(BeEmpty()) Expect(token).ToNot(BeEmpty())

View file

@ -236,7 +236,7 @@ func (c *client) makeRequest(ctx context.Context, method string, params url.Valu
var response Response var response Response
jsonErr := decoder.Decode(&response) jsonErr := decoder.Decode(&response)
if resp.StatusCode != 200 && jsonErr != nil { if resp.StatusCode != http.StatusOK && jsonErr != nil {
return nil, fmt.Errorf("last.fm http status: (%d)", resp.StatusCode) return nil, fmt.Errorf("last.fm http status: (%d)", resp.StatusCode)
} }
if jsonErr != nil { if jsonErr != nil {

View file

@ -30,17 +30,17 @@ var _ = Describe("client", func() {
Describe("albumGetInfo", func() { Describe("albumGetInfo", func() {
It("returns an album on successful response", func() { It("returns an album on successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
album, err := client.albumGetInfo(ctx, "Believe", "U2", "mbid-1234", "pt") album, err := client.albumGetInfo(ctx, "Believe", "U2", "mbid-1234", "pt")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(album.Name).To(Equal("Believe")) Expect(album.Name).To(Equal("Believe"))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?album=Believe&api_key=API_KEY&artist=U2&format=json&lang=pt&mbid=mbid-1234&method=album.getInfo")) Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?album=Believe&api_key=API_KEY&artist=U2&format=json&lang=pt&mbid=mbid-1234&method=album.getInfo"))
}) })
It("does not double-encode plus signs", func() { It("does not double-encode plus signs", func() {
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := client.albumGetInfo(ctx, "Lungs", "Florence + the Machine", "", "en") _, err := client.albumGetInfo(ctx, "Lungs", "Florence + the Machine", "", "en")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -51,17 +51,17 @@ var _ = Describe("client", func() {
Describe("artistGetInfo", func() { Describe("artistGetInfo", func() {
It("returns an artist for a successful response", func() { It("returns an artist for a successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
artist, err := client.artistGetInfo(ctx, "U2", "pt") artist, err := client.artistGetInfo(ctx, "U2", "pt")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(artist.Name).To(Equal("U2")) Expect(artist.Name).To(Equal("U2"))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&lang=pt&method=artist.getInfo")) Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&lang=pt&method=artist.getInfo"))
}) })
It("double-encodes plus signs in the artist name", func() { It("double-encodes plus signs in the artist name", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := client.artistGetInfo(ctx, "Florence + the Machine", "en") _, err := client.artistGetInfo(ctx, "Florence + the Machine", "en")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -71,7 +71,7 @@ var _ = Describe("client", func() {
It("fails if Last.fm returns an http status != 200", func() { It("fails if Last.fm returns an http status != 200", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Internal Server Error`)), Body: io.NopCloser(bytes.NewBufferString(`Internal Server Error`)),
StatusCode: 500, StatusCode: http.StatusInternalServerError,
} }
_, err := client.artistGetInfo(ctx, "U2", "pt") _, err := client.artistGetInfo(ctx, "U2", "pt")
@ -81,7 +81,7 @@ var _ = Describe("client", func() {
It("fails if Last.fm returns an http status != 200", func() { It("fails if Last.fm returns an http status != 200", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":3,"message":"Invalid Method - No method with that name in this package"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":3,"message":"Invalid Method - No method with that name in this package"}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
_, err := client.artistGetInfo(ctx, "U2", "pt") _, err := client.artistGetInfo(ctx, "U2", "pt")
@ -91,7 +91,7 @@ var _ = Describe("client", func() {
It("fails if Last.fm returns an error", func() { It("fails if Last.fm returns an error", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":6,"message":"The artist you supplied could not be found"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":6,"message":"The artist you supplied could not be found"}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
_, err := client.artistGetInfo(ctx, "U2", "pt") _, err := client.artistGetInfo(ctx, "U2", "pt")
@ -108,7 +108,7 @@ var _ = Describe("client", func() {
It("fails if returned body is not a valid JSON", func() { It("fails if returned body is not a valid JSON", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`<xml>NOT_VALID_JSON</xml>`)), Body: io.NopCloser(bytes.NewBufferString(`<xml>NOT_VALID_JSON</xml>`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
_, err := client.artistGetInfo(ctx, "U2", "pt") _, err := client.artistGetInfo(ctx, "U2", "pt")
@ -120,17 +120,17 @@ var _ = Describe("client", func() {
Describe("artistGetSimilar", func() { Describe("artistGetSimilar", func() {
It("returns an artist for a successful response", func() { It("returns an artist for a successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
similar, err := client.artistGetSimilar(ctx, "U2", 2) similar, err := client.artistGetSimilar(ctx, "U2", 2)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(similar.Artists)).To(Equal(2)) Expect(similar.Artists).To(HaveLen(2))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&limit=2&method=artist.getSimilar")) Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&limit=2&method=artist.getSimilar"))
}) })
It("double-encodes plus signs in the artist name", func() { It("double-encodes plus signs in the artist name", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := client.artistGetSimilar(ctx, "+44", 2) _, err := client.artistGetSimilar(ctx, "+44", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -141,17 +141,17 @@ var _ = Describe("client", func() {
Describe("artistGetTopTracks", func() { Describe("artistGetTopTracks", func() {
It("returns top tracks for a successful response", func() { It("returns top tracks for a successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json") f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
top, err := client.artistGetTopTracks(ctx, "U2", 2) top, err := client.artistGetTopTracks(ctx, "U2", 2)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(top.Track)).To(Equal(2)) Expect(top.Track).To(HaveLen(2))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&limit=2&method=artist.getTopTracks")) Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&limit=2&method=artist.getTopTracks"))
}) })
It("double-encodes plus signs in the artist name", func() { It("double-encodes plus signs in the artist name", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json") f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := client.artistGetTopTracks(ctx, "C+C Music Factory", 2) _, err := client.artistGetTopTracks(ctx, "C+C Music Factory", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -162,11 +162,11 @@ var _ = Describe("client", func() {
Describe("trackGetSimilar", func() { Describe("trackGetSimilar", func() {
It("returns similar tracks for a successful response", func() { It("returns similar tracks for a successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json") f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
similar, err := client.trackGetSimilar(ctx, "Just Can't Get Enough", "Depeche Mode", 5) similar, err := client.trackGetSimilar(ctx, "Just Can't Get Enough", "Depeche Mode", 5)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(similar.Track)).To(Equal(5)) Expect(similar.Track).To(HaveLen(5))
Expect(similar.Track[0].Name).To(Equal("Dreaming of Me")) Expect(similar.Track[0].Name).To(Equal("Dreaming of Me"))
Expect(similar.Track[0].Artist.Name).To(Equal("Depeche Mode")) Expect(similar.Track[0].Artist.Name).To(Equal("Depeche Mode"))
Expect(similar.Track[0].Match).To(Equal(1.0)) Expect(similar.Track[0].Match).To(Equal(1.0))
@ -175,7 +175,7 @@ var _ = Describe("client", func() {
It("double-encodes plus signs in the track and artist names", func() { It("double-encodes plus signs in the track and artist names", func() {
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json") f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := client.trackGetSimilar(ctx, "1+1", "Queen + Paul Rodgers", 5) _, err := client.trackGetSimilar(ctx, "1+1", "Queen + Paul Rodgers", 5)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -186,10 +186,10 @@ var _ = Describe("client", func() {
It("returns empty list when no similar tracks found", func() { It("returns empty list when no similar tracks found", func() {
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json") f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
similar, err := client.trackGetSimilar(ctx, "UnknownTrack", "UnknownArtist", 3) similar, err := client.trackGetSimilar(ctx, "UnknownTrack", "UnknownArtist", 3)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(similar.Track).To(BeEmpty()) Expect(similar.Track).To(BeEmpty())
}) })
}) })
@ -198,7 +198,7 @@ var _ = Describe("client", func() {
It("returns a token when the request is successful", func() { It("returns a token when the request is successful", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"token":"TOKEN"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"token":"TOKEN"}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
Expect(client.GetToken(ctx)).To(Equal("TOKEN")) Expect(client.GetToken(ctx)).To(Equal("TOKEN"))
@ -214,7 +214,7 @@ var _ = Describe("client", func() {
It("returns a session key when the request is successful", func() { It("returns a session key when the request is successful", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"session":{"name":"Navidrome","key":"SESSION_KEY","subscriber":0}}`)), Body: io.NopCloser(bytes.NewBufferString(`{"session":{"name":"Navidrome","key":"SESSION_KEY","subscriber":0}}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
Expect(client.getSession(ctx, "TOKEN")).To(Equal("SESSION_KEY")) Expect(client.getSession(ctx, "TOKEN")).To(Equal("SESSION_KEY"))
@ -231,7 +231,7 @@ var _ = Describe("client", func() {
It("sends parameters in request body for POST", func() { It("sends parameters in request body for POST", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"scrobbles":{"scrobble":{"ignoredMessage":{"code":"0"}},"@attr":{"accepted":1}}}`)), Body: io.NopCloser(bytes.NewBufferString(`{"scrobbles":{"scrobble":{"ignoredMessage":{"code":"0"}},"@attr":{"accepted":1}}}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
info := ScrobbleInfo{ info := ScrobbleInfo{
@ -243,7 +243,7 @@ var _ = Describe("client", func() {
albumArtist: "U2", albumArtist: "U2",
} }
err := client.scrobble(ctx, "SESSION_KEY", info) err := client.scrobble(ctx, "SESSION_KEY", info)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
req := httpClient.SavedRequest req := httpClient.SavedRequest
Expect(req.Method).To(Equal(http.MethodPost)) Expect(req.Method).To(Equal(http.MethodPost))
@ -265,7 +265,7 @@ var _ = Describe("client", func() {
It("sends parameters in request body for POST", func() { It("sends parameters in request body for POST", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"nowplaying":{"ignoredMessage":{"code":"0"}}}`)), Body: io.NopCloser(bytes.NewBufferString(`{"nowplaying":{"ignoredMessage":{"code":"0"}}}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
info := ScrobbleInfo{ info := ScrobbleInfo{
@ -277,7 +277,7 @@ var _ = Describe("client", func() {
albumArtist: "U2", albumArtist: "U2",
} }
err := client.updateNowPlaying(ctx, "SESSION_KEY", info) err := client.updateNowPlaying(ctx, "SESSION_KEY", info)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
req := httpClient.SavedRequest req := httpClient.SavedRequest
Expect(req.Method).To(Equal(http.MethodPost)) Expect(req.Method).To(Equal(http.MethodPost))

View file

@ -14,7 +14,7 @@ var _ = Describe("LastFM responses", func() {
var resp Response var resp Response
body, _ := os.ReadFile("tests/fixtures/lastfm.artist.getinfo.json") body, _ := os.ReadFile("tests/fixtures/lastfm.artist.getinfo.json")
err := json.Unmarshal(body, &resp) err := json.Unmarshal(body, &resp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(resp.Artist.Name).To(Equal("U2")) Expect(resp.Artist.Name).To(Equal("U2"))
Expect(resp.Artist.MBID).To(Equal("a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432")) Expect(resp.Artist.MBID).To(Equal("a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432"))
@ -28,7 +28,7 @@ var _ = Describe("LastFM responses", func() {
var resp Response var resp Response
body, _ := os.ReadFile("tests/fixtures/lastfm.artist.getsimilar.json") body, _ := os.ReadFile("tests/fixtures/lastfm.artist.getsimilar.json")
err := json.Unmarshal(body, &resp) err := json.Unmarshal(body, &resp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(resp.SimilarArtists.Artists).To(HaveLen(2)) Expect(resp.SimilarArtists.Artists).To(HaveLen(2))
Expect(resp.SimilarArtists.Artists[0].Name).To(Equal("Passengers")) Expect(resp.SimilarArtists.Artists[0].Name).To(Equal("Passengers"))
@ -41,7 +41,7 @@ var _ = Describe("LastFM responses", func() {
var resp Response var resp Response
body, _ := os.ReadFile("tests/fixtures/lastfm.artist.gettoptracks.json") body, _ := os.ReadFile("tests/fixtures/lastfm.artist.gettoptracks.json")
err := json.Unmarshal(body, &resp) err := json.Unmarshal(body, &resp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(resp.TopTracks.Track).To(HaveLen(2)) Expect(resp.TopTracks.Track).To(HaveLen(2))
Expect(resp.TopTracks.Track[0].Name).To(Equal("Beautiful Day")) Expect(resp.TopTracks.Track[0].Name).To(Equal("Beautiful Day"))
@ -56,7 +56,7 @@ var _ = Describe("LastFM responses", func() {
var error Response var error Response
body := []byte(`{"error":3,"message":"Invalid Method - No method with that name in this package"}`) body := []byte(`{"error":3,"message":"Invalid Method - No method with that name in this package"}`)
err := json.Unmarshal(body, &error) err := json.Unmarshal(body, &error)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(error.Error).To(Equal(3)) Expect(error.Error).To(Equal(3))
Expect(error.Message).To(Equal("Invalid Method - No method with that name in this package")) Expect(error.Message).To(Equal("Invalid Method - No method with that name in this package"))

View file

@ -8,6 +8,7 @@ import (
"io" "io"
"net/http" "net/http"
"os" "os"
"reflect"
"time" "time"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
@ -47,8 +48,8 @@ var _ = Describe("listenBrainzAgent", func() {
Duration: 142.2, Duration: 142.2,
Participants: map[model.Role]model.ParticipantList{ Participants: map[model.Role]model.ParticipantList{
model.RoleArtist: []model.Participant{ model.RoleArtist: []model.Participant{
{Artist: model.Artist{ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"}}, {ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"},
{Artist: model.Artist{ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"}}, {ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"},
}, },
}, },
} }
@ -81,7 +82,7 @@ var _ = Describe("listenBrainzAgent", func() {
Describe("NowPlaying", func() { Describe("NowPlaying", func() {
It("updates NowPlaying successfully", func() { It("updates NowPlaying successfully", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: http.StatusOK}
err := agent.NowPlaying(ctx, "user-1", track, 0) err := agent.NowPlaying(ctx, "user-1", track, 0)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -101,14 +102,14 @@ var _ = Describe("listenBrainzAgent", func() {
}) })
It("sends a Scrobble successfully", func() { It("sends a Scrobble successfully", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: http.StatusOK}
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
}) })
It("sets the Timestamp properly", func() { It("sets the Timestamp properly", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: http.StatusOK}
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -129,7 +130,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns ErrRetryLater on error 503", func() { It("returns ErrRetryLater on error 503", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 503, "error": "Cannot submit listens to queue, please try again later."}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 503, "error": "Cannot submit listens to queue, please try again later."}`)),
StatusCode: 503, StatusCode: http.StatusServiceUnavailable,
} }
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
@ -139,7 +140,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns ErrRetryLater on error 500", func() { It("returns ErrRetryLater on error 500", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 500, "error": "Something went wrong. Please try again."}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 500, "error": "Something went wrong. Please try again."}`)),
StatusCode: 500, StatusCode: http.StatusInternalServerError,
} }
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
@ -149,7 +150,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns ErrRetryLater on http errors", func() { It("returns ErrRetryLater on http errors", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad Gateway`)), Body: io.NopCloser(bytes.NewBufferString(`Bad Gateway`)),
StatusCode: 500, StatusCode: http.StatusInternalServerError,
} }
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
@ -159,7 +160,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns ErrUnrecoverable on other errors", func() { It("returns ErrUnrecoverable on other errors", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400, "error": "BadRequest: Invalid JSON document submitted."}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 400, "error": "BadRequest: Invalid JSON document submitted."}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
@ -168,7 +169,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("keeps a 429 scrobble for retry and carries the delay", func() { It("keeps a 429 scrobble for retry and carries the delay", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
StatusCode: 429, StatusCode: http.StatusTooManyRequests,
Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}}, Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}},
Body: io.NopCloser(bytes.NewBufferString(`{"code":429,"error":"rate limited"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code":429,"error":"rate limited"}`)),
} }
@ -192,7 +193,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns artist url when MBID present", func() { It("returns artist url when MBID present", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json") f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
Expect(agent.GetArtistURL(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")).To(Equal("http://projectmili.com/")) Expect(agent.GetArtistURL(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")).To(Equal("http://projectmili.com/"))
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
Expect(httpClient.SavedRequest.URL.Query().Get("artist_mbids")).To(Equal("d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")) Expect(httpClient.SavedRequest.URL.Query().Get("artist_mbids")).To(Equal("d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56"))
@ -200,7 +201,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns error when url not present", func() { It("returns error when url not present", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json") f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973") _, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973")
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -218,7 +219,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns error when ListenBrainz returns an error", func() { It("returns error when ListenBrainz returns an error", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
_, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973") _, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973")
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
@ -248,7 +249,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns an error on listenbrainz error", func() { It("returns an error on listenbrainz error", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
_, err := agent.GetArtistTopSongs(ctx, "", "", "1", 1) _, err := agent.GetArtistTopSongs(ctx, "", "", "1", 1)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
@ -258,7 +259,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns all tracks when asked", func() { It("returns all tracks when asked", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json") f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 2) data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]agents.Song{ Expect(data).To(Equal([]agents.Song{
@ -285,7 +286,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns only one track when prompted", func() { It("returns only one track when prompted", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json") f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1) data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]agents.Song{ Expect(data).To(Equal([]agents.Song{
@ -311,7 +312,7 @@ var _ = Describe("listenBrainzAgent", func() {
"release_mbid": "rel-1", "release_mbid": "rel-1",
"length": 200000 "length": 200000
}]` }]`
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: http.StatusOK}
data, err := agent.GetArtistTopSongs(ctx, "", "", "mbid-drake", 1) data, err := agent.GetArtistTopSongs(ctx, "", "", "mbid-drake", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(HaveLen(1)) Expect(data).To(HaveLen(1))
@ -323,7 +324,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("leaves Artists nil when the top song carries no name or MBIDs", func() { It("leaves Artists nil when the top song carries no name or MBIDs", func() {
body := `[{"recording_name": "Anon", "recording_mbid": "rec-1", "artist_name": "", "artist_mbids": []}]` body := `[{"recording_name": "Anon", "recording_mbid": "rec-1", "artist_name": "", "artist_mbids": []}]`
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: http.StatusOK}
data, err := agent.GetArtistTopSongs(ctx, "", "", "x", 1) data, err := agent.GetArtistTopSongs(ctx, "", "", "x", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(HaveLen(1)) Expect(data).To(HaveLen(1))
@ -355,7 +356,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns an error on listenbrainz error", func() { It("returns an error on listenbrainz error", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)), Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
_, err := agent.GetSimilarArtists(ctx, "", "", "1", 1) _, err := agent.GetSimilarArtists(ctx, "", "", "1", 1)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
@ -365,7 +366,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns all data on call", func() { It("returns all data on call", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 2) resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -379,7 +380,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns subset of data on call", func() { It("returns subset of data on call", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 1) resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -415,7 +416,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns an error on listenbrainz error", func() { It("returns an error on listenbrainz error", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)), Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
_, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", "1", 1) _, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", "1", 1)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
@ -425,7 +426,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns all data on call", func() { It("returns all data on call", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 2) resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -457,7 +458,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns subset of data on call", func() { It("returns subset of data on call", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 1) resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -500,8 +501,9 @@ var _ = Describe("register", func() {
}) })
It("builds no scrobbler and no agent", func() { It("builds no scrobbler and no agent", func() {
Expect(newScrobbler(ds) == nil).To(BeTrue()) // TypeOf is nil only for an untyped nil; a typed nil would pass callers' != nil checks
Expect(agents.Map[listenBrainzAgentName](ds) == nil).To(BeTrue()) Expect(reflect.TypeOf(newScrobbler(ds))).To(BeNil())
Expect(reflect.TypeOf(agents.Map[listenBrainzAgentName](ds))).To(BeNil())
}) })
}) })

View file

@ -34,28 +34,28 @@ var _ = Describe("ListenBrainz Auth Router", func() {
Describe("getLinkStatus", func() { Describe("getLinkStatus", func() {
It("returns false when there is no stored session key", func() { It("returns false when there is no stored session key", func() {
req = httptest.NewRequest("GET", "/listenbrainz/link", nil) req = httptest.NewRequest(http.MethodGet, "/listenbrainz/link", nil)
r.getLinkStatus(resp, req) r.getLinkStatus(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK)) Expect(resp.Code).To(Equal(http.StatusOK))
var parsed map[string]any var parsed map[string]any
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil()) Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(Succeed())
Expect(parsed["status"]).To(Equal(false)) Expect(parsed["status"]).To(BeFalse())
}) })
It("returns true when there is a stored session key", func() { It("returns true when there is a stored session key", func() {
sk.KeyValue = "sk-1" sk.KeyValue = "sk-1"
req = httptest.NewRequest("GET", "/listenbrainz/link", nil) req = httptest.NewRequest(http.MethodGet, "/listenbrainz/link", nil)
r.getLinkStatus(resp, req) r.getLinkStatus(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK)) Expect(resp.Code).To(Equal(http.StatusOK))
var parsed map[string]any var parsed map[string]any
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil()) Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(Succeed())
Expect(parsed["status"]).To(Equal(true)) Expect(parsed["status"]).To(BeTrue())
}) })
}) })
Describe("link", func() { Describe("link", func() {
It("returns bad request when no token is sent", func() { It("returns bad request when no token is sent", func() {
req = httptest.NewRequest("PUT", "/listenbrainz/link", strings.NewReader(`{}`)) req = httptest.NewRequest(http.MethodPut, "/listenbrainz/link", strings.NewReader(`{}`))
r.link(resp, req) r.link(resp, req)
Expect(resp.Code).To(Equal(http.StatusBadRequest)) Expect(resp.Code).To(Equal(http.StatusBadRequest))
}) })
@ -63,10 +63,10 @@ var _ = Describe("ListenBrainz Auth Router", func() {
It("returns bad request when the token is invalid", func() { It("returns bad request when the token is invalid", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token invalid.", "valid": false}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token invalid.", "valid": false}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
req = httptest.NewRequest("PUT", "/listenbrainz/link", strings.NewReader(`{"token": "invalid-tok-1"}`)) req = httptest.NewRequest(http.MethodPut, "/listenbrainz/link", strings.NewReader(`{"token": "invalid-tok-1"}`))
r.link(resp, req) r.link(resp, req)
Expect(resp.Code).To(Equal(http.StatusBadRequest)) Expect(resp.Code).To(Equal(http.StatusBadRequest))
}) })
@ -74,25 +74,25 @@ var _ = Describe("ListenBrainz Auth Router", func() {
It("returns true and the username when the token is valid", func() { It("returns true and the username when the token is valid", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token valid.", "user_name": "ListenBrainzUser", "valid": true}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token valid.", "user_name": "ListenBrainzUser", "valid": true}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
req = httptest.NewRequest("PUT", "/listenbrainz/link", strings.NewReader(`{"token": "tok-1"}`)) req = httptest.NewRequest(http.MethodPut, "/listenbrainz/link", strings.NewReader(`{"token": "tok-1"}`))
r.link(resp, req) r.link(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK)) Expect(resp.Code).To(Equal(http.StatusOK))
var parsed map[string]any var parsed map[string]any
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil()) Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(Succeed())
Expect(parsed["status"]).To(Equal(true)) Expect(parsed["status"]).To(BeTrue())
Expect(parsed["user"]).To(Equal("ListenBrainzUser")) Expect(parsed["user"]).To(Equal("ListenBrainzUser"))
}) })
It("saves the session key when the token is valid", func() { It("saves the session key when the token is valid", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token valid.", "user_name": "ListenBrainzUser", "valid": true}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token valid.", "user_name": "ListenBrainzUser", "valid": true}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
req = httptest.NewRequest("PUT", "/listenbrainz/link", strings.NewReader(`{"token": "tok-1"}`)) req = httptest.NewRequest(http.MethodPut, "/listenbrainz/link", strings.NewReader(`{"token": "tok-1"}`))
r.link(resp, req) r.link(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK)) Expect(resp.Code).To(Equal(http.StatusOK))
Expect(sk.KeyValue).To(Equal("tok-1")) Expect(sk.KeyValue).To(Equal("tok-1"))
@ -102,7 +102,7 @@ var _ = Describe("ListenBrainz Auth Router", func() {
Describe("unlink", func() { Describe("unlink", func() {
It("removes the session key when unlinking", func() { It("removes the session key when unlinking", func() {
sk.KeyValue = "tok-1" sk.KeyValue = "tok-1"
req = httptest.NewRequest("DELETE", "/listenbrainz/link", nil) req = httptest.NewRequest(http.MethodDelete, "/listenbrainz/link", nil)
r.unlink(resp, req) r.unlink(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK)) Expect(resp.Code).To(Equal(http.StatusOK))
Expect(sk.KeyValue).To(Equal("")) Expect(sk.KeyValue).To(Equal(""))

View file

@ -162,7 +162,10 @@ func (c *client) path(endpoint string) (string, error) {
} }
func (c *client) makeAuthenticatedRequest(ctx context.Context, method string, endpoint string, r *listenBrainzRequest) (*listenBrainzResponse, error) { func (c *client) makeAuthenticatedRequest(ctx context.Context, method string, endpoint string, r *listenBrainzRequest) (*listenBrainzResponse, error) {
b, _ := json.Marshal(r.Body) b, err := json.Marshal(r.Body)
if err != nil {
return nil, fmt.Errorf("encoding request body: %w", err)
}
uri, err := c.path(endpoint) uri, err := c.path(endpoint)
if err != nil { if err != nil {
return nil, err return nil, err
@ -171,7 +174,7 @@ func (c *client) makeAuthenticatedRequest(ctx context.Context, method string, en
req.Header.Add("Content-Type", "application/json; charset=UTF-8") req.Header.Add("Content-Type", "application/json; charset=UTF-8")
if r.ApiKey != "" { if r.ApiKey != "" {
req.Header.Add("Authorization", fmt.Sprintf("Token %s", r.ApiKey)) req.Header.Add("Authorization", "Token "+r.ApiKey)
} }
log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz %s request", req.Method), "url", req.URL) log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz %s request", req.Method), "url", req.URL)
@ -188,7 +191,7 @@ func (c *client) makeAuthenticatedRequest(ctx context.Context, method string, en
var response listenBrainzResponse var response listenBrainzResponse
jsonErr := decoder.Decode(&response) jsonErr := decoder.Decode(&response)
if resp.StatusCode != 200 && jsonErr != nil { if resp.StatusCode != http.StatusOK && jsonErr != nil {
return nil, fmt.Errorf("ListenBrainz: HTTP Error, Status: (%d)", resp.StatusCode) return nil, fmt.Errorf("ListenBrainz: HTTP Error, Status: (%d)", resp.StatusCode)
} }
if jsonErr != nil { if jsonErr != nil {
@ -223,7 +226,7 @@ func (c *client) makeGenericRequest(ctx context.Context, method string, endpoint
} }
// On a 200 code, there is no code. Decode using using error message if it exists // On a 200 code, there is no code. Decode using using error message if it exists
if resp.StatusCode != 200 { if resp.StatusCode != http.StatusOK {
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode == http.StatusTooManyRequests { if resp.StatusCode == http.StatusTooManyRequests {
return nil, retryLaterErr(resp.Header) return nil, retryLaterErr(resp.Header)

View file

@ -48,7 +48,7 @@ var _ = Describe("client", func() {
BeforeEach(func() { BeforeEach(func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token valid.", "user_name": "ListenBrainzUser", "valid": true}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token valid.", "user_name": "ListenBrainzUser", "valid": true}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
}) })
@ -64,7 +64,7 @@ var _ = Describe("client", func() {
It("parses and returns the response", func() { It("parses and returns the response", func() {
res, err := client.validateToken(ctx, "LB-TOKEN") res, err := client.validateToken(ctx, "LB-TOKEN")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(res.Valid).To(Equal(true)) Expect(res.Valid).To(BeTrue())
Expect(res.UserName).To(Equal("ListenBrainzUser")) Expect(res.UserName).To(Equal("ListenBrainzUser"))
}) })
}) })
@ -74,7 +74,7 @@ var _ = Describe("client", func() {
BeforeEach(func() { BeforeEach(func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
li = listenInfo{ li = listenInfo{
TrackMetadata: trackMetadata{ TrackMetadata: trackMetadata{
@ -131,7 +131,7 @@ var _ = Describe("client", func() {
It("handles a malformed request with status code", func() { It("handles a malformed request with status code", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
_, err := client.getArtistUrl(ctx, "1") _, err := client.getArtistUrl(ctx, "1")
Expect(err.Error()).To(Equal("ListenBrainz error(400): artist mbid 1 is not valid.")) Expect(err.Error()).To(Equal("ListenBrainz error(400): artist mbid 1 is not valid."))
@ -143,7 +143,7 @@ var _ = Describe("client", func() {
It("handles a malformed request without meaningful body", func() { It("handles a malformed request without meaningful body", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(``)), Body: io.NopCloser(bytes.NewBufferString(``)),
StatusCode: 501, StatusCode: http.StatusNotImplemented,
} }
_, err := client.getArtistUrl(ctx, "1") _, err := client.getArtistUrl(ctx, "1")
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (501)")) Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (501)"))
@ -154,7 +154,7 @@ var _ = Describe("client", func() {
It("It returns not found when the artist has no official homepage", func() { It("It returns not found when the artist has no official homepage", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json") f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := client.getArtistUrl(ctx, "7c2cc610-f998-43ef-a08f-dae3344b8973") _, err := client.getArtistUrl(ctx, "7c2cc610-f998-43ef-a08f-dae3344b8973")
Expect(err.Error()).To(Equal("listenbrainz: not found")) Expect(err.Error()).To(Equal("listenbrainz: not found"))
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
@ -164,7 +164,7 @@ var _ = Describe("client", func() {
It("It returns data when the artist has a homepage", func() { It("It returns data when the artist has a homepage", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json") f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
url, err := client.getArtistUrl(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56") url, err := client.getArtistUrl(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(url).To(Equal("http://projectmili.com/")) Expect(url).To(Equal("http://projectmili.com/"))
@ -180,7 +180,7 @@ var _ = Describe("client", func() {
It("handles a malformed request with status code", func() { It("handles a malformed request with status code", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
_, err := client.getArtistTopSongs(ctx, "1", 50) _, err := client.getArtistTopSongs(ctx, "1", 50)
Expect(err.Error()).To(Equal("ListenBrainz error(400): artist_mbid: '1' is not a valid uuid")) Expect(err.Error()).To(Equal("ListenBrainz error(400): artist_mbid: '1' is not a valid uuid"))
@ -192,7 +192,7 @@ var _ = Describe("client", func() {
It("handles a malformed request without standard body", func() { It("handles a malformed request without standard body", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(``)), Body: io.NopCloser(bytes.NewBufferString(``)),
StatusCode: 500, StatusCode: http.StatusInternalServerError,
} }
_, err := client.getArtistTopSongs(ctx, "1", 1) _, err := client.getArtistTopSongs(ctx, "1", 1)
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (500)")) Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (500)"))
@ -203,7 +203,7 @@ var _ = Describe("client", func() {
It("It returns all tracks when given the opportunity", func() { It("It returns all tracks when given the opportunity", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json") f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 5) data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 5)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]trackInfo{ Expect(data).To(Equal([]trackInfo{
@ -233,7 +233,7 @@ var _ = Describe("client", func() {
It("It returns a subset of tracks when allowed", func() { It("It returns a subset of tracks when allowed", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json") f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1) data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]trackInfo{ Expect(data).To(Equal([]trackInfo{
@ -269,7 +269,7 @@ var _ = Describe("client", func() {
It("handles a malformed request with status code", func() { It("handles a malformed request with status code", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)), Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
_, err := client.getSimilarArtists(ctx, "1", 2) _, err := client.getSimilarArtists(ctx, "1", 2)
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)")) Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)"))
@ -280,7 +280,7 @@ var _ = Describe("client", func() {
It("handles real data properly", func() { It("handles real data properly", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := client.getSimilarArtists(ctx, mbid, 2) resp, err := client.getSimilarArtists(ctx, mbid, 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
@ -294,7 +294,7 @@ var _ = Describe("client", func() {
It("truncates data when requested", func() { It("truncates data when requested", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := client.getSimilarArtists(ctx, "db92a151-1ac2-438b-bc43-b82e149ddd50", 1) resp, err := client.getSimilarArtists(ctx, "db92a151-1ac2-438b-bc43-b82e149ddd50", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
@ -310,7 +310,7 @@ var _ = Describe("client", func() {
conf.Update(func(c *conf.Options) { c.ListenBrainz.ArtistAlgorithm = algorithm }) conf.Update(func(c *conf.Options) { c.ListenBrainz.ArtistAlgorithm = algorithm })
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := client.getSimilarArtists(ctx, mbid, 2) resp, err := client.getSimilarArtists(ctx, mbid, 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
@ -339,7 +339,7 @@ var _ = Describe("client", func() {
It("handles a malformed request with status code", func() { It("handles a malformed request with status code", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)), Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
_, err := client.getSimilarRecordings(ctx, "1", 2) _, err := client.getSimilarRecordings(ctx, "1", 2)
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)")) Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)"))
@ -350,7 +350,7 @@ var _ = Describe("client", func() {
It("handles real data properly", func() { It("handles real data properly", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := client.getSimilarRecordings(ctx, mbid, 2) resp, err := client.getSimilarRecordings(ctx, mbid, 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
@ -378,7 +378,7 @@ var _ = Describe("client", func() {
It("truncates data when requested", func() { It("truncates data when requested", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := client.getSimilarRecordings(ctx, mbid, 1) resp, err := client.getSimilarRecordings(ctx, mbid, 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
@ -398,7 +398,7 @@ var _ = Describe("client", func() {
It("properly sorts by score and truncates duplicates", func() { It("properly sorts by score and truncates duplicates", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings-real-out-of-order.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings-real-out-of-order.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
// There are actually 5 items. The dedup should happen FIRST // There are actually 5 items. The dedup should happen FIRST
resp, err := client.getSimilarRecordings(ctx, mbid, 4) resp, err := client.getSimilarRecordings(ctx, mbid, 4)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -446,7 +446,7 @@ var _ = Describe("client", func() {
conf.Update(func(c *conf.Options) { c.ListenBrainz.TrackAlgorithm = algorithm }) conf.Update(func(c *conf.Options) { c.ListenBrainz.TrackAlgorithm = algorithm })
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := client.getSimilarRecordings(ctx, mbid, 1) resp, err := client.getSimilarRecordings(ctx, mbid, 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
@ -468,7 +468,7 @@ var _ = Describe("client", func() {
Describe("rate limiting", func() { Describe("rate limiting", func() {
It("returns RetryLaterError with the header delay on 429", func() { It("returns RetryLaterError with the header delay on 429", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
StatusCode: 429, StatusCode: http.StatusTooManyRequests,
Header: http.Header{"X-Ratelimit-Reset-In": []string{"3"}}, Header: http.Header{"X-Ratelimit-Reset-In": []string{"3"}},
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)), Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)),
} }
@ -481,7 +481,7 @@ var _ = Describe("client", func() {
It("returns RetryLaterError with zero delay when no header is present", func() { It("returns RetryLaterError with zero delay when no header is present", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
StatusCode: 429, StatusCode: http.StatusTooManyRequests,
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)), Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
} }
_, err := client.validateToken(ctx, "token") _, err := client.validateToken(ctx, "token")
@ -493,7 +493,7 @@ var _ = Describe("client", func() {
DescribeTable("caps absurd header values at one hour", DescribeTable("caps absurd header values at one hour",
func(header string) { func(header string) {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
StatusCode: 429, StatusCode: http.StatusTooManyRequests,
Header: http.Header{"X-Ratelimit-Reset-In": []string{header}}, Header: http.Header{"X-Ratelimit-Reset-In": []string{header}},
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)), Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
} }
@ -509,7 +509,7 @@ var _ = Describe("client", func() {
It("maps a body-level 429 sent with a non-429 status", func() { It("maps a body-level 429 sent with a non-429 status", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}}, Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}},
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)), Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)),
} }
@ -522,7 +522,7 @@ var _ = Describe("client", func() {
It("returns RetryLaterError on a 429 from makeGenericRequest", func() { It("returns RetryLaterError on a 429 from makeGenericRequest", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
StatusCode: 429, StatusCode: http.StatusTooManyRequests,
Header: http.Header{"X-Ratelimit-Reset-In": []string{"5"}}, Header: http.Header{"X-Ratelimit-Reset-In": []string{"5"}},
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)), Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
} }

View file

@ -342,7 +342,7 @@ func selectedKinds(kinds, sources []string, all bool) ([]model.Kind, error) {
return artwork.ReprocessKinds, nil return artwork.ReprocessKinds, nil
} }
if len(kinds) == 0 { if len(kinds) == 0 {
return nil, fmt.Errorf("no selector given: pass --kind, --source or --all") return nil, errors.New("no selector given: pass --kind, --source or --all")
} }
return parseAll(kinds, func(s string) (model.Kind, error) { return parseAll(kinds, func(s string) (model.Kind, error) {
return parseArtworkKind(s, artwork.ReprocessKinds) return parseArtworkKind(s, artwork.ReprocessKinds)
@ -428,7 +428,7 @@ func promptConfirm(in io.Reader, verb string) confirmFunc {
return func(out io.Writer, total, external int64) bool { return func(out io.Writer, total, external int64) bool {
var cost string var cost string
if external > 0 { if external > 0 {
cost = fmt.Sprintf(" %s", externalLookupLine(external)) cost = " " + externalLookupLine(external)
} }
fmt.Fprintf(out, "\nThis will %s %d items.%s Continue? [y/N] ", verb, total, cost) fmt.Fprintf(out, "\nThis will %s %d items.%s Continue? [y/N] ", verb, total, cost)
var answer string var answer string
@ -559,7 +559,7 @@ func cancelSelection(kinds, priorities []string, all bool) ([]model.Kind, []int,
return nil, nil, nil return nil, nil, nil
} }
if len(kinds) == 0 && len(priorities) == 0 { if len(kinds) == 0 && len(priorities) == 0 {
return nil, nil, fmt.Errorf("no selector given: pass --kind, --priority or --all") return nil, nil, errors.New("no selector given: pass --kind, --priority or --all")
} }
// RefreshableKinds, not ReprocessKinds: media files are queued, so --kind must reach them. // RefreshableKinds, not ReprocessKinds: media files are queued, so --kind must reach them.
outKinds, err := parseAll(kinds, func(s string) (model.Kind, error) { outKinds, err := parseAll(kinds, func(s string) (model.Kind, error) {

View file

@ -425,9 +425,9 @@ var _ = Describe("explainConfig", func() {
var _ = Describe("artwork refresh command", func() { var _ = Describe("artwork refresh command", func() {
It("requires at least one argument", func() { It("requires at least one argument", func() {
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{})).To(HaveOccurred()) Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{})).ToNot(Succeed())
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"id1"})).ToNot(HaveOccurred()) Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"id1"})).To(Succeed())
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"ar", "id1"})).ToNot(HaveOccurred()) Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"ar", "id1"})).To(Succeed())
}) })
}) })
@ -810,8 +810,8 @@ var _ = Describe("reprocessArtwork", func() {
var _ = Describe("artwork status command", func() { var _ = Describe("artwork status command", func() {
It("takes no arguments", func() { It("takes no arguments", func() {
Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{})).ToNot(HaveOccurred()) Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{})).To(Succeed())
Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{"x"})).To(HaveOccurred()) Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{"x"})).ToNot(Succeed())
}) })
}) })

View file

@ -50,11 +50,11 @@ func prettyMarshal(v any) ([]byte, error) {
out := v.([]core.InspectOutput) out := v.([]core.InspectOutput)
var res strings.Builder var res strings.Builder
for i := range out { for i := range out {
res.WriteString(fmt.Sprintf("====================\nFile: %s\n\n", out[i].File)) fmt.Fprintf(&res, "====================\nFile: %s\n\n", out[i].File)
t, _ := toml.Marshal(out[i].RawTags) t, _ := toml.Marshal(out[i].RawTags)
res.WriteString(fmt.Sprintf("Raw tags:\n%s\n\n", t)) fmt.Fprintf(&res, "Raw tags:\n%s\n\n", t)
t, _ = toml.Marshal(out[i].MappedTags) t, _ = toml.Marshal(out[i].MappedTags)
res.WriteString(fmt.Sprintf("Mapped tags:\n%s\n\n", t)) fmt.Fprintf(&res, "Mapped tags:\n%s\n\n", t)
} }
return []byte(res.String()), nil return []byte(res.String()), nil
} }

View file

@ -94,7 +94,10 @@ func writeMissingList(w io.Writer, format string, mfs model.MediaFileCursor) err
if err != nil { if err != nil {
return err return err
} }
j, _ := json.Marshal(displayMissingFile{ID: mf.ID, LibraryID: mf.LibraryID, Title: mf.Title, Album: mf.Album, Artist: mf.Artist, Path: mf.Path}) j, err := json.Marshal(displayMissingFile{ID: mf.ID, LibraryID: mf.LibraryID, Title: mf.Title, Album: mf.Album, Artist: mf.Artist, Path: mf.Path})
if err != nil {
return err
}
_, _ = fmt.Fprintf(bw, "%s%s", sep, j) _, _ = fmt.Fprintf(bw, "%s%s", sep, j)
sep = "," sep = ","
} }

View file

@ -247,7 +247,10 @@ func runList(ctx context.Context) {
display[idx].Public = playlist.Public display[idx].Public = playlist.Public
} }
j, _ := json.Marshal(display) j, err := json.Marshal(display)
if err != nil {
log.Fatal(ctx, "Failed to encode playlists", err)
}
fmt.Printf("%s\n", j) fmt.Printf("%s\n", j)
} }
} }

View file

@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/csv" "encoding/csv"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -307,7 +308,7 @@ func formatPluginList(list model.Plugins, format string) (string, error) {
_ = w.Write([]string{"id", "name", "version", "enabled", "last error"}) _ = w.Write([]string{"id", "name", "version", "enabled", "last error"})
for _, p := range list { for _, p := range list {
name, version := manifestSummary(p) name, version := manifestSummary(p)
_ = w.Write([]string{p.ID, name, version, fmt.Sprintf("%t", p.Enabled), p.LastError}) _ = w.Write([]string{p.ID, name, version, strconv.FormatBool(p.Enabled), p.LastError})
} }
w.Flush() w.Flush()
return sb.String(), w.Error() return sb.String(), w.Error()
@ -440,7 +441,7 @@ func readConfigFile(ctx context.Context, path string) string {
func applyPluginEdit(ctx context.Context, mgr pluginManager, cur *model.Plugin, opts pluginEditOptions) error { func applyPluginEdit(ctx context.Context, mgr pluginManager, cur *model.Plugin, opts pluginEditOptions) error {
if opts.config == nil && opts.users == nil && opts.allUsers == nil && if opts.config == nil && opts.users == nil && opts.allUsers == nil &&
opts.libraries == nil && opts.allLibraries == nil && opts.writeAccess == nil { opts.libraries == nil && opts.allLibraries == nil && opts.writeAccess == nil {
return fmt.Errorf("nothing to update: provide at least one of --config/--users/--libraries/--write-access") return errors.New("nothing to update: provide at least one of --config/--users/--libraries/--write-access")
} }
id := cur.ID id := cur.ID
if opts.config != nil { if opts.config != nil {
@ -499,18 +500,18 @@ func usersToJSON(value string) (string, error) {
} }
if strings.HasPrefix(strings.TrimSpace(value), "[") { if strings.HasPrefix(strings.TrimSpace(value), "[") {
if !json.Valid([]byte(value)) { if !json.Valid([]byte(value)) {
return "", fmt.Errorf("invalid JSON in --users") return "", errors.New("invalid JSON in --users")
} }
return value, nil return value, nil
} }
var names []string var names []string
for _, u := range strings.Split(value, ",") { for u := range strings.SplitSeq(value, ",") {
if u = strings.TrimSpace(u); u != "" { if u = strings.TrimSpace(u); u != "" {
names = append(names, u) names = append(names, u)
} }
} }
b, _ := json.Marshal(names) b, err := json.Marshal(names)
return string(b), nil return string(b), err
} }
// librariesToJSON accepts either a JSON array (starts with '[') or a // librariesToJSON accepts either a JSON array (starts with '[') or a
@ -521,12 +522,12 @@ func librariesToJSON(value string) (string, error) {
} }
if strings.HasPrefix(strings.TrimSpace(value), "[") { if strings.HasPrefix(strings.TrimSpace(value), "[") {
if !json.Valid([]byte(value)) { if !json.Valid([]byte(value)) {
return "", fmt.Errorf("invalid JSON in --libraries") return "", errors.New("invalid JSON in --libraries")
} }
return value, nil return value, nil
} }
ids := []int{} ids := []int{}
for _, l := range strings.Split(value, ",") { for l := range strings.SplitSeq(value, ",") {
if l = strings.TrimSpace(l); l != "" { if l = strings.TrimSpace(l); l != "" {
id, err := strconv.Atoi(l) id, err := strconv.Atoi(l)
if err != nil { if err != nil {
@ -535,8 +536,8 @@ func librariesToJSON(value string) (string, error) {
ids = append(ids, id) ids = append(ids, id)
} }
} }
b, _ := json.Marshal(ids) b, err := json.Marshal(ids)
return string(b), nil return string(b), err
} }
var pluginRescanCmd = &cobra.Command{ var pluginRescanCmd = &cobra.Command{

View file

@ -449,6 +449,7 @@ func startPluginManager(ctx context.Context) func() error {
} }
// TODO: Implement some struct tags to map flags to viper // TODO: Implement some struct tags to map flags to viper
func init() { func init() {
cobra.OnInitialize(func() { cobra.OnInitialize(func() {
conf.InitConfig(cfgFile, true) conf.InitConfig(cfgFile, true)

View file

@ -469,7 +469,10 @@ func runUserList(ctx context.Context) {
users[idx].Libraries = paths users[idx].Libraries = paths
} }
j, _ := json.Marshal(users) j, err := json.Marshal(users)
if err != nil {
log.Fatal(ctx, "Failed to encode users", err)
}
fmt.Printf("%s\n", j) fmt.Printf("%s\n", j)
} }
} }

View file

@ -3,6 +3,7 @@ package conf
import ( import (
"cmp" "cmp"
"encoding" "encoding"
"errors"
"fmt" "fmt"
"math" "math"
"net/url" "net/url"
@ -101,6 +102,7 @@ type Options struct {
DefaultUIVolume int DefaultUIVolume int
UISearchDebounceMs int UISearchDebounceMs int
UICoverArtSize int UICoverArtSize int
UIAppendRemixers bool // Whether to show remixers after the track artists in the UI
EnableReplayGain bool EnableReplayGain bool
EnableCoverAnimation bool EnableCoverAnimation bool
EnableNowPlaying bool EnableNowPlaying bool
@ -142,6 +144,7 @@ type Options struct {
DevUIShowConfig bool DevUIShowConfig bool
DevNewEventStream bool DevNewEventStream bool
DevOffsetOptimize int DevOffsetOptimize int
DevMaxPlaylistTracksPerRequest int
DevArtworkMaxRequests int DevArtworkMaxRequests int
DevArtworkThrottleBacklogLimit int DevArtworkThrottleBacklogLimit int
DevArtworkThrottleBacklogTimeout time.Duration DevArtworkThrottleBacklogTimeout time.Duration
@ -392,7 +395,7 @@ func Load(noConfigDump bool) {
out := os.Stderr out := os.Stderr
if s.LogFile != "" { if s.LogFile != "" {
if mkErr := os.MkdirAll(filepath.Dir(s.LogFile), os.ModePerm); mkErr != nil { if mkErr := os.MkdirAll(filepath.Dir(s.LogFile), os.ModePerm); mkErr != nil {
logFatal(fmt.Sprintf("Error creating log file directory: %s", mkErr.Error())) logFatal("Error creating log file directory: " + mkErr.Error())
} }
out, err = os.OpenFile(s.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 { if err != nil {
@ -728,7 +731,7 @@ func asWrittenInConfigFile(keys []string) []string {
}) })
} }
// Matches keys and section headers in all supported config formats. // configFileKeyRx matches keys and section headers in all supported config formats.
var configFileKeyRx = regexp.MustCompile(`(?m)^\s*\[?\s*"?([\w.]+)"?\s*[]=:]`) var configFileKeyRx = regexp.MustCompile(`(?m)^\s*\[?\s*"?([\w.]+)"?\s*[]=:]`)
// configKeys maps every accepted option name, lowercased, to its canonical spelling, // configKeys maps every accepted option name, lowercased, to its canonical spelling,
@ -863,7 +866,7 @@ func (s *Options) validateEnforceNonRootUser() error {
} }
if getEUID() == 0 { if getEUID() == 0 {
return fmt.Errorf("EnforceNonRootUser is enabled but Navidrome is running as root") return errors.New("EnforceNonRootUser is enabled but Navidrome is running as root")
} }
return nil return nil
@ -1019,6 +1022,7 @@ func setViperDefaults() {
viper.SetDefault("defaultuivolume", consts.DefaultUIVolume) viper.SetDefault("defaultuivolume", consts.DefaultUIVolume)
viper.SetDefault("uisearchdebouncems", consts.DefaultUISearchDebounceMs) viper.SetDefault("uisearchdebouncems", consts.DefaultUISearchDebounceMs)
viper.SetDefault("uicoverartsize", consts.DefaultUICoverArtSize) viper.SetDefault("uicoverartsize", consts.DefaultUICoverArtSize)
viper.SetDefault("uiappendremixers", true)
viper.SetDefault("enablereplaygain", true) viper.SetDefault("enablereplaygain", true)
viper.SetDefault("enablecoveranimation", true) viper.SetDefault("enablecoveranimation", true)
viper.SetDefault("enablenowplaying", true) viper.SetDefault("enablenowplaying", true)
@ -1117,6 +1121,7 @@ func setViperDefaults() {
viper.SetDefault("devneweventstream", true) viper.SetDefault("devneweventstream", true)
viper.SetDefault("devapiv1", false) viper.SetDefault("devapiv1", false)
viper.SetDefault("devoffsetoptimize", 50000) viper.SetDefault("devoffsetoptimize", 50000)
viper.SetDefault("devmaxplaylisttracksperrequest", 50000)
// Half the pool: streams may take up to this many connections, leaving the rest for the scanner, // Half the pool: streams may take up to this many connections, leaving the rest for the scanner,
// scrobbles and the UI. See MaxOpenConns. // scrobbles and the UI. See MaxOpenConns.
viper.SetDefault("jellyfin.maxconcurrentstreams", max(2, MaxOpenConns()/2)) viper.SetDefault("jellyfin.maxconcurrentstreams", max(2, MaxOpenConns()/2))

View file

@ -109,7 +109,7 @@ var _ = Describe("Configuration", func() {
It("rejects a URL that cannot be parsed", func() { It("rejects a URL that cannot be parsed", func() {
fn := conf.ValidateURL("TestOption", "://invalid") fn := conf.ValidateURL("TestOption", "://invalid")
Expect(fn()).To(HaveOccurred()) Expect(fn()).ToNot(Succeed())
}) })
It("rejects a URL without a host", func() { It("rejects a URL without a host", func() {

View file

@ -213,12 +213,10 @@ var HTTPUserAgent = "Navidrome/" + Version + " - https://github.com/navidrome"
var ( var (
VariousArtists = "Various Artists" VariousArtists = "Various Artists"
// TODO This will be dynamic when using disambiguation VariousArtistsID = "63sqASlAfjbGMuLP4JhnZU" // TODO This will be dynamic when using disambiguation
VariousArtistsID = "63sqASlAfjbGMuLP4JhnZU"
UnknownAlbum = "[Unknown Album]" UnknownAlbum = "[Unknown Album]"
UnknownArtist = "[Unknown Artist]" UnknownArtist = "[Unknown Artist]"
// TODO This will be dynamic when using disambiguation UnknownArtistID = id.NewHash(strings.ToLower(UnknownArtist)) // TODO This will be dynamic when using disambiguation
UnknownArtistID = id.NewHash(strings.ToLower(UnknownArtist))
VariousArtistsMbzId = "89ad4ac3-39f7-470e-963a-56509c546377" VariousArtistsMbzId = "89ad4ac3-39f7-470e-963a-56509c546377"
ArtistJoiner = " • " ArtistJoiner = " • "

View file

@ -6,7 +6,7 @@ import (
) )
var ( var (
// This will be set in build time. If not, version will be set to "dev" // gitTag will be set in build time. If not, version will be set to "dev"
gitTag string gitTag string
gitSha string gitSha string
) )

View file

@ -24,7 +24,7 @@ var _ = Describe("SessionKeys", func() {
Expect(sk.KeyName).To(Equal("fakeSessionKey")) Expect(sk.KeyName).To(Equal("fakeSessionKey"))
}) })
It("stores a value in the DB", func() { It("stores a value in the DB", func() {
Expect(sk.Put(ctx, user.ID, "test-stored-value")).To(BeNil()) Expect(sk.Put(ctx, user.ID, "test-stored-value")).To(Succeed())
}) })
It("fetches the stored value", func() { It("fetches the stored value", func() {
value, err := sk.Get(ctx, user.ID) value, err := sk.Get(ctx, user.ID)
@ -32,7 +32,7 @@ var _ = Describe("SessionKeys", func() {
Expect(value).To(Equal("test-stored-value")) Expect(value).To(Equal("test-stored-value"))
}) })
It("deletes the stored value", func() { It("deletes the stored value", func() {
Expect(sk.Delete(ctx, user.ID)).To(BeNil()) Expect(sk.Delete(ctx, user.ID)).To(Succeed())
}) })
It("handles a not found value", func() { It("handles a not found value", func() {
_, err := sk.Get(ctx, "u-2") _, err := sk.Get(ctx, "u-2")

View file

@ -61,7 +61,7 @@ func (a *archiver) ZipArtist(ctx context.Context, id string, format string, bitr
return a.zipAlbums(ctx, id, format, bitrate, out, filter, model.Artist{ID: id}.CoverArtID()) return a.zipAlbums(ctx, id, format, bitrate, out, filter, model.Artist{ID: id}.CoverArtID())
} }
// rootArt, when set, is added to the archive root. // zipAlbums writes the songs matching filters to out. rootArt, when set, is added to the archive root.
func (a *archiver) zipAlbums(ctx context.Context, id string, format string, bitrate int, out io.Writer, filters squirrel.Sqlizer, rootArt model.ArtworkID) error { func (a *archiver) zipAlbums(ctx context.Context, id string, format string, bitrate int, out io.Writer, filters squirrel.Sqlizer, rootArt model.ArtworkID) error {
mfs, err := a.ds.MediaFile().GetAll(ctx, model.QueryOptions{Filters: filters, Sort: "album"}) mfs, err := a.ds.MediaFile().GetAll(ctx, model.QueryOptions{Filters: filters, Sort: "album"})
if err != nil { if err != nil {
@ -112,8 +112,8 @@ func createZipWriter(out io.Writer, format string, bitrate int) *zip.Writer {
return z return z
} }
// Tried in order; the first one whose values are distinct across the clashing albums wins. // albumDisambiguators are tried in order; the first one whose values are distinct across the clashing
// One album may have an empty value: it keeps the plain name, which the others can't clash with. // albums wins. One album may have an empty value: it keeps the plain name, which the others can't clash with.
var albumDisambiguators = []func(model.MediaFile) string{ var albumDisambiguators = []func(model.MediaFile) string{
func(mf model.MediaFile) string { return mf.Tags.First(model.TagAlbumVersion) }, func(mf model.MediaFile) string { return mf.Tags.First(model.TagAlbumVersion) },
func(mf model.MediaFile) string { func(mf model.MediaFile) string {
@ -346,7 +346,7 @@ func (a *archiver) readCoverArt(ctx context.Context, artID model.ArtworkID) ([]b
return io.ReadAll(img) return io.ReadAll(img)
} }
// Resizing may re-encode the image, so the type comes from its bytes. // coverArtExtension takes the type from the image bytes, because resizing may re-encode the image.
func coverArtExtension(data []byte) string { func coverArtExtension(data []byte) string {
switch http.DetectContentType(data) { switch http.DetectContentType(data) {
case "image/jpeg": case "image/jpeg":

View file

@ -60,12 +60,12 @@ var _ = Describe("Archiver", func() {
out := new(bytes.Buffer) out := new(bytes.Buffer)
err := arch.ZipAlbum(ctx, "1", "mp3", 128, out) err := arch.ZipAlbum(ctx, "1", "mp3", 128, out)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(zr.File)).To(Equal(2)) Expect(zr.File).To(HaveLen(2))
Expect(zr.File[0].Name).To(Equal("Album_Promo/01 - track1.mp3")) Expect(zr.File[0].Name).To(Equal("Album_Promo/01 - track1.mp3"))
Expect(zr.File[1].Name).To(Equal("Album_Promo/02 - track2.mp3")) Expect(zr.File[1].Name).To(Equal("Album_Promo/02 - track2.mp3"))
}) })
@ -109,12 +109,12 @@ var _ = Describe("Archiver", func() {
out := new(bytes.Buffer) out := new(bytes.Buffer)
err := arch.ZipArtist(ctx, "1", "mp3", 128, out) err := arch.ZipArtist(ctx, "1", "mp3", 128, out)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(zr.File)).To(Equal(2)) Expect(zr.File).To(HaveLen(2))
Expect(zr.File[0].Name).To(Equal("Album 1/01 - track1.mp3")) Expect(zr.File[0].Name).To(Equal("Album 1/01 - track1.mp3"))
Expect(zr.File[1].Name).To(Equal("Album 1/02 - track2.mp3")) Expect(zr.File[1].Name).To(Equal("Album 1/02 - track2.mp3"))
}) })
@ -131,7 +131,7 @@ var _ = Describe("Archiver", func() {
out := new(bytes.Buffer) out := new(bytes.Buffer)
Expect(arch.ZipArtist(ctx, "1", "mp3", 128, out)).To(Succeed()) Expect(arch.ZipArtist(ctx, "1", "mp3", 128, out)).To(Succeed())
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
names := make([]string, len(zr.File)) names := make([]string, len(zr.File))
for i, f := range zr.File { for i, f := range zr.File {
names[i] = f.Name names[i] = f.Name
@ -296,16 +296,16 @@ var _ = Describe("Archiver", func() {
out := new(bytes.Buffer) out := new(bytes.Buffer)
err := arch.ZipShare(ctx, share, out) err := arch.ZipShare(ctx, share, out)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
// Share.Load records a visit; re-loading here would double-count // Share.Load records a visit; re-loading here would double-count
// every download. // every download.
sh.AssertNotCalled(GinkgoT(), "Load", mock.Anything, mock.Anything) sh.AssertNotCalled(GinkgoT(), "Load", mock.Anything, mock.Anything)
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(zr.File)).To(Equal(2)) Expect(zr.File).To(HaveLen(2))
Expect(zr.File[0].Name).To(Equal("01 - Artist 1 - track1.mp3")) Expect(zr.File[0].Name).To(Equal("01 - Artist 1 - track1.mp3"))
Expect(zr.File[1].Name).To(Equal("02 - Artist 2 - track2.mp3")) Expect(zr.File[1].Name).To(Equal("02 - Artist 2 - track2.mp3"))
@ -315,7 +315,7 @@ var _ = Describe("Archiver", func() {
Context("ZipPlaylist", func() { Context("ZipPlaylist", func() {
It("names the entries and the M3U lines after the resolved format", func() { It("names the entries and the M3U lines after the resolved format", func() {
pls := &model.Playlist{ID: "1", Name: "Test Playlist", Tracks: []model.PlaylistTrack{ pls := &model.Playlist{ID: "1", Name: "Test Playlist", Tracks: []model.PlaylistTrack{
{MediaFile: model.MediaFile{Path: "test_data/01 - track1.flac", Suffix: "flac", Artist: "Artist 1", Title: "track1"}}, {Path: "test_data/01 - track1.flac", Suffix: "flac", Artist: "Artist 1", Title: "track1"},
}} }}
plRepo := &mockPlaylistRepository{} plRepo := &mockPlaylistRepository{}
plRepo.On("GetWithTracks", "1", true, false).Return(pls, nil) plRepo.On("GetWithTracks", "1", true, false).Return(pls, nil)
@ -339,8 +339,8 @@ var _ = Describe("Archiver", func() {
It("zips a playlist correctly", func() { It("zips a playlist correctly", func() {
tracks := []model.PlaylistTrack{ tracks := []model.PlaylistTrack{
{MediaFile: model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "AC/DC", Title: "track1"}}, {Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "AC/DC", Title: "track1"},
{MediaFile: model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "Artist 2", Title: "track2"}}, {Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "Artist 2", Title: "track2"},
} }
pls := &model.Playlist{ pls := &model.Playlist{
@ -356,23 +356,23 @@ var _ = Describe("Archiver", func() {
out := new(bytes.Buffer) out := new(bytes.Buffer)
err := arch.ZipPlaylist(ctx, "1", "mp3", 128, out) err := arch.ZipPlaylist(ctx, "1", "mp3", 128, out)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(zr.File)).To(Equal(3)) Expect(zr.File).To(HaveLen(3))
Expect(zr.File[0].Name).To(Equal("01 - AC_DC - track1.mp3")) Expect(zr.File[0].Name).To(Equal("01 - AC_DC - track1.mp3"))
Expect(zr.File[1].Name).To(Equal("02 - Artist 2 - track2.mp3")) Expect(zr.File[1].Name).To(Equal("02 - Artist 2 - track2.mp3"))
Expect(zr.File[2].Name).To(Equal("Test Playlist.m3u")) Expect(zr.File[2].Name).To(Equal("Test Playlist.m3u"))
// Verify M3U content // Verify M3U content
m3uFile, err := zr.File[2].Open() m3uFile, err := zr.File[2].Open()
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
defer m3uFile.Close() defer m3uFile.Close()
m3uContent, err := io.ReadAll(m3uFile) m3uContent, err := io.ReadAll(m3uFile)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
expectedM3U := "#EXTM3U\n#PLAYLIST:Test Playlist\n#EXTINF:0,AC/DC - track1\n01 - AC_DC - track1.mp3\n#EXTINF:0,Artist 2 - track2\n02 - Artist 2 - track2.mp3\n" expectedM3U := "#EXTM3U\n#PLAYLIST:Test Playlist\n#EXTINF:0,AC/DC - track1\n01 - AC_DC - track1.mp3\n#EXTINF:0,Artist 2 - track2\n02 - Artist 2 - track2.mp3\n"
Expect(string(m3uContent)).To(Equal(expectedM3U)) Expect(string(m3uContent)).To(Equal(expectedM3U))
@ -454,7 +454,7 @@ var _ = Describe("Archiver", func() {
ID: "1", ID: "1",
Name: "Test Playlist", Name: "Test Playlist",
Tracks: []model.PlaylistTrack{ Tracks: []model.PlaylistTrack{
{MediaFile: model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Artist: "Artist 1", Title: "track1"}}, {Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Artist: "Artist 1", Title: "track1"},
}, },
}, nil) }, nil)
ds.On("Playlist", mock.Anything).Return(plRepo) ds.On("Playlist", mock.Anything).Return(plRepo)

View file

@ -341,7 +341,7 @@ var _ = Describe("Artwork", func() {
img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf4"), 0, false) img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf4"), 0, false)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(len(readAll(img))).To(BeNumerically(">", 0)) Expect(readAll(img)).ToNot(BeEmpty())
Expect(queueRepo.Data[primaryKey("mf", "mf4")].Priority).To(Equal(model.ArtworkPriorityBump)) Expect(queueRepo.Data[primaryKey("mf", "mf4")].Priority).To(Equal(model.ArtworkPriorityBump))
_, err = artRepo.GetItemArtwork(ctx, model.KindMediaFileArtwork, "mf4", model.ImageTypePrimary) _, err = artRepo.GetItemArtwork(ctx, model.KindMediaFileArtwork, "mf4", model.ImageTypePrimary)
Expect(err).To(MatchError(model.ErrNotFound)) Expect(err).To(MatchError(model.ErrNotFound))

View file

@ -15,8 +15,14 @@ func BenchmarkImageDecode(b *testing.B) {
name string name string
gen func(tb testing.TB, w, h int) []byte gen func(tb testing.TB, w, h int) []byte
}{ }{
{"jpeg", func(tb testing.TB, w, h int) []byte { return generateJPEG(tb, w, h, 75) }}, {"jpeg", func(tb testing.TB, w, h int) []byte {
{"png", func(tb testing.TB, w, h int) []byte { return generatePNG(tb, w, h) }}, tb.Helper()
return generateJPEG(tb, w, h, 75)
}},
{"png", func(tb testing.TB, w, h int) []byte {
tb.Helper()
return generatePNG(tb, w, h)
}},
} }
for _, format := range formats { for _, format := range formats {

View file

@ -200,7 +200,7 @@ func (d *discArtworkReader) fromDiscSubtitle(ctx context.Context, subtitle strin
} }
} }
// filepath.Match's '\' escape is excluded on purpose: treating it as a metachar // globMetaChars excludes filepath.Match's '\' escape on purpose: treating it as a metachar
// would misalign the literal-prefix extraction in extractDiscNumber. // would misalign the literal-prefix extraction in extractDiscNumber.
const globMetaChars = "*?[" const globMetaChars = "*?["

View file

@ -10,14 +10,14 @@ import (
) )
const ( const (
// 4 bits per channel: coarse enough that near-identical pixels land together, fine enough that // bits per channel: 4 is coarse enough that near-identical pixels land together, fine enough that
// distinct colours stay apart. // distinct colours stay apart.
bits = 4 bits = 4
nBins = 1 << (3 * bits) nBins = 1 << (3 * bits)
// Only the heaviest bins can win, and merging is O(n^2) over whatever survives. // maxBins caps the bins kept: only the heaviest can win, and merging is O(n^2) over whatever survives.
maxBins = 64 maxBins = 64
// Oklab distance below which two bins are the same colour to the eye. Merging matters because a // mergeDist is the Oklab distance below which two bins are the same colour to the eye. Merging matters
// gradient splits across adjacent bins and would otherwise lose to a smaller flat region. // because a gradient splits across adjacent bins and would otherwise lose to a smaller flat region.
mergeDist = 0.10 mergeDist = 0.10
) )

View file

@ -185,7 +185,7 @@ var _ = Describe("Acquisition → serve loop", func() {
art, err := artRepo.GetImage(ctx, ia.Hash) art, err := artRepo.GetImage(ctx, ia.Hash)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(art.Mime).To(Equal("image/png")) Expect(art.Mime).To(Equal("image/png"))
Expect(len(readAll(img))).To(BeNumerically(">", 0)) Expect(readAll(img)).ToNot(BeEmpty())
}) })
It("acquires a radio station's uploaded image and serves it", func() { It("acquires a radio station's uploaded image and serves it", func() {
@ -214,7 +214,7 @@ var _ = Describe("Acquisition → serve loop", func() {
Expect(provisional.Placeholder).To(BeFalse()) Expect(provisional.Placeholder).To(BeFalse())
Expect(provisional.Hash).ToNot(BeEmpty()) Expect(provisional.Hash).ToNot(BeEmpty())
provisionalBytes := readAll(provisional) provisionalBytes := readAll(provisional)
Expect(len(provisionalBytes)).To(BeNumerically(">", 0)) Expect(provisionalBytes).ToNot(BeEmpty())
_, err = artRepo.GetItemArtwork(ctx, model.KindMediaFileArtwork, "mf1", model.ImageTypePrimary) _, err = artRepo.GetItemArtwork(ctx, model.KindMediaFileArtwork, "mf1", model.ImageTypePrimary)
Expect(err).To(MatchError(model.ErrNotFound), "provisional serving must not write a state row") Expect(err).To(MatchError(model.ErrNotFound), "provisional serving must not write a state row")

View file

@ -2,6 +2,7 @@ package e2e
import ( import (
"fmt" "fmt"
"strconv"
"testing/fstest" "testing/fstest"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
@ -274,7 +275,7 @@ var _ = Describe("Disc artwork resolution", func() {
for i, name := range discNames { for i, name := range discNames {
discNum := i + 1 discNum := i + 1
prefix := fmt.Sprintf("Pop; Rock/Grateful Dead/(2001) The Golden Road/%s/", name) prefix := fmt.Sprintf("Pop; Rock/Grateful Dead/(2001) The Golden Road/%s/", name)
layout[prefix+"01 - Track.mp3"] = trackFile(1, fmt.Sprintf("T%d", discNum), map[string]any{"disc": fmt.Sprintf("%d", discNum)}) layout[prefix+"01 - Track.mp3"] = trackFile(1, fmt.Sprintf("T%d", discNum), map[string]any{"disc": strconv.Itoa(discNum)})
layout[prefix+"folder.jpg"] = smallPNG(fmt.Sprintf("disc-%02d-folder", discNum)) layout[prefix+"folder.jpg"] = smallPNG(fmt.Sprintf("disc-%02d-folder", discNum))
} }
setLayout(layout) setLayout(layout)
@ -313,7 +314,7 @@ var _ = Describe("Disc artwork resolution", func() {
} }
for i := 1; i <= 3; i++ { for i := 1; i <= 3; i++ {
prefix := fmt.Sprintf("Album/Disc %02d/", i) prefix := fmt.Sprintf("Album/Disc %02d/", i)
layout[prefix+"01 - Track.mp3"] = trackFile(1, fmt.Sprintf("T%d", i), map[string]any{"disc": fmt.Sprintf("%d", i)}) layout[prefix+"01 - Track.mp3"] = trackFile(1, fmt.Sprintf("T%d", i), map[string]any{"disc": strconv.Itoa(i)})
layout[prefix+"folder.jpg"] = smallPNG(fmt.Sprintf("disc-%02d-folder", i)) layout[prefix+"folder.jpg"] = smallPNG(fmt.Sprintf("disc-%02d-folder", i))
} }
setLayout(layout) setLayout(layout)

View file

@ -3,6 +3,7 @@ package e2e
import ( import (
"bytes" "bytes"
"context" "context"
"errors"
"fmt" "fmt"
"hash/fnv" "hash/fnv"
"image" "image"
@ -117,7 +118,7 @@ func setupResolutionHarness() {
// size=0 requests stream originals, so this reader is never called (serving_test covers resizing). // size=0 requests stream originals, so this reader is never called (serving_test covers resizing).
imgCache := cache.NewFileCache("ArtworkResolutionE2E", "100MB", "images", 0, imgCache := cache.NewFileCache("ArtworkResolutionE2E", "100MB", "images", 0,
func(context.Context, cache.Item) (io.Reader, error) { func(context.Context, cache.Item) (io.Reader, error) {
return nil, fmt.Errorf("resize not exercised in e2e") return nil, errors.New("resize not exercised in e2e")
}) })
Eventually(func() bool { return imgCache.Available(rctx) }, 10*time.Second).Should(BeTrue()) Eventually(func() bool { return imgCache.Available(rctx) }, 10*time.Second).Should(BeTrue())

View file

@ -28,7 +28,7 @@ const (
func fromArtistFolder(ctx context.Context, libFS fs.FS, libPath, artistFolder, pattern string) sourceFunc { func fromArtistFolder(ctx context.Context, libFS fs.FS, libPath, artistFolder, pattern string) sourceFunc {
return func() (io.ReadCloser, string, error) { return func() (io.ReadCloser, string, error) {
if libFS == nil { if libFS == nil {
return nil, "", fmt.Errorf("artist folder lookup unavailable") return nil, "", errors.New("artist folder lookup unavailable")
} }
rel, err := filepath.Rel(libPath, artistFolder) rel, err := filepath.Rel(libPath, artistFolder)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {

View file

@ -45,6 +45,8 @@ func (o outcome) String() string {
return "foundStale" return "foundStale"
case outcomeAbsent: case outcomeAbsent:
return "absent" return "absent"
case outcomeFailed:
fallthrough
default: default:
return "failed" return "failed"
} }

View file

@ -180,8 +180,9 @@ func chainFetchesExternal(priority string) bool {
return false return false
} }
// Album and artist fetches stop here when the resolver is local-only, rather than at each point in // fetchExternalAlbum and fetchExternalArtist are where album and artist fetches stop when the resolver is
// the chain walk; resolvePlaylist gates the third network path, the m3u image URL, itself. // local-only, rather than at each point in the chain walk; resolvePlaylist gates the third network path,
// the m3u image URL, itself.
func (r *resolver) fetchExternalAlbum(ctx context.Context, al model.Album) (io.ReadCloser, string, error) { func (r *resolver) fetchExternalAlbum(ctx context.Context, al model.Album) (io.ReadCloser, string, error) {
if r.ext == nil { if r.ext == nil {
return nil, "", nil return nil, "", nil

View file

@ -56,7 +56,7 @@ func fromExternalFile(ctx context.Context, libFS fs.FS, files []string, pattern
} }
} }
// These regexes are used to match the picture type in the file, in the order they are listed. // picTypeRegexes match the picture type in the file, in the order they are listed.
var picTypeRegexes = []*regexp.Regexp{ var picTypeRegexes = []*regexp.Regexp{
regexp.MustCompile(`(?i).*cover.*front.*|.*front.*cover.*`), regexp.MustCompile(`(?i).*cover.*front.*|.*front.*cover.*`),
regexp.MustCompile(`(?i).*front.*`), regexp.MustCompile(`(?i).*front.*`),

View file

@ -230,7 +230,7 @@ func pack(w, h int, hasAlpha bool, lx, ly int,
return hash return hash
} }
// NRGBA, not RGBA: ThumbHash requires non-premultiplied RGB and the pipeline hands us a // toNRGBA returns NRGBA, not RGBA: ThumbHash requires non-premultiplied RGB and the pipeline hands us a
// premultiplied *image.RGBA, which draw.Draw un-premultiplies on the way in. // premultiplied *image.RGBA, which draw.Draw un-premultiplies on the way in.
func toNRGBA(img image.Image) *image.NRGBA { func toNRGBA(img image.Image) *image.NRGBA {
// Conservative: a sub-image re-slices Pix so the loops would read it correctly too, but the // Conservative: a sub-image re-slices Pix so the loops would read it correctly too, but the

View file

@ -7,6 +7,7 @@ import (
"slices" "slices"
"sync" "sync"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/utils/str" "github.com/navidrome/navidrome/utils/str"
) )
@ -94,7 +95,10 @@ func encodeSteps(steps []TraceStep, sourcePath string) string {
} }
out = append(out, storedStep{C: s.Candidate, O: s.Outcome, D: str.TruncateRunes(d, maxTraceDetail, "...")}) out = append(out, storedStep{C: s.Candidate, O: s.Outcome, D: str.TruncateRunes(d, maxTraceDetail, "...")})
} }
b, _ := json.Marshal(out) // []storedStep is all strings, so this cannot fail b, err := json.Marshal(out)
if err != nil {
log.Error("Artwork: Could not encode resolution trace", err)
}
return string(b) return string(b)
} }

View file

@ -87,7 +87,7 @@ var _ = Describe("Auth", func() {
Expect(claims.Issuer).To(Equal(consts.JWTIssuer)) Expect(claims.Issuer).To(Equal(consts.JWTIssuer))
Expect(claims.Subject).To(Equal("johndoe")) Expect(claims.Subject).To(Equal("johndoe"))
Expect(claims.UserID).To(Equal("123")) Expect(claims.UserID).To(Equal("123"))
Expect(claims.IsAdmin).To(Equal(true)) Expect(claims.IsAdmin).To(BeTrue())
Expect(claims.ExpiresAt).To(BeTemporally(">", time.Now())) Expect(claims.ExpiresAt).To(BeTemporally(">", time.Now()))
}) })
}) })

View file

@ -18,6 +18,7 @@ func userName(ctx context.Context) string {
// BFR We should only access files through the `storage.Storage` interface. This will require changing how // BFR We should only access files through the `storage.Storage` interface. This will require changing how
// TagLib and ffmpeg access files // TagLib and ffmpeg access files
var AbsolutePath = func(ctx context.Context, ds model.DataStore, libId int, path string) string { var AbsolutePath = func(ctx context.Context, ds model.DataStore, libId int, path string) string {
libPath, err := ds.Library().GetPath(ctx, libId) libPath, err := ds.Library().GetPath(ctx, libId)
if err != nil { if err != nil {

View file

@ -17,7 +17,7 @@ import (
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/server/events"
"github.com/navidrome/navidrome/utils" "github.com/navidrome/navidrome/utils"
. "github.com/navidrome/navidrome/utils/gg" "github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/slice" "github.com/navidrome/navidrome/utils/slice"
"github.com/navidrome/navidrome/utils/str" "github.com/navidrome/navidrome/utils/str"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
@ -125,7 +125,7 @@ func (e *provider) UpdateAlbumInfo(ctx context.Context, id string) (*model.Album
return nil, err return nil, err
} }
updatedAt := V(album.ExternalInfoUpdatedAt) updatedAt := gg.V(album.ExternalInfoUpdatedAt)
albumName := album.Name() albumName := album.Name()
if updatedAt.IsZero() { if updatedAt.IsZero() {
log.Debug(ctx, "AlbumInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", albumName) log.Debug(ctx, "AlbumInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", albumName)
@ -232,7 +232,7 @@ func (e *provider) refreshArtistInfo(ctx context.Context, id string) (auxArtist,
} }
// If we don't have any info, retrieves it now // If we don't have any info, retrieves it now
updatedAt := V(artist.ExternalInfoUpdatedAt) updatedAt := gg.V(artist.ExternalInfoUpdatedAt)
artistName := artist.Name() artistName := artist.Name()
if updatedAt.IsZero() { if updatedAt.IsZero() {
log.Debug(ctx, "ArtistInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", artistName) log.Debug(ctx, "ArtistInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", artistName)

View file

@ -19,8 +19,8 @@ import (
const ( const (
maxSeeds = 5 maxSeeds = 5
// Subsonic passes the client's count through unbounded, and it ends up as a SQL limit. 500 is // maxSimilarSongs caps the client's count, which Subsonic passes through unbounded and ends up as a SQL
// what the widest caller (similarAlbums, limit*5) legitimately asks for. // limit. 500 is what the widest caller (similarAlbums, limit*5) legitimately asks for.
maxSimilarSongs = 500 maxSimilarSongs = 500
) )

View file

@ -142,7 +142,7 @@ var _ = Describe("Provider - TopSongs", func() {
track := model.MediaFile{ track := model.MediaFile{
ID: "song-1", Title: "Song One", ArtistID: "artist-1", ID: "song-1", Title: "Song One", ArtistID: "artist-1",
Participants: model.Participants{model.RoleArtist: model.ParticipantList{ Participants: model.Participants{model.RoleArtist: model.ParticipantList{
{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"}}, {ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"},
}}, }},
} }
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{track}, nil) mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{track}, nil)
@ -173,7 +173,7 @@ var _ = Describe("Provider - TopSongs", func() {
track := model.MediaFile{ track := model.MediaFile{
ID: "one-track", Title: "Collab Song", ArtistID: "artist-1", ID: "one-track", Title: "Collab Song", ArtistID: "artist-1",
Participants: model.Participants{model.RoleArtist: model.ParticipantList{ Participants: model.Participants{model.RoleArtist: model.ParticipantList{
{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"}}, {ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"},
}}, }},
} }
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{track}, nil) mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{track}, nil)
@ -332,7 +332,7 @@ var _ = Describe("Provider - TopSongs", func() {
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
// Title track-fetch: tracks must carry RoleArtist participants so back-mapping routes them. // Title track-fetch: tracks must carry RoleArtist participants so back-mapping routes them.
participant1 := model.Participant{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}} participant1 := model.Participant{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}
song1 := model.MediaFile{ song1 := model.MediaFile{
ID: "song-1", Title: "Song One", Artist: "Artist One", ArtistID: "artist-1", ID: "song-1", Title: "Song One", Artist: "Artist One", ArtistID: "artist-1",
Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}}, Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}},
@ -373,7 +373,7 @@ var _ = Describe("Provider - TopSongs", func() {
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once() mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once()
// Title track-fetch: song2 must carry RoleArtist participants for back-mapping. // Title track-fetch: song2 must carry RoleArtist participants for back-mapping.
participant1 := model.Participant{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}} participant1 := model.Participant{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}
song2 := model.MediaFile{ song2 := model.MediaFile{
ID: "song-2", Title: "Song Two", Artist: "Artist One", ArtistID: "artist-1", ID: "song-2", Title: "Song Two", Artist: "Artist One", ArtistID: "artist-1",
Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}}, Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}},

View file

@ -293,7 +293,7 @@ func parseProbeOutput(data []byte) (*AudioProbeResult, error) {
return result, nil return result, nil
} }
return nil, fmt.Errorf("no audio stream found in ffprobe output") return nil, errors.New("no audio stream found in ffprobe output")
} }
func (e *ffmpeg) CmdPath() (string, error) { func (e *ffmpeg) CmdPath() (string, error) {
@ -552,7 +552,7 @@ func bitDepthToSampleFmt(bitDepth int) string {
} }
} }
// Path will always be an absolute path // createFFmpegCommand expects path to always be an absolute path
func createFFmpegCommand(cmd, path string, maxBitRate, offset int) []string { func createFFmpegCommand(cmd, path string, maxBitRate, offset int) []string {
var args []string var args []string
for _, s := range fixCmd(cmd) { for _, s := range fixCmd(cmd) {
@ -643,6 +643,7 @@ func (p *encoderProbe) has(cmdPath, encoder string) bool {
return true return true
case encoderProbeUnavailable: case encoderProbeUnavailable:
return false return false
case encoderProbeUnknown:
} }
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)

View file

@ -27,7 +27,7 @@ func TestFFmpeg(t *testing.T) {
_, file, _, _ := runtime.Caller(0) _, file, _, _ := runtime.Caller(0)
appPath, _ := filepath.Abs(filepath.Join(filepath.Dir(file), "..", "..")) appPath, _ := filepath.Abs(filepath.Join(filepath.Dir(file), "..", ".."))
confPath := filepath.Join(appPath, "tests", "navidrome-test.toml") confPath := filepath.Join(appPath, "tests", "navidrome-test.toml")
_ = os.Chdir(appPath) t.Chdir(appPath)
conf.LoadFromFile(confPath) conf.LoadFromFile(confPath)
log.SetLevel(log.LevelFatal) log.SetLevel(log.LevelFatal)
RegisterFailHandler(Fail) RegisterFailHandler(Fail)

View file

@ -111,7 +111,7 @@ func (s *libraryService) SetUserLibraries(ctx context.Context, userID string, li
func (s *libraryService) ValidateLibraryAccess(ctx context.Context, userID string, libraryID int) error { func (s *libraryService) ValidateLibraryAccess(ctx context.Context, userID string, libraryID int) error {
user, ok := request.UserFrom(ctx) user, ok := request.UserFrom(ctx)
if !ok { if !ok {
return fmt.Errorf("user not found in context") return errors.New("user not found in context")
} }
// Admin users have access to all libraries // Admin users have access to all libraries
@ -157,7 +157,7 @@ func (r *libraryRepositoryWrapper) Save(ctx context.Context, lib *model.Library)
return "", err return "", err
} }
err := r.LibraryRepository.Put(ctx, lib) err := r.Put(ctx, lib)
if err != nil { if err != nil {
return "", r.mapError(err) return "", r.mapError(err)
} }
@ -205,7 +205,7 @@ func (r *libraryRepositoryWrapper) Update(ctx context.Context, id string, entity
pidChanged := (updatesColumn(cols, "pidAlbum") && originalLib.PIDAlbum != lib.PIDAlbum) || pidChanged := (updatesColumn(cols, "pidAlbum") && originalLib.PIDAlbum != lib.PIDAlbum) ||
(updatesColumn(cols, "pidTrack") && originalLib.PIDTrack != lib.PIDTrack) (updatesColumn(cols, "pidTrack") && originalLib.PIDTrack != lib.PIDTrack)
err = r.LibraryRepository.Put(ctx, lib, cols...) err = r.Put(ctx, lib, cols...)
if err != nil { if err != nil {
return r.mapError(err) return r.mapError(err)
} }
@ -350,7 +350,7 @@ func updatesColumn(cols []string, col string) bool {
func (r *libraryRepositoryWrapper) validateLibraryPath(ctx context.Context, library *model.Library) error { func (r *libraryRepositoryWrapper) validateLibraryPath(ctx context.Context, library *model.Library) error {
// Validate path format // Validate path format
if !filepath.IsAbs(library.Path) { if !filepath.IsAbs(library.Path) {
return fmt.Errorf("library path must be absolute") return errors.New("library path must be absolute")
} }
// Clean the path to normalize it // Clean the path to normalize it
@ -377,7 +377,7 @@ func (r *libraryRepositoryWrapper) validateLibraryPath(ctx context.Context, libr
} }
if !info.IsDir() { if !info.IsDir() {
return fmt.Errorf("resources.library.validation.pathNotDirectory") return errors.New("resources.library.validation.pathNotDirectory")
} }
return nil return nil

View file

@ -7,6 +7,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"sync" "sync"
"time"
"github.com/deluan/rest" "github.com/deluan/rest"
_ "github.com/navidrome/navidrome/adapters/gotaglib" // Register taglib extractor _ "github.com/navidrome/navidrome/adapters/gotaglib" // Register taglib extractor
@ -498,7 +499,7 @@ var _ = Describe("Library Service", func() {
err := repo.Delete(ctx, "1") err := repo.Delete(ctx, "1")
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(libraryRepo.Data).To(HaveLen(0)) Expect(libraryRepo.Data).To(BeEmpty())
}) })
It("fails when library doesn't exist", func() { It("fails when library doesn't exist", func() {
@ -657,7 +658,7 @@ var _ = Describe("Library Service", func() {
// Wait briefly for the goroutine to complete // Wait briefly for the goroutine to complete
Eventually(func() int { Eventually(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
// Verify scan was called with correct parameters // Verify scan was called with correct parameters
calls := scanner.GetScanAllCalls() calls := scanner.GetScanAllCalls()
@ -683,7 +684,7 @@ var _ = Describe("Library Service", func() {
// Wait briefly for the goroutine to complete // Wait briefly for the goroutine to complete
Eventually(func() int { Eventually(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
// Verify scan was called with correct parameters // Verify scan was called with correct parameters
calls := scanner.GetScanAllCalls() calls := scanner.GetScanAllCalls()
@ -704,7 +705,7 @@ var _ = Describe("Library Service", func() {
// Wait a bit to ensure no scan was triggered // Wait a bit to ensure no scan was triggered
Consistently(func() int { Consistently(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
It("triggers scan when updating the library PID config", func() { It("triggers scan when updating the library PID config", func() {
@ -715,7 +716,7 @@ var _ = Describe("Library Service", func() {
Eventually(func() int { Eventually(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
// A quick scan: the scanner itself rescans this library in full // A quick scan: the scanner itself rescans this library in full
Expect(scanner.GetScanAllCalls()[0].FullScan).To(BeFalse()) Expect(scanner.GetScanAllCalls()[0].FullScan).To(BeFalse())
}) })
@ -729,7 +730,7 @@ var _ = Describe("Library Service", func() {
Consistently(func() int { Consistently(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
It("waits for a running scan before triggering a new one", func() { It("waits for a running scan before triggering a new one", func() {
@ -741,12 +742,12 @@ var _ = Describe("Library Service", func() {
Consistently(func() int { Consistently(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "200ms", "20ms").Should(Equal(0)) }, 200*time.Millisecond, 20*time.Millisecond).Should(Equal(0))
scanner.SetScanning(false) scanner.SetScanning(false)
Eventually(func() int { Eventually(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "3s", "20ms").Should(Equal(1)) }, 3*time.Second, 20*time.Millisecond).Should(Equal(1))
}) })
It("does not trigger scan when library creation fails", func() { It("does not trigger scan when library creation fails", func() {
@ -759,7 +760,7 @@ var _ = Describe("Library Service", func() {
// Ensure no scan was triggered since creation failed // Ensure no scan was triggered since creation failed
Consistently(func() int { Consistently(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
It("does not trigger scan when library update fails", func() { It("does not trigger scan when library update fails", func() {
@ -776,7 +777,7 @@ var _ = Describe("Library Service", func() {
// Ensure no scan was triggered since update failed // Ensure no scan was triggered since update failed
Consistently(func() int { Consistently(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
It("triggers scan when deleting a library", func() { It("triggers scan when deleting a library", func() {
@ -792,7 +793,7 @@ var _ = Describe("Library Service", func() {
// Wait briefly for the goroutine to complete // Wait briefly for the goroutine to complete
Eventually(func() int { Eventually(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
// Verify scan was called with correct parameters // Verify scan was called with correct parameters
calls := scanner.GetScanAllCalls() calls := scanner.GetScanAllCalls()
@ -807,7 +808,7 @@ var _ = Describe("Library Service", func() {
// Ensure no scan was triggered since deletion failed // Ensure no scan was triggered since deletion failed
Consistently(func() int { Consistently(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
Context("Watcher Integration", func() { Context("Watcher Integration", func() {
@ -820,7 +821,7 @@ var _ = Describe("Library Service", func() {
// Verify watcher was started // Verify watcher was started
Eventually(func() int { Eventually(func() int {
return watcherManager.lenStarted() return watcherManager.lenStarted()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
Expect(watcherManager.StartedWatchers[0].ID).To(Equal(1)) Expect(watcherManager.StartedWatchers[0].ID).To(Equal(1))
Expect(watcherManager.StartedWatchers[0].Name).To(Equal("New Library")) Expect(watcherManager.StartedWatchers[0].Name).To(Equal("New Library"))
@ -849,7 +850,7 @@ var _ = Describe("Library Service", func() {
// Verify watcher was restarted // Verify watcher was restarted
Eventually(func() int { Eventually(func() int {
return watcherManager.lenRestarted() return watcherManager.lenRestarted()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
Expect(watcherManager.RestartedWatchers[0].ID).To(Equal(1)) Expect(watcherManager.RestartedWatchers[0].ID).To(Equal(1))
Expect(watcherManager.RestartedWatchers[0].Path).To(Equal(newTempDir)) Expect(watcherManager.RestartedWatchers[0].Path).To(Equal(newTempDir))
@ -869,7 +870,7 @@ var _ = Describe("Library Service", func() {
// Verify watcher was NOT restarted (since path didn't change) // Verify watcher was NOT restarted (since path didn't change)
Consistently(func() int { Consistently(func() int {
return watcherManager.lenRestarted() return watcherManager.lenRestarted()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
It("stops watcher when library is deleted", func() { It("stops watcher when library is deleted", func() {
@ -884,7 +885,7 @@ var _ = Describe("Library Service", func() {
// Verify watcher was stopped // Verify watcher was stopped
Eventually(func() int { Eventually(func() int {
return watcherManager.lenStopped() return watcherManager.lenStopped()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
Expect(watcherManager.StoppedWatchers[0]).To(Equal(1)) Expect(watcherManager.StoppedWatchers[0]).To(Equal(1))
}) })
@ -902,7 +903,7 @@ var _ = Describe("Library Service", func() {
// Verify watcher was NOT stopped since deletion failed // Verify watcher was NOT stopped since deletion failed
Consistently(func() int { Consistently(func() int {
return watcherManager.lenStopped() return watcherManager.lenStopped()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
}) })
}) })

View file

@ -3,7 +3,7 @@ package lyrics_test
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "errors"
"os" "os"
"path/filepath" "path/filepath"
@ -164,7 +164,7 @@ var _ = Describe("Lyrics", func() {
conf.Update(func(c *conf.Options) { c.LyricsPriority = priority }) conf.Update(func(c *conf.Options) { c.LyricsPriority = priority })
svc := lyrics.NewLyrics(nil, nil) svc := lyrics.NewLyrics(nil, nil)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(expected)) Expect(list).To(Equal(expected))
}, },
Entry("embedded > lrc > txt", "embedded,.lrc,.txt", embeddedLyrics), Entry("embedded > lrc > txt", "embedded,.lrc,.txt", embeddedLyrics),
@ -177,7 +177,7 @@ var _ = Describe("Lyrics", func() {
It("resolves source priority across duplicate media files", func() { It("resolves source priority across duplicate media files", func() {
conf.Update(func(c *conf.Options) { c.LyricsPriority = ".ttml,embedded" }) conf.Update(func(c *conf.Options) { c.LyricsPriority = ".ttml,embedded" })
embeddedJSON, err := json.Marshal(embeddedLyrics) embeddedJSON, err := json.Marshal(embeddedLyrics)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
repo := &tests.MockMediaFileRepo{} repo := &tests.MockMediaFileRepo{}
repo.SetData(model.MediaFiles{ repo.SetData(model.MediaFiles{
@ -193,7 +193,7 @@ var _ = Describe("Lyrics", func() {
svc := lyrics.NewLyrics(&tests.MockDataStore{MockedMediaFile: repo}, nil) svc := lyrics.NewLyrics(&tests.MockDataStore{MockedMediaFile: repo}, nil)
list, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up") list, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(ttmlLyrics)) Expect(list).To(Equal(ttmlLyrics))
}) })
@ -221,7 +221,7 @@ var _ = Describe("Lyrics", func() {
Path: "song.mp3", Path: "song.mp3",
}) })
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(HaveLen(1)) Expect(list).To(HaveLen(1))
Expect(list[0].Line).To(Equal([]model.Line{ Expect(list[0].Line).To(Equal([]model.Line{
{Start: new(int64(1000)), Value: "Upper suffix"}, {Start: new(int64(1000)), Value: "Upper suffix"},
@ -248,7 +248,7 @@ var _ = Describe("Lyrics", func() {
// ParseLyrics falls back to plain text for any suffix when the content // ParseLyrics falls back to plain text for any suffix when the content
// doesn't match the structured format, so the .yaml hit is non-empty and // doesn't match the structured format, so the .yaml hit is non-empty and
// shadows the lower-priority .lrc entirely. // shadows the lower-priority .lrc entirely.
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(HaveLen(1)) Expect(list).To(HaveLen(1))
Expect(list[0].Synced).To(BeFalse()) Expect(list[0].Synced).To(BeFalse())
Expect(list[0].Line).To(Equal([]model.Line{ Expect(list[0].Line).To(Equal([]model.Line{
@ -286,7 +286,7 @@ var _ = Describe("Lyrics", func() {
svc := lyrics.NewLyrics(nil, nil) svc := lyrics.NewLyrics(nil, nil)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(embeddedLyrics)) Expect(list).To(Equal(embeddedLyrics))
}) })
@ -295,7 +295,7 @@ var _ = Describe("Lyrics", func() {
svc := lyrics.NewLyrics(nil, nil) svc := lyrics.NewLyrics(nil, nil)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(BeEmpty()) Expect(list).To(BeEmpty())
}) })
}) })
@ -313,7 +313,7 @@ var _ = Describe("Lyrics", func() {
mockLoader.lyrics = unsyncedLyrics mockLoader.lyrics = unsyncedLyrics
svc := lyrics.NewLyrics(nil, mockLoader) svc := lyrics.NewLyrics(nil, mockLoader)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(unsyncedLyrics)) Expect(list).To(Equal(unsyncedLyrics))
}) })
@ -323,7 +323,7 @@ var _ = Describe("Lyrics", func() {
mockLoader.lyrics = unsyncedLyrics mockLoader.lyrics = unsyncedLyrics
svc := lyrics.NewLyrics(nil, mockLoader) svc := lyrics.NewLyrics(nil, mockLoader)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(unsyncedLyrics)) Expect(list).To(Equal(unsyncedLyrics))
}) })
@ -332,7 +332,7 @@ var _ = Describe("Lyrics", func() {
mockLoader.lyrics = unsyncedLyrics mockLoader.lyrics = unsyncedLyrics
svc := lyrics.NewLyrics(nil, mockLoader) svc := lyrics.NewLyrics(nil, mockLoader)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(embeddedLyrics)) // embedded wins Expect(list).To(Equal(embeddedLyrics)) // embedded wins
}) })
@ -341,7 +341,7 @@ var _ = Describe("Lyrics", func() {
mockLoader.notFound = true mockLoader.notFound = true
svc := lyrics.NewLyrics(nil, mockLoader) svc := lyrics.NewLyrics(nil, mockLoader)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(embeddedLyrics)) // falls through to embedded Expect(list).To(Equal(embeddedLyrics)) // falls through to embedded
}) })
@ -351,16 +351,16 @@ var _ = Describe("Lyrics", func() {
mockLoader.lyrics = unsyncedLyrics mockLoader.lyrics = unsyncedLyrics
svc := lyrics.NewLyrics(nil, mockLoader) svc := lyrics.NewLyrics(nil, mockLoader)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(unsyncedLyrics)) Expect(list).To(Equal(unsyncedLyrics))
}) })
It("should handle plugin error gracefully", func() { It("should handle plugin error gracefully", func() {
conf.Update(func(c *conf.Options) { c.LyricsPriority = "test-lyrics-plugin,embedded" }) conf.Update(func(c *conf.Options) { c.LyricsPriority = "test-lyrics-plugin,embedded" })
mockLoader.err = fmt.Errorf("plugin error") mockLoader.err = errors.New("plugin error")
svc := lyrics.NewLyrics(nil, mockLoader) svc := lyrics.NewLyrics(nil, mockLoader)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(embeddedLyrics)) // falls through to embedded Expect(list).To(Equal(embeddedLyrics)) // falls through to embedded
}) })
}) })
@ -397,7 +397,7 @@ var _ = Describe("Lyrics", func() {
}) })
It("caches a plugin error as a miss, since some plugins report no lyrics as an error", func() { It("caches a plugin error as a miss, since some plugins report no lyrics as an error", func() {
mockLoader.err = fmt.Errorf("no lyrics found from any provider") mockLoader.err = errors.New("no lyrics found from any provider")
for range 2 { for range 2 {
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())

View file

@ -22,8 +22,8 @@ var _ = Describe("sources", func() {
mf := model.MediaFile{} mf := model.MediaFile{}
lyrics, err := fromEmbedded(ctx, &mf) lyrics, err := fromEmbedded(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(0)) Expect(lyrics).To(BeEmpty())
}) })
It("should return lyrics for a media file with well-formatted lyrics", func() { It("should return lyrics for a media file with well-formatted lyrics", func() {
@ -45,7 +45,7 @@ var _ = Describe("sources", func() {
} }
lyrics, err := fromEmbedded(ctx, &mf) lyrics, err := fromEmbedded(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).ToNot(BeNil()) Expect(lyrics).ToNot(BeNil())
Expect(lyrics).To(Equal(expectedList)) Expect(lyrics).To(Equal(expectedList))
}) })
@ -54,8 +54,8 @@ var _ = Describe("sources", func() {
mf := model.MediaFile{Lyrics: "["} mf := model.MediaFile{Lyrics: "["}
lyrics, err := fromEmbedded(ctx, &mf) lyrics, err := fromEmbedded(ctx, &mf)
Expect(lyrics).To(HaveLen(0)) Expect(lyrics).To(BeEmpty())
Expect(err).ToNot(BeNil()) Expect(err).To(HaveOccurred())
}) })
}) })
@ -76,8 +76,8 @@ var _ = Describe("sources", func() {
It("should return nil for lyrics that don't exist", func() { It("should return nil for lyrics that don't exist", func() {
lyrics, err := fromExternalFile(ctx, mf("01 Invisible (RED) Edit Version.mp3"), ".lrc") lyrics, err := fromExternalFile(ctx, mf("01 Invisible (RED) Edit Version.mp3"), ".lrc")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(0)) Expect(lyrics).To(BeEmpty())
}) })
// fromExternalFile delegates format parsing to model.ParseLyrics; the // fromExternalFile delegates format parsing to model.ParseLyrics; the
@ -87,7 +87,7 @@ var _ = Describe("sources", func() {
func(name, suffix string, expectSynced bool) { func(name, suffix string, expectSynced bool) {
lyrics, err := fromExternalFile(ctx, mf(name), suffix) lyrics, err := fromExternalFile(ctx, mf(name), suffix)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).ToNot(BeEmpty()) Expect(lyrics).ToNot(BeEmpty())
Expect(lyrics[0].Line).ToNot(BeEmpty()) Expect(lyrics[0].Line).ToNot(BeEmpty())
Expect(lyrics[0].Synced).To(Equal(expectSynced)) Expect(lyrics[0].Synced).To(Equal(expectSynced))
@ -103,7 +103,7 @@ var _ = Describe("sources", func() {
It("should handle LRC files with UTF-8 BOM marker (issue #4631)", func() { It("should handle LRC files with UTF-8 BOM marker (issue #4631)", func() {
lyrics, err := fromExternalFile(ctx, mf("bom-test.mp3"), ".lrc") lyrics, err := fromExternalFile(ctx, mf("bom-test.mp3"), ".lrc")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(1)) Expect(lyrics).To(HaveLen(1))
Expect(lyrics[0].Synced).To(BeTrue(), "Lyrics with BOM marker should be recognized as synced") Expect(lyrics[0].Synced).To(BeTrue(), "Lyrics with BOM marker should be recognized as synced")
Expect(lyrics[0].Line).To(HaveLen(1)) Expect(lyrics[0].Line).To(HaveLen(1))
@ -114,7 +114,7 @@ var _ = Describe("sources", func() {
It("should handle UTF-16 LE encoded LRC files", func() { It("should handle UTF-16 LE encoded LRC files", func() {
lyrics, err := fromExternalFile(ctx, mf("bom-utf16-test.mp3"), ".lrc") lyrics, err := fromExternalFile(ctx, mf("bom-utf16-test.mp3"), ".lrc")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(1)) Expect(lyrics).To(HaveLen(1))
Expect(lyrics[0].Synced).To(BeTrue(), "UTF-16 encoded lyrics should be recognized as synced") Expect(lyrics[0].Synced).To(BeTrue(), "UTF-16 encoded lyrics should be recognized as synced")
Expect(lyrics[0].Line).To(HaveLen(2)) Expect(lyrics[0].Line).To(HaveLen(2))
@ -127,7 +127,7 @@ var _ = Describe("sources", func() {
It("should handle TTML files with UTF-8 BOM marker", func() { It("should handle TTML files with UTF-8 BOM marker", func() {
lyrics, err := fromExternalFile(ctx, mf("bom-test.mp3"), ".ttml") lyrics, err := fromExternalFile(ctx, mf("bom-test.mp3"), ".ttml")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(1)) Expect(lyrics).To(HaveLen(1))
Expect(lyrics[0].Kind).To(Equal("main")) Expect(lyrics[0].Kind).To(Equal("main"))
Expect(lyrics[0].Synced).To(BeTrue()) Expect(lyrics[0].Synced).To(BeTrue())
@ -139,7 +139,7 @@ var _ = Describe("sources", func() {
It("should handle UTF-16 BE encoded TTML files", func() { It("should handle UTF-16 BE encoded TTML files", func() {
lyrics, err := fromExternalFile(ctx, mf("bom-utf16-test.mp3"), ".ttml") lyrics, err := fromExternalFile(ctx, mf("bom-utf16-test.mp3"), ".ttml")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(1)) Expect(lyrics).To(HaveLen(1))
Expect(lyrics[0].Kind).To(Equal("main")) Expect(lyrics[0].Kind).To(Equal("main"))
Expect(lyrics[0].Synced).To(BeTrue()) Expect(lyrics[0].Synced).To(BeTrue())

View file

@ -310,9 +310,9 @@ func (s *maintenanceService) refreshStatsAsync(ctx context.Context, affectedAlbu
}) })
} }
// Wait waits for all background goroutines to complete. // wait waits for all background goroutines to complete.
// WARNING: This method is ONLY for testing. Never call this in production code. // WARNING: This method is ONLY for testing. Never call this in production code.
// Calling Wait() in production will block until ALL background operations complete // Calling wait() in production will block until ALL background operations complete
// and may cause race conditions with new operations starting. // and may cause race conditions with new operations starting.
func (s *maintenanceService) wait() { func (s *maintenanceService) wait() {
s.wg.Wait() s.wg.Wait()

View file

@ -395,7 +395,7 @@ var _ = Describe("Maintenance", func() {
It("preserves the target's participants on the remapped track", func() { It("preserves the target's participants on the remapped track", func() {
participant := model.Participant{ participant := model.Participant{
Artist: model.Artist{ID: "a1", Name: "Artist", OrderArtistName: "artist", MbzArtistID: "mbz-artist"}, ID: "a1", Name: "Artist", OrderArtistName: "artist", MbzArtistID: "mbz-artist",
} }
mfRepo.SetData(model.MediaFiles{ mfRepo.SetData(model.MediaFiles{
{ID: "m1", AlbumID: "album1", Missing: true}, {ID: "m1", AlbumID: "album1", Missing: true},

View file

@ -353,10 +353,10 @@ var _ = Describe("Matcher", func() {
ID: "comp", Title: "Qmart", Artist: "Björk", ID: "comp", Title: "Qmart", Artist: "Björk",
Participants: model.Participants{ Participants: model.Participants{
model.RoleArtist: model.ParticipantList{ model.RoleArtist: model.ParticipantList{
{Artist: model.Artist{ID: "a-bjork", Name: "Björk", OrderArtistName: "bjork"}}, {ID: "a-bjork", Name: "Björk", OrderArtistName: "bjork"},
}, },
model.RoleAlbumArtist: model.ParticipantList{ model.RoleAlbumArtist: model.ParticipantList{
{Artist: model.Artist{ID: "a-808", Name: "808 State", OrderArtistName: "808 state"}}, {ID: "a-808", Name: "808 State", OrderArtistName: "808 state"},
}, },
}, },
} }
@ -545,7 +545,7 @@ var _ = Describe("Matcher", func() {
// Shares only Drake (overlap 1) but starred. // Shares only Drake (overlap 1) but starred.
starredOne := model.MediaFile{ starredOne := model.MediaFile{
ID: "starred-one", Title: "Collab Hit", ID: "starred-one", Title: "Collab Hit",
Annotations: model.Annotations{Starred: true}, Starred: true,
Participants: artistParticipants(model.Artist{ID: "id-drake", Name: "Drake", OrderArtistName: "drake"}), Participants: artistParticipants(model.Artist{ID: "id-drake", Name: "Drake", OrderArtistName: "drake"}),
} }
// Shares both (overlap 2), not starred. // Shares both (overlap 2), not starred.
@ -958,7 +958,7 @@ var _ = Describe("Matcher", func() {
} }
starredTrack := model.MediaFile{ starredTrack := model.MediaFile{
ID: "starred", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Singles", ID: "starred", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Singles",
Annotations: model.Annotations{Starred: true}, Starred: true,
Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}), Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}),
} }
allowTitlePhase(model.MediaFiles{albumMatch, starredTrack}) allowTitlePhase(model.MediaFiles{albumMatch, starredTrack})
@ -979,7 +979,7 @@ var _ = Describe("Matcher", func() {
} }
ratedTrack := model.MediaFile{ ratedTrack := model.MediaFile{
ID: "rated", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Singles", ID: "rated", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Singles",
Annotations: model.Annotations{Rating: 4}, Rating: 4,
Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}), Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}),
} }
allowTitlePhase(model.MediaFiles{albumMatch, ratedTrack}) allowTitlePhase(model.MediaFiles{albumMatch, ratedTrack})
@ -1001,7 +1001,7 @@ var _ = Describe("Matcher", func() {
} }
starred := model.MediaFile{ starred := model.MediaFile{
ID: "starred", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Violator", ID: "starred", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Violator",
Annotations: model.Annotations{Starred: true}, Starred: true,
Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}), Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}),
} }
allowTitlePhase(model.MediaFiles{plain, starred}) allowTitlePhase(model.MediaFiles{plain, starred})

View file

@ -103,7 +103,7 @@ func (c *insightsCollector) sendInsights(ctx context.Context) {
return return
} }
body := bytes.NewReader(data) body := bytes.NewReader(data)
req, err := http.NewRequestWithContext(ctx, "POST", consts.InsightsEndpoint, body) req, err := http.NewRequestWithContext(ctx, http.MethodPost, consts.InsightsEndpoint, body)
if err != nil { if err != nil {
log.Trace(ctx, "Could not create Insights request", err) log.Trace(ctx, "Could not create Insights request", err)
return return

View file

@ -24,11 +24,11 @@ func getOSVersion() (string, string) {
version := "" version := ""
distro := "" distro := ""
for _, line := range lines { for _, line := range lines {
if strings.HasPrefix(line, "VERSION_ID=") { if v, ok := strings.CutPrefix(line, "VERSION_ID="); ok {
version = strings.ReplaceAll(strings.TrimPrefix(line, "VERSION_ID="), "\"", "") version = strings.ReplaceAll(v, "\"", "")
} }
if strings.HasPrefix(line, "ID=") { if v, ok := strings.CutPrefix(line, "ID="); ok {
distro = strings.ReplaceAll(strings.TrimPrefix(line, "ID="), "\"", "") distro = strings.ReplaceAll(v, "\"", "")
} }
} }
return version, distro return version, distro

View file

@ -117,7 +117,7 @@ type prometheusMetrics struct {
pluginRequestDuration *prometheus.SummaryVec pluginRequestDuration *prometheus.SummaryVec
} }
// Prometheus' metrics requires initialization. But not more than once // getPrometheusMetrics initializes Prometheus' metrics, which must not happen more than once
var getPrometheusMetrics = sync.OnceValue(func() *prometheusMetrics { var getPrometheusMetrics = sync.OnceValue(func() *prometheusMetrics {
quartilesToEstimate := map[float64]float64{0.5: 0.05, 0.75: 0.025, 0.9: 0.01, 0.99: 0.001} quartilesToEstimate := map[float64]float64{0.5: 0.05, 0.75: 0.025, 0.9: 0.01, 0.99: 0.001}

View file

@ -4,6 +4,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"strconv"
"sync" "sync"
"github.com/navidrome/navidrome/core/playback/mpv" "github.com/navidrome/navidrome/core/playback/mpv"
@ -222,7 +223,7 @@ func (pd *playbackDevice) Remove(ctx context.Context, index int) (DeviceStatus,
if index > -1 && index < pd.PlaybackQueue.Size() { if index > -1 && index < pd.PlaybackQueue.Size() {
pd.PlaybackQueue.Remove(index) pd.PlaybackQueue.Remove(index)
} else { } else {
log.Error(ctx, "Index to remove out of range: "+fmt.Sprint(index)) log.Error(ctx, "Index to remove out of range: "+strconv.Itoa(index))
} }
return pd.getStatus(), nil return pd.getStatus(), nil
} }

View file

@ -17,7 +17,7 @@ import (
func start(ctx context.Context, args []string) (Executor, error) { func start(ctx context.Context, args []string) (Executor, error) {
if len(args) == 0 { if len(args) == 0 {
return Executor{}, fmt.Errorf("no command arguments provided") return Executor{}, errors.New("no command arguments provided")
} }
log.Debug("Executing mpv command", "cmd", args) log.Debug("Executing mpv command", "cmd", args)
j := Executor{args: args} j := Executor{args: args}
@ -34,7 +34,7 @@ func (j *Executor) Cancel() error {
if j.cmd != nil { if j.cmd != nil {
return j.cmd.Cancel() return j.cmd.Cancel()
} }
return fmt.Errorf("there is non command to cancel") return errors.New("there is non command to cancel")
} }
type Executor struct { type Executor struct {
@ -72,7 +72,7 @@ func (j *Executor) wait() {
_ = j.out.Close() _ = j.out.Close()
} }
// Path will always be an absolute path // createMPVCommand expects filename to always be an absolute path
func createMPVCommand(deviceName string, filename string, socketName string) []string { func createMPVCommand(deviceName string, filename string, socketName string) []string {
// Parse the template structure using shell parsing to handle quoted arguments // 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)
@ -102,7 +102,7 @@ func createMPVCommand(deviceName string, filename string, socketName string) []s
return templateArgs return templateArgs
} }
// This is a 1:1 copy of the stuff in ffmpeg.go, need to be unified. // mpvCommand is a 1:1 copy of the stuff in ffmpeg.go, need to be unified.
func mpvCommand() (string, error) { func mpvCommand() (string, error) {
mpvOnce.Do(func() { mpvOnce.Do(func() {
if conf.Server().MPVPath != "" { if conf.Server().MPVPath != "" {

View file

@ -7,6 +7,7 @@ package mpv
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"os" "os"
"time" "time"
@ -36,7 +37,7 @@ func NewTrack(ctx context.Context, playbackDoneChannel chan bool, deviceName str
args := createMPVCommand(deviceName, mf.AbsolutePath(), tmpSocketName) args := createMPVCommand(deviceName, mf.AbsolutePath(), tmpSocketName)
if len(args) == 0 { if len(args) == 0 {
return nil, fmt.Errorf("no mpv command arguments provided") return nil, errors.New("no mpv command arguments provided")
} }
exe, err := start(ctx, args) exe, err := start(ctx, args)
if err != nil { if err != nil {
@ -76,7 +77,7 @@ func (t *MpvTrack) String() string {
return fmt.Sprintf("Name: %s, Socket: %s", t.MediaFile.Path, t.IPCSocketName) return fmt.Sprintf("Name: %s, Socket: %s", t.MediaFile.Path, t.IPCSocketName)
} }
// Used to control the playback volume. A float value between 0.0 and 1.0. // SetVolume controls the playback volume. A float value between 0.0 and 1.0.
func (t *MpvTrack) SetVolume(value float32) { func (t *MpvTrack) SetVolume(value float32) {
// mpv's volume as described in the --volume parameter: // mpv's volume as described in the --volume parameter:
// Set the startup volume. 0 means silence, 100 means no volume reduction or amplification. // Set the startup volume. 0 means silence, 100 means no volume reduction or amplification.

View file

@ -7,6 +7,7 @@ package playback
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
@ -106,7 +107,7 @@ func (ps *playbackServer) getDefaultDevice() (*playbackDevice, error) {
return &ps.playbackDevices[idx], nil return &ps.playbackDevices[idx], nil
} }
} }
return nil, fmt.Errorf("no default device found") return nil, errors.New("no default device found")
} }
// GetMediaFile retrieves the MediaFile given by the id parameter // GetMediaFile retrieves the MediaFile given by the id parameter

View file

@ -3,6 +3,7 @@ package playback
import ( import (
"fmt" "fmt"
"math/rand" "math/rand"
"strconv"
"strings" "strings"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
@ -24,12 +25,12 @@ func NewQueue() *Queue {
func (pd *Queue) String() string { func (pd *Queue) String() string {
var filenames strings.Builder var filenames strings.Builder
for idx, item := range pd.Items { for idx, item := range pd.Items {
filenames.WriteString(fmt.Sprint(idx) + ":" + item.Path + " ") filenames.WriteString(strconv.Itoa(idx) + ":" + item.Path + " ")
} }
return fmt.Sprintf("#Items: %d, idx: %d, files: %s", len(pd.Items), pd.Index, filenames.String()) return fmt.Sprintf("#Items: %d, idx: %d, files: %s", len(pd.Items), pd.Index, filenames.String())
} }
// returns the current mediafile or nil // Current returns the current mediafile or nil
func (pd *Queue) Current() *model.MediaFile { func (pd *Queue) Current() *model.MediaFile {
if pd.Index == -1 { if pd.Index == -1 {
return nil return nil
@ -42,7 +43,7 @@ func (pd *Queue) Current() *model.MediaFile {
return &pd.Items[pd.Index] return &pd.Items[pd.Index]
} }
// returns the whole queue // Get returns the whole queue
func (pd *Queue) Get() model.MediaFiles { func (pd *Queue) Get() model.MediaFiles {
return pd.Items return pd.Items
} }
@ -55,13 +56,13 @@ func (pd *Queue) IsEmpty() bool {
return len(pd.Items) < 1 return len(pd.Items) < 1
} }
// set is similar to a clear followed by a add, but will not change the currently playing track. // Set is similar to a clear followed by an add, but will not change the currently playing track.
func (pd *Queue) Set(items model.MediaFiles) { func (pd *Queue) Set(items model.MediaFiles) {
pd.Clear() pd.Clear()
pd.Items = append(pd.Items, items...) pd.Items = append(pd.Items, items...)
} }
// adding mediafiles to the queue // Add appends mediafiles to the queue
func (pd *Queue) Add(items model.MediaFiles) { func (pd *Queue) Add(items model.MediaFiles) {
pd.Items = append(pd.Items, items...) pd.Items = append(pd.Items, items...)
if pd.Index == -1 && len(pd.Items) > 0 { if pd.Index == -1 && len(pd.Items) > 0 {
@ -69,13 +70,13 @@ func (pd *Queue) Add(items model.MediaFiles) {
} }
} }
// empties whole queue // Clear empties the whole queue
func (pd *Queue) Clear() { func (pd *Queue) Clear() {
pd.Index = -1 pd.Index = -1
pd.Items = nil pd.Items = nil
} }
// idx Zero-based index of the song to skip to or remove. // Remove removes the song at idx, a zero-based index.
func (pd *Queue) Remove(idx int) { func (pd *Queue) Remove(idx int) {
current := pd.Current() current := pd.Current()
backupID := "" backupID := ""
@ -119,18 +120,18 @@ func (pd *Queue) getMediaFileIndexByID(id string) (int, error) {
return -1, fmt.Errorf("ID not found in playlist: %s", id) return -1, fmt.Errorf("ID not found in playlist: %s", id)
} }
// Sets the index to a new, valid value inside the Items. Values lower than zero are going to be zero, // SetIndex sets the index to a new, valid value inside the Items. Values lower than zero are going to be
// values above will be limited by number of items. // zero, values above will be limited by number of items.
func (pd *Queue) SetIndex(idx int) { func (pd *Queue) SetIndex(idx int) {
pd.Index = max(0, min(idx, len(pd.Items)-1)) pd.Index = max(0, min(idx, len(pd.Items)-1))
} }
// Are we at the last track? // IsAtLastElement reports whether we are at the last track.
func (pd *Queue) IsAtLastElement() bool { func (pd *Queue) IsAtLastElement() bool {
return (pd.Index + 1) >= len(pd.Items) return (pd.Index + 1) >= len(pd.Items)
} }
// Goto next index // IncreaseIndex moves to the next index, unless at the last track.
func (pd *Queue) IncreaseIndex() { func (pd *Queue) IncreaseIndex() {
if !pd.IsAtLastElement() { if !pd.IsAtLastElement() {
pd.SetIndex(pd.Index + 1) pd.SetIndex(pd.Index + 1)

View file

@ -61,7 +61,7 @@ func (s *playlists) ImportFile(ctx context.Context, absolutePath string, sync bo
hasher := xxh3.New() hasher := xxh3.New()
reader := io.TeeReader(ioutils.UTF8Reader(file), hasher) reader := io.TeeReader(ioutils.UTF8Reader(file), hasher)
if err := s.parseM3U(ctx, pls, nil, reader); err != nil { if err := s.parseM3U(ctx, pls, nil, reader, noEntryLimit); err != nil {
return nil, err return nil, err
} }
pls.ImportedHash = fingerprint(hasher) pls.ImportedHash = fingerprint(hasher)
@ -71,7 +71,7 @@ func (s *playlists) ImportFile(ctx context.Context, absolutePath string, sync bo
return pls, nil return pls, nil
} }
var errNotInLibrary = fmt.Errorf("path not in any library") var errNotInLibrary = errors.New("path not in any library")
func (s *playlists) resolveFolder(ctx context.Context, dir string) (*model.Folder, error) { func (s *playlists) resolveFolder(ctx context.Context, dir string) (*model.Folder, error) {
libs, err := s.ds.Library().GetAll(ctx) libs, err := s.ds.Library().GetAll(ctx)
@ -110,14 +110,48 @@ func (s *playlists) importFromFolder(ctx context.Context, folder *model.Folder,
return pls, err return pls, err
} }
// noEntryLimit is passed to parseM3U for on-disk playlists.
const noEntryLimit = 0
// ErrTooManyEntries is returned by ImportM3U when the playlist has more than MaxTracksPerRequest entries.
var ErrTooManyEntries = errors.New("playlist has too many entries")
// importM3USlot runs one upload import at a time, so concurrent uploads cannot stack their memory use.
var importM3USlot = make(chan struct{}, 1)
// errReader keeps the first read error, which the line scanner in parseM3U drops.
type errReader struct {
r io.Reader
err error
}
func (e *errReader) Read(p []byte) (int, error) {
n, err := e.r.Read(p)
if err != nil && !errors.Is(err, io.EOF) && e.err == nil {
e.err = err
}
return n, err
}
func (s *playlists) ImportM3U(ctx context.Context, reader io.Reader) (*model.Playlist, error) { func (s *playlists) ImportM3U(ctx context.Context, reader io.Reader) (*model.Playlist, error) {
select {
case importM3USlot <- struct{}{}:
defer func() { <-importM3USlot }()
case <-ctx.Done():
return nil, ctx.Err()
}
owner, _ := request.UserFrom(ctx) owner, _ := request.UserFrom(ctx)
pls := &model.Playlist{ pls := &model.Playlist{
OwnerID: owner.ID, OwnerID: owner.ID,
Public: false, Public: false,
Sync: false, Sync: false,
} }
err := s.parseM3U(ctx, pls, nil, reader) body := &errReader{r: reader}
// Uploads only: on-disk playlists in the scanner can legitimately be larger.
err := s.parseM3U(ctx, pls, nil, body, MaxTracksPerRequest())
if err == nil {
err = body.err
}
if err != nil { if err != nil {
log.Error(ctx, "Error parsing playlist", err) log.Error(ctx, "Error parsing playlist", err)
return nil, err return nil, err
@ -150,7 +184,7 @@ func (s *playlists) parsePlaylist(ctx context.Context, playlistFile string, fold
case ".nsp": case ".nsp":
err = s.parseNSP(ctx, pls, reader) err = s.parseNSP(ctx, pls, reader)
default: default:
err = s.parseM3U(ctx, pls, folder, reader) err = s.parseM3U(ctx, pls, folder, reader, noEntryLimit)
} }
if err != nil { if err != nil {
return pls, err return pls, err

View file

@ -2,11 +2,14 @@ package playlists_test
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"io"
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
"strings" "strings"
"testing/iotest"
"time" "time"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
@ -995,6 +998,81 @@ var _ = Describe("Playlists - Import", func() {
Expect(pls.Tracks[2].Path).To(Equal("album2/test2.mp3")) Expect(pls.Tracks[2].Path).To(Equal("album2/test2.mp3"))
}) })
Describe("entry limit", func() {
repeat := func(n int) string {
return strings.Repeat("/music/tests/test.mp3\n", n)
}
BeforeEach(func() {
repo.data = []string{"tests/test.mp3"}
conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 3 })
})
It("imports a playlist with exactly DevMaxPlaylistTracksPerRequest entries, duplicates included", func() {
pls, err := ps.ImportM3U(ctx, strings.NewReader(repeat(3)))
Expect(err).ToNot(HaveOccurred())
Expect(pls.Tracks).To(HaveLen(3))
})
It("rejects a playlist over the limit without saving it", func() {
_, err := ps.ImportM3U(ctx, strings.NewReader(repeat(4)))
Expect(err).To(MatchError(playlists.ErrTooManyEntries))
Expect(mockPlsRepo.Last).To(BeNil())
})
It("imports any number of entries when the limit is 0", func() {
conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 0 })
pls, err := ps.ImportM3U(ctx, strings.NewReader(repeat(4)))
Expect(err).ToNot(HaveOccurred())
Expect(pls.Tracks).To(HaveLen(4))
})
It("does not cap playlists imported from disk", func() {
tmpDir := GinkgoT().TempDir()
libDir := filepath.Join(tmpDir, "music")
Expect(os.Mkdir(libDir, 0755)).To(Succeed())
mockLibRepo.SetData([]model.Library{{ID: 1, Path: libDir}})
plsFile := filepath.Join(tmpDir, "big.m3u")
content := strings.Repeat(libDir+"/tests/test.mp3\n", 4)
Expect(os.WriteFile(plsFile, []byte(content), 0600)).To(Succeed())
pls, err := ps.ImportFile(ctx, plsFile, false)
Expect(err).ToNot(HaveOccurred())
Expect(pls.Tracks).To(HaveLen(4))
})
})
It("makes a second upload wait for the running one, without reading its body", func() {
repo.data = []string{"tests/test.mp3"}
pr, pw := io.Pipe()
firstDone := make(chan error, 1)
go func() {
_, err := ps.ImportM3U(ctx, pr)
firstDone <- err
}()
_, err := pw.Write([]byte("/music/tests/test.mp3\n"))
Expect(err).ToNot(HaveOccurred())
waiting, cancel := context.WithCancel(ctx)
cancel()
second := &readRecorder{}
_, err = ps.ImportM3U(waiting, second)
Expect(err).To(MatchError(context.Canceled))
Expect(second.read).To(BeFalse())
Expect(pw.Close()).To(Succeed())
Eventually(firstDone).Should(Receive(BeNil()))
})
It("fails on a read error instead of saving a truncated playlist", func() {
repo.data = []string{"tests/test.mp3"}
readErr := errors.New("body too large")
body := io.MultiReader(strings.NewReader("/music/tests/test.mp3\n"), iotest.ErrReader(readErr))
_, err := ps.ImportM3U(ctx, body)
Expect(err).To(MatchError(readErr))
Expect(mockPlsRepo.Last).To(BeNil())
})
It("is case-insensitive when comparing paths", func() { It("is case-insensitive when comparing paths", func() {
repo.data = []string{ repo.data = []string{
"abc/tEsT1.Mp3", "abc/tEsT1.Mp3",
@ -1254,3 +1332,10 @@ func (m *mockFolderRepoForImport) GetByPath(_ context.Context, _ model.Library,
func hashOf(content string) string { func hashOf(content string) string {
return id.Encode(xxh3.Hash128([]byte(content)).Bytes()) return id.Encode(xxh3.Hash128([]byte(content)).Bytes())
} }
type readRecorder struct{ read bool }
func (r *readRecorder) Read([]byte) (int, error) {
r.read = true
return 0, io.EOF
}

View file

@ -2,6 +2,7 @@ package playlists
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"net/url" "net/url"
@ -17,13 +18,15 @@ import (
"golang.org/x/text/unicode/norm" "golang.org/x/text/unicode/norm"
) )
func (s *playlists) parseM3U(ctx context.Context, pls *model.Playlist, folder *model.Folder, reader io.Reader) error { // parseM3U fails with ErrTooManyEntries if maxEntries > 0 and the playlist has more audio entries.
func (s *playlists) parseM3U(ctx context.Context, pls *model.Playlist, folder *model.Folder, reader io.Reader, maxEntries int) error {
mediaFileRepository := s.ds.MediaFile() mediaFileRepository := s.ds.MediaFile()
resolver, err := newPathResolver(ctx, s.ds) resolver, err := newPathResolver(ctx, s.ds)
if err != nil { if err != nil {
return err return err
} }
var mfs model.MediaFiles var mfs model.MediaFiles
entries := 0
// Chunked so a huge playlist is not held in memory at once. Each line yields up to // Chunked so a huge playlist is not held in memory at once. Each line yields up to
// 4 lookup candidates (NFC/NFD × raw/lowercase), far below SQLite's 32766 variables. // 4 lookup candidates (NFC/NFD × raw/lowercase), far below SQLite's 32766 variables.
for lines := range slice.CollectChunks(slice.LinesFrom(reader), 100) { for lines := range slice.CollectChunks(slice.LinesFrom(reader), 100) {
@ -52,6 +55,10 @@ func (s *playlists) parseM3U(ctx context.Context, pls *model.Playlist, folder *m
} }
filteredLines = append(filteredLines, line) filteredLines = append(filteredLines, line)
} }
entries += len(filteredLines)
if maxEntries > 0 && entries > maxEntries {
return fmt.Errorf("%w (limit is %d)", ErrTooManyEntries, maxEntries)
}
resolvedPaths, err := resolver.resolvePaths(ctx, folder, filteredLines) resolvedPaths, err := resolver.resolvePaths(ctx, folder, filteredLines)
if err != nil { if err != nil {
log.Warn(ctx, "Error resolving paths in playlist", "playlist", pls.Name, err) log.Warn(ctx, "Error resolving paths in playlist", "playlist", pls.Name, err)
@ -144,7 +151,7 @@ type pathResolution struct {
// Format: "libraryID:relativePath" with forward slashes for path separators. // Format: "libraryID:relativePath" with forward slashes for path separators.
func (r pathResolution) ToQualifiedString() (string, error) { func (r pathResolution) ToQualifiedString() (string, error) {
if !r.valid { if !r.valid {
return "", fmt.Errorf("invalid path resolution") return "", errors.New("invalid path resolution")
} }
relativePath, err := filepath.Rel(r.libraryPath, r.absolutePath) relativePath, err := filepath.Rel(r.libraryPath, r.absolutePath)
if err != nil { if err != nil {

View file

@ -5,9 +5,9 @@ import (
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
"strconv"
"strings" "strings"
"github.com/Masterminds/squirrel"
"github.com/bmatcuk/doublestar/v4" "github.com/bmatcuk/doublestar/v4"
"github.com/deluan/rest" "github.com/deluan/rest"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
@ -17,6 +17,18 @@ import (
"github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/model/request"
) )
// MaxTracksPerRequest is how many tracks one API request may add or set; 0 means no limit.
// Native album, artist and disc ids are not counted: their expansion is bounded by the library size.
func MaxTracksPerRequest() int {
return max(conf.Server().DevMaxPlaylistTracksPerRequest, 0)
}
// TooManyTracks reports whether n tracks exceed MaxTracksPerRequest.
func TooManyTracks(n int) bool {
limit := MaxTracksPerRequest()
return limit > 0 && n > limit
}
type Playlists interface { type Playlists interface {
// Reads // Reads
GetAll(ctx context.Context, options ...model.QueryOptions) (model.Playlists, error) GetAll(ctx context.Context, options ...model.QueryOptions) (model.Playlists, error)
@ -190,15 +202,22 @@ func (s *playlists) Update(ctx context.Context, playlistID string,
if len(idxToRemove) > 0 { if len(idxToRemove) > 0 {
tracksRepo := repo.Tracks(ctx, playlistID, false) tracksRepo := repo.Tracks(ctx, playlistID, false)
// Convert 0-based indices to 1-based position IDs and delete them directly, // Indexes refer to GetWithTracks' list, which hides missing and inaccessible-library tracks.
// avoiding the need to load all tracks into memory. visible, err := tracksRepo.GetPositionIDs(ctx, model.QueryOptions{Sort: "id", Filters: squirrel.Eq{"missing": false}})
positions := make([]string, len(idxToRemove)) if err != nil {
for i, idx := range idxToRemove { return err
positions[i] = strconv.Itoa(idx + 1)
} }
positions := make([]string, 0, len(idxToRemove))
for _, idx := range idxToRemove {
if idx >= 0 && idx < len(visible) {
positions = append(positions, visible[idx])
}
}
if len(positions) > 0 {
if err := tracksRepo.Delete(ctx, positions...); err != nil { if err := tracksRepo.Delete(ctx, positions...); err != nil {
return err return err
} }
}
if len(idsToAdd) > 0 { if len(idsToAdd) > 0 {
if _, err := tracksRepo.Add(ctx, idsToAdd); err != nil { if _, err := tracksRepo.Add(ctx, idsToAdd); err != nil {
return err return err

View file

@ -19,7 +19,7 @@ import (
const timeout = 10 * time.Minute const timeout = 10 * time.Minute
// Initiate is unauthenticated, so the number of live requests must be bounded. // maxPending bounds the number of live requests, because Initiate is unauthenticated.
const maxPending = 1000 const maxPending = 1000
var ( var (
@ -100,7 +100,7 @@ func (qc *quickConnect) Initiate(device Device) (Request, error) {
App: strings.Clone(device.App), AppVersion: strings.Clone(device.AppVersion)} App: strings.Clone(device.App), AppVersion: strings.Clone(device.AppVersion)}
now := time.Now() now := time.Now()
e := &entry{ e := &entry{
Request: Request{Device: device, Secret: newSecret(), Code: qc.newCode(), DateAdded: now}, Device: device, Secret: newSecret(), Code: qc.newCode(), DateAdded: now,
expiresAt: now.Add(timeout), expiresAt: now.Add(timeout),
} }
qc.bySecret[e.Secret] = e qc.bySecret[e.Secret] = e
@ -197,7 +197,7 @@ func newSecret() string {
return hex.EncodeToString(b) return hex.EncodeToString(b)
} }
// Users often type the code in groups ("123 456"). // normalizeCode removes whitespace: users often type the code in groups ("123 456").
func normalizeCode(code string) string { func normalizeCode(code string) string {
return strings.Join(strings.Fields(code), "") return strings.Join(strings.Fields(code), "")
} }

View file

@ -184,7 +184,7 @@ func TestBufferedScrobblerBackoffWindow(t *testing.T) {
defer bs.Stop() defer bs.Stop()
// First enqueue: one immediate attempt, then a 5s window opens. // First enqueue: one immediate attempt, then a 5s window opens.
_ = bs.Scrobble(t.Context(), "user1", Scrobble{MediaFile: model.MediaFile{ID: "1"}, TimeStamp: time.Now()}) _ = bs.Scrobble(t.Context(), "user1", Scrobble{ID: "1", TimeStamp: time.Now()})
synctest.Wait() synctest.Wait()
if got := scr.ScrobbleAttempts(); got != 1 { if got := scr.ScrobbleAttempts(); got != 1 {
t.Fatalf("expected 1 attempt after first enqueue, got %d", got) t.Fatalf("expected 1 attempt after first enqueue, got %d", got)
@ -192,7 +192,7 @@ func TestBufferedScrobblerBackoffWindow(t *testing.T) {
// A wake inside the window must NOT trigger an early attempt. // A wake inside the window must NOT trigger an early attempt.
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
_ = bs.Scrobble(t.Context(), "user1", Scrobble{MediaFile: model.MediaFile{ID: "2"}, TimeStamp: time.Now()}) _ = bs.Scrobble(t.Context(), "user1", Scrobble{ID: "2", TimeStamp: time.Now()})
synctest.Wait() synctest.Wait()
if got := scr.ScrobbleAttempts(); got != 1 { if got := scr.ScrobbleAttempts(); got != 1 {
t.Fatalf("wake during backoff drained early: %d attempts", got) t.Fatalf("wake during backoff drained early: %d attempts", got)
@ -218,7 +218,7 @@ func TestBufferedScrobblerHonorsServerDelay(t *testing.T) {
bs := newBufferedScrobbler(ds, scr, "test") bs := newBufferedScrobbler(ds, scr, "test")
defer bs.Stop() defer bs.Stop()
_ = bs.Scrobble(t.Context(), "user1", Scrobble{MediaFile: model.MediaFile{ID: "1"}, TimeStamp: time.Now()}) _ = bs.Scrobble(t.Context(), "user1", Scrobble{ID: "1", TimeStamp: time.Now()})
synctest.Wait() synctest.Wait()
if got := scr.ScrobbleAttempts(); got != 1 { if got := scr.ScrobbleAttempts(); got != 1 {
t.Fatalf("expected 1 attempt, got %d", got) t.Fatalf("expected 1 attempt, got %d", got)

View file

@ -532,7 +532,7 @@ func (p *playTracker) incPlay(ctx context.Context, track *model.MediaFile, times
}) })
} }
// Take this verdict before incPlay mutates what a filter reads, and independently of // isFilteredOut must take its verdict before incPlay mutates what a filter reads, and independently of
// which scrobblers are active: it can be stored on a session and dispatched much later. // which scrobblers are active: it can be stored on a session and dispatched much later.
// Any parse or query failure fails open, because filtering must not break scrobbling. // Any parse or query failure fails open, because filtering must not break scrobbling.
func (p *playTracker) isFilteredOut(ctx context.Context, t *model.MediaFile) bool { func (p *playTracker) isFilteredOut(ctx context.Context, t *model.MediaFile) bool {

View file

@ -384,7 +384,7 @@ var _ = Describe("PlayTracker", func() {
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
mockDS := ds.(*tests.MockDataStore) mockDS := ds.(*tests.MockDataStore)
mockScrobble := mockDS.Scrobble().(*tests.MockScrobbleRepo) mockScrobble := mockDS.Scrobble().(*tests.MockScrobbleRepo)
Expect(mockScrobble.RecordedScrobbles).To(HaveLen(0)) Expect(mockScrobble.RecordedScrobbles).To(BeEmpty())
}) })
}) })
}) })
@ -1563,9 +1563,9 @@ func (f *fakeScrobbler) PlaybackReport(ctx context.Context, info PlaybackSession
} }
func _p(id, name string, sortName ...string) model.Participant { func _p(id, name string, sortName ...string) model.Participant {
p := model.Participant{Artist: model.Artist{ID: id, Name: name}} p := model.Participant{ID: id, Name: name}
if len(sortName) > 0 { if len(sortName) > 0 {
p.Artist.SortArtistName = sortName[0] p.SortArtistName = sortName[0]
} }
return p return p
} }

View file

@ -12,7 +12,7 @@ import (
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/model/request"
. "github.com/navidrome/navidrome/utils/gg" "github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/nanoid" "github.com/navidrome/navidrome/utils/nanoid"
"github.com/navidrome/navidrome/utils/slice" "github.com/navidrome/navidrome/utils/slice"
"github.com/navidrome/navidrome/utils/str" "github.com/navidrome/navidrome/utils/str"
@ -41,7 +41,7 @@ func (s *shareService) Load(ctx context.Context, id string) (*model.Share, error
if err != nil { if err != nil {
return nil, err return nil, err
} }
expiresAt := V(share.ExpiresAt) expiresAt := gg.V(share.ExpiresAt)
if !expiresAt.IsZero() && expiresAt.Before(time.Now()) { if !expiresAt.IsZero() && expiresAt.Before(time.Now()) {
return nil, model.ErrExpired return nil, model.ErrExpired
} }
@ -91,7 +91,7 @@ func (r *shareRepositoryWrapper) Save(ctx context.Context, s *model.Share) (stri
return "", err return "", err
} }
s.ID = id s.ID = id
if V(s.ExpiresAt).IsZero() { if gg.V(s.ExpiresAt).IsZero() {
s.ExpiresAt = new(time.Now().Add(conf.Server().DefaultShareExpiration)) s.ExpiresAt = new(time.Now().Add(conf.Server().DefaultShareExpiration))
} }
@ -121,7 +121,7 @@ var shareableKinds = []model.Kind{model.KindArtistArtwork, model.KindAlbumArtwor
// ride along behind a valid first one, and requires all IDs to be of the same kind. // ride along behind a valid first one, and requires all IDs to be of the same kind.
func (r *shareRepositoryWrapper) resourceType(ctx context.Context, resourceIDs string) (string, error) { func (r *shareRepositoryWrapper) resourceType(ctx context.Context, resourceIDs string) (string, error) {
resourceType := "" resourceType := ""
for _, id := range strings.Split(resourceIDs, ",") { for id := range strings.SplitSeq(resourceIDs, ",") {
kind, err := model.GetEntityKindByID(ctx, r.ds, id) kind, err := model.GetEntityKindByID(ctx, r.ds, id)
if err != nil { if err != nil {
return "", err return "", err
@ -142,7 +142,7 @@ func (r *shareRepositoryWrapper) Update(ctx context.Context, id string, entity m
cols := []string{"description", "downloadable"} cols := []string{"description", "downloadable"}
// TODO Better handling of Share expiration // TODO Better handling of Share expiration
if !V(entity.ExpiresAt).IsZero() { if !gg.V(entity.ExpiresAt).IsZero() {
cols = append(cols, "expires_at") cols = append(cols, "expires_at")
} }
return r.ShareRepository.Update(ctx, id, entity, cols...) return r.ShareRepository.Update(ctx, id, entity, cols...)

View file

@ -134,7 +134,8 @@ func (ffs *FakeFS) UpdateTags(filePath string, newTags map[string]any, when ...t
var tags map[string]any var tags map[string]any
gomega.Expect(json.Unmarshal(f.Data, &tags)).To(gomega.Succeed()) gomega.Expect(json.Unmarshal(f.Data, &tags)).To(gomega.Succeed())
maps.Copy(tags, newTags) maps.Copy(tags, newTags)
data, _ := json.Marshal(tags) data, err := json.Marshal(tags)
gomega.Expect(err).ToNot(gomega.HaveOccurred())
f.Data = data f.Data = data
ffs.Touch(filePath, when...) ffs.Touch(filePath, when...)
} }
@ -208,7 +209,8 @@ func File(tags ...map[string]any) *fstest.MapFile {
if _, ok := ts[fakeFileInfoMode]; !ok { if _, ok := ts[fakeFileInfoMode]; !ok {
ts[fakeFileInfoMode] = fs.ModePerm ts[fakeFileInfoMode] = fs.ModePerm
} }
data, _ := json.Marshal(ts) data, err := json.Marshal(ts)
gomega.Expect(err).ToNot(gomega.HaveOccurred())
if _, ok := ts[fakeFileInfoSize]; !ok { if _, ok := ts[fakeFileInfoSize]; !ok {
ts[fakeFileInfoSize] = int64(len(data)) ts[fakeFileInfoSize] = int64(len(data))
} }

View file

@ -61,14 +61,16 @@ func targetSampleRate(srcSampleRate int, srcCodec string, capDSD bool) int {
// targetBitDepth returns the bit depth for a transcoded stream: 0 for lossy // 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 // targets (they have no PCM bit depth), otherwise the source depth, with DSD
// (1 bit in tags, 8 in ffprobe) 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 { func targetBitDepth(src *Details, targetIsLossless bool) int {
if !targetIsLossless { switch {
case !targetIsLossless:
return 0 return 0
} case strings.EqualFold(src.Codec, "dsd"):
if strings.EqualFold(srcCodec, "dsd") {
return 24 return 24
case !src.IsLossless:
return 16 // the most widely supported depth
} }
return srcBitDepth return src.BitDepth
} }
// codecFixedOutputSampleRate returns the mandatory output sample rate for codecs // codecFixedOutputSampleRate returns the mandatory output sample rate for codecs

View file

@ -257,9 +257,12 @@ func (s *deciderService) computeTranscodedStream(ctx context.Context, src *Detai
targetIsLossless := isLosslessFormat(targetFormat) targetIsLossless := isLosslessFormat(targetFormat)
// Reject lossy to lossless conversion lossyToLossless := !src.IsLossless && targetIsLossless
if !src.IsLossless && targetIsLossless { // Lossless output from a lossy source is far larger than the source, so no bitrate cap can be honored
log.Trace(ctx, "Skipping transcoding profile: lossy to lossless not allowed", "targetFormat", targetFormat) lossyToLosslessAllowed := clientInfo.AllowLossyToLossless && clientInfo.MaxAudioBitrate == 0
if lossyToLossless && !lossyToLosslessAllowed {
log.Trace(ctx, "Skipping transcoding profile: lossy to lossless not allowed", "sourceCodec", src.Codec,
"targetFormat", targetFormat, "maxAudioBitrate", clientInfo.MaxAudioBitrate)
return nil, "" return nil, ""
} }
@ -274,7 +277,7 @@ func (s *deciderService) computeTranscodedStream(ctx context.Context, src *Detai
Codec: targetCodec, Codec: targetCodec,
SampleRate: targetSampleRate(src.SampleRate, src.Codec, capDSD), SampleRate: targetSampleRate(src.SampleRate, src.Codec, capDSD),
Channels: src.Channels, Channels: src.Channels,
BitDepth: targetBitDepth(src.BitDepth, src.Codec, targetIsLossless), BitDepth: targetBitDepth(src, targetIsLossless),
IsLossless: targetIsLossless, IsLossless: targetIsLossless,
} }
@ -386,7 +389,7 @@ func (s *deciderService) computeBitrate(ctx context.Context, src *Details, targe
return false return false
} }
} }
} else { } else if !targetIsLossless {
ts.Bitrate = src.Bitrate ts.Bitrate = src.Bitrate
} }

View file

@ -3,7 +3,7 @@ package stream
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "errors"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/auth"
@ -26,7 +26,8 @@ func withProbe(mf *model.MediaFile) *model.MediaFile {
BitDepth: gg.V(mf.BitDepth), BitDepth: gg.V(mf.BitDepth),
Channels: mf.Channels, Channels: mf.Channels,
} }
data, _ := json.Marshal(probe) data, err := json.Marshal(probe)
Expect(err).ToNot(HaveOccurred())
mf.ProbeData = string(data) mf.ProbeData = string(data)
return mf return mf
} }
@ -1281,7 +1282,7 @@ var _ = Describe("Decider", func() {
mf := withProbe(&model.MediaFile{ID: "probe-2", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2}) mf := withProbe(&model.MediaFile{ID: "probe-2", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2})
// Set error on mock — if ffprobe were called, this would fail // Set error on mock — if ffprobe were called, this would fail
ff.Error = fmt.Errorf("should not be called") ff.Error = errors.New("should not be called")
svc := NewTranscodeDecider(ds, ff).(*deciderService) svc := NewTranscodeDecider(ds, ff).(*deciderService)
probe, err := svc.ensureProbed(ctx, mf) probe, err := svc.ensureProbed(ctx, mf)
@ -1291,7 +1292,7 @@ var _ = Describe("Decider", func() {
It("returns error when ffprobe fails", func() { It("returns error when ffprobe fails", func() {
mf := &model.MediaFile{ID: "probe-3", Suffix: "mp3"} mf := &model.MediaFile{ID: "probe-3", Suffix: "mp3"}
ff.Error = fmt.Errorf("ffprobe not found") ff.Error = errors.New("ffprobe not found")
svc := NewTranscodeDecider(ds, ff).(*deciderService) svc := NewTranscodeDecider(ds, ff).(*deciderService)
_, err := svc.ensureProbed(ctx, mf) _, err := svc.ensureProbed(ctx, mf)

View file

@ -42,6 +42,7 @@ func buildLegacyClientInfo(mf *model.MediaFile, reqFormat string, reqBitRate int
ci.TranscodingProfiles = []Profile{ ci.TranscodingProfiles = []Profile{
{Container: targetFormat, AudioCodec: targetFormat, Protocol: ProtocolHTTP}, {Container: targetFormat, AudioCodec: targetFormat, Protocol: ProtocolHTTP},
} }
ci.AllowLossyToLossless = reqFormat != ""
if reqBitRate > 0 { if reqBitRate > 0 {
ci.MaxAudioBitrate = reqBitRate ci.MaxAudioBitrate = reqBitRate
ci.MaxTranscodingAudioBitrate = reqBitRate ci.MaxTranscodingAudioBitrate = reqBitRate

View file

@ -285,6 +285,16 @@ var _ = Describe("ResolveRequest", func() {
Expect(req.BitRate).To(Equal(160)) Expect(req.BitRate).To(Equal(160))
}) })
It("serves a lossy source raw when the override targets a lossless format", func() {
mf := withProbe(&model.MediaFile{ID: "1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100})
overrideCtx := request.WithTranscoding(ctx, model.Transcoding{TargetFormat: "flac", DefaultBitRate: 0})
decider := svc.(*deciderService)
req := decider.ResolveRequest(overrideCtx, mf, "", 0, 0)
Expect(req.Format).To(Equal("raw"))
})
It("does not apply override when no transcoding is in context", func() { It("does not apply override when no transcoding is in context", func() {
mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100}) mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100})
@ -295,6 +305,40 @@ var _ = Describe("ResolveRequest", func() {
}) })
}) })
Context("lossy source with an explicitly requested lossless format", func() {
var mf *model.MediaFile
BeforeEach(func() {
conf.Update(func(c *conf.Options) { c.DefaultDownsamplingFormat = "opus" })
mf = withProbe(&model.MediaFile{ID: "1", Suffix: "ogg", Codec: "Vorbis", BitRate: 320, Channels: 2, SampleRate: 44100})
})
It("transcodes to the requested format", func() {
decider := svc.(*deciderService)
req := decider.ResolveRequest(ctx, mf, "flac", 0, 0)
Expect(req.Format).To(Equal("flac"))
Expect(req.BitRate).To(BeZero())
Expect(req.BitDepth).To(Equal(16))
})
It("falls back to DefaultDownsamplingFormat when a bitrate limit is also requested", func() {
decider := svc.(*deciderService)
req := decider.ResolveRequest(ctx, mf, "flac", 1000, 0)
Expect(req.Format).To(Equal("opus"))
})
It("falls back to DefaultDownsamplingFormat when the player has a bitrate cap", func() {
playerCtx := request.WithPlayer(ctx, model.Player{MaxBitRate: 1000})
decider := svc.(*deciderService)
req := decider.ResolveRequest(playerCtx, mf, "flac", 0, 0)
Expect(req.Format).To(Equal("opus"))
})
})
Context("Player MaxBitRate cap", func() { Context("Player MaxBitRate cap", func() {
It("applies player MaxBitRate cap when client has no limit", func() { It("applies player MaxBitRate cap when client has no limit", func() {
mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: new(16)}) mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 44100, BitDepth: new(16)})

View file

@ -68,7 +68,7 @@ var _ = Describe("MediaStreamer", func() {
}) })
It("returns a NON seekable stream if transcode is required", func() { It("returns a NON seekable stream if transcode is required", func() {
s, err := streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 64}) s, err := streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 64})
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(s.Seekable()).To(BeFalse()) Expect(s.Seekable()).To(BeFalse())
Expect(s.Duration()).To(Equal(float32(257.0))) Expect(s.Duration()).To(Equal(float32(257.0)))
}) })
@ -113,7 +113,7 @@ var _ = Describe("MediaStreamer", func() {
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
_, _ = io.ReadAll(s1) _, _ = io.ReadAll(s1)
_ = s1.Close() _ = s1.Close()
Eventually(func() bool { return ffmpeg.IsClosed() }, "3s").Should(BeTrue()) Eventually(func() bool { return ffmpeg.IsClosed() }, 3*time.Second).Should(BeTrue())
// Slot should now be free for a different transcode. // Slot should now be free for a different transcode.
s2, err := tightStreamer.NewStream(userCtx, mf, stream.Request{Format: "mp3", BitRate: 96}) s2, err := tightStreamer.NewStream(userCtx, mf, stream.Request{Format: "mp3", BitRate: 96})
@ -144,13 +144,13 @@ var _ = Describe("MediaStreamer", func() {
It("returns a seekable stream if the file is complete in the cache", func() { It("returns a seekable stream if the file is complete in the cache", func() {
s, err := streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 32}) s, err := streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 32})
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
_, _ = io.ReadAll(s) _, _ = io.ReadAll(s)
_ = s.Close() _ = s.Close()
Eventually(func() bool { return ffmpeg.IsClosed() }, "3s").Should(BeTrue()) Eventually(func() bool { return ffmpeg.IsClosed() }, 3*time.Second).Should(BeTrue())
s, err = streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 32}) s, err = streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 32})
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(s.Seekable()).To(BeTrue()) Expect(s.Seekable()).To(BeTrue())
}) })
}) })

View file

@ -38,6 +38,9 @@ type ClientInfo struct {
DirectPlayProfiles []DirectPlayProfile DirectPlayProfiles []DirectPlayProfile
TranscodingProfiles []Profile TranscodingProfiles []Profile
CodecProfiles []CodecProfile CodecProfiles []CodecProfile
// AllowLossyToLossless is set when a format was requested by name rather than
// negotiated from a preference list, where it would only inflate lossy files.
AllowLossyToLossless bool
} }
// CapBitrate lowers the client's declared audio bitrate limits to maxKbps, // CapBitrate lowers the client's declared audio bitrate limits to maxKbps,

View file

@ -60,11 +60,11 @@ func copyDatabase(ctx context.Context, dest, source *sql.DB) error {
return sourceConn.Raw(func(rawSource any) error { return sourceConn.Raw(func(rawSource any) error {
sqliteDest, destOk := rawDest.(*sqlite3.SQLiteConn) sqliteDest, destOk := rawDest.(*sqlite3.SQLiteConn)
if !destOk { if !destOk {
return fmt.Errorf("error trying to convert destination to sqlite connection") return errors.New("error trying to convert destination to sqlite connection")
} }
sqliteSource, sourceOk := rawSource.(*sqlite3.SQLiteConn) sqliteSource, sourceOk := rawSource.(*sqlite3.SQLiteConn)
if !sourceOk { if !sourceOk {
return fmt.Errorf("error trying to convert source to sqlite connection") return errors.New("error trying to convert source to sqlite connection")
} }
backupOp, err := sqliteDest.Backup("main", sqliteSource, "main") backupOp, err := sqliteDest.Backup("main", sqliteSource, "main")
@ -80,7 +80,7 @@ func copyDatabase(ctx context.Context, dest, source *sql.DB) error {
return fmt.Errorf("error during backup step: %w", err) return fmt.Errorf("error during backup step: %w", err)
} }
if !done { if !done {
return fmt.Errorf("backup not done with step -1") return errors.New("backup not done with step -1")
} }
err = backupOp.Finish() err = backupOp.Finish()

View file

@ -34,8 +34,8 @@ var embedMigrations embed.FS
const migrationsFolder = "migrations" const migrationsFolder = "migrations"
// sql.Register panics if called twice, so guard it: the singleton instance can be reset // registerDriverOnce guards sql.Register, which panics if called twice: the singleton instance can be
// (tests/benchmarks) and rebuilt, but the driver is process-global and registers only once. // reset (tests/benchmarks) and rebuilt, but the driver is process-global and registers only once.
var registerDriverOnce sync.Once var registerDriverOnce sync.Once
func Db() *sql.DB { func Db() *sql.DB {

View file

@ -126,9 +126,10 @@ create index folder_parent_id on folder(parent_id);
`) `)
} }
// Use paths from `media_file` table to populate `folder` table. The `folder` table must contain all paths, including // upSupportNewScanner_PopulateTableFolder uses paths from `media_file` table to populate `folder` table.
// the ones that do not contain any media_file. We can get all paths from the media_file table to populate a // The `folder` table must contain all paths, including the ones that do not contain any media_file. We can
// fstest.MapFS{}, and then walk the filesystem to insert all folders into the DB, including empty parent ones. // get all paths from the media_file table to populate a fstest.MapFS{}, and then walk the filesystem to
// insert all folders into the DB, including empty parent ones.
func upSupportNewScanner_PopulateTableFolder(ctx context.Context, tx *sql.Tx) execFunc { func upSupportNewScanner_PopulateTableFolder(ctx context.Context, tx *sql.Tx) execFunc {
return func() error { return func() error {
// First, get all folder paths from media_file table // First, get all folder paths from media_file table

View file

@ -13,10 +13,10 @@ func init() {
goose.AddMigrationContext(upBackfillArtistSearchNormalized, downBackfillArtistSearchNormalized) goose.AddMigrationContext(upBackfillArtistSearchNormalized, downBackfillArtistSearchNormalized)
} }
// The FTS5 migration back-filled artist.search_normalized with a SQL approximation that // upBackfillArtistSearchNormalized recomputes artist.search_normalized in Go. The FTS5 migration
// cannot transliterate atomic letters (Ø, æ, ß, ...), and the scanner never rewrote the // back-filled it with a SQL approximation that cannot transliterate atomic letters (Ø, æ, ß, ...),
// column, leaving artists like "GØGGS" unfindable by ASCII searches. Recompute it in Go; // and the scanner never rewrote the column, leaving artists like "GØGGS" unfindable by ASCII
// the artist_fts update trigger re-indexes every row that changes. // searches. The artist_fts update trigger re-indexes every row that changes.
func upBackfillArtistSearchNormalized(ctx context.Context, tx *sql.Tx) error { func upBackfillArtistSearchNormalized(ctx context.Context, tx *sql.Tx) error {
notice(ctx, tx, "Rebuilding artist search index data. This may take a moment on large libraries.") notice(ctx, tx, "Rebuilding artist search index data. This may take a moment on large libraries.")

View file

@ -93,7 +93,7 @@ var _ = Describe("idColumns inventory", func() {
} }
dangling = append(dangling, key) dangling = append(dangling, key)
} }
Expect(rows.Err()).ToNot(HaveOccurred()) Expect(rows.Err()).To(Succeed())
Expect(rows.Close()).To(Succeed()) Expect(rows.Close()).To(Succeed())
} }
Expect(dangling).To(BeEmpty(), Expect(dangling).To(BeEmpty(),

View file

@ -11,7 +11,8 @@ import (
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
) )
// Use this in migrations that need to communicate something important (breaking changes, forced reindexes, etc...) // notice is for migrations that need to communicate something important (breaking changes, forced
// reindexes, etc...)
func notice(ctx context.Context, tx *sql.Tx, msg string) { func notice(ctx context.Context, tx *sql.Tx, msg string) {
if isDBInitialized(ctx, tx) { if isDBInitialized(ctx, tx) {
line := strings.Repeat("*", len(msg)+8) line := strings.Repeat("*", len(msg)+8)
@ -19,7 +20,7 @@ func notice(ctx context.Context, tx *sql.Tx, msg string) {
} }
} }
// Call this in migrations that requires a full rescan // forceFullRescan is for migrations that require a full rescan
func forceFullRescan(ctx context.Context, tx *sql.Tx) error { func forceFullRescan(ctx context.Context, tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, fmt.Sprintf(` _, err := tx.ExecContext(ctx, fmt.Sprintf(`
INSERT OR REPLACE into property (id, value) values ('%s', '1'); INSERT OR REPLACE into property (id, value) values ('%s', '1');
@ -64,8 +65,8 @@ func createExecuteFunc(ctx context.Context, tx *sql.Tx) execStmtFunc {
} }
} }
// Hack way to add a new `not null` column to a table, setting the initial value for existing rows based on a // createAddColumnFunc is a hack to add a new `not null` column to a table, setting the initial value for
// SQL expression. It is done in 3 steps: // existing rows based on a SQL expression. It is done in 3 steps:
// 1. Add the column as nullable. Due to the way SQLite manipulates the DDL in memory, we need to add extra padding // 1. Add the column as nullable. Due to the way SQLite manipulates the DDL in memory, we need to add extra padding
// to the default value to avoid truncating it when changing the column to not null // to the default value to avoid truncating it when changing the column to not null
// 2. Update the column with the initial value // 2. Update the column with the initial value
@ -76,7 +77,7 @@ func createAddColumnFunc(ctx context.Context, tx *sql.Tx) addColumnFunc {
return func(tableName, columnName, columnType, defaultValue, initialValue string) execFunc { return func(tableName, columnName, columnType, defaultValue, initialValue string) execFunc {
return func() error { return func() error {
// Format the `default null` value to have the same length as the final defaultValue // Format the `default null` value to have the same length as the final defaultValue
finalLen := len(fmt.Sprintf(`%s not`, defaultValue)) finalLen := len(defaultValue + " not")
tempDefault := fmt.Sprintf(`default %s null`, strings.Repeat(" ", finalLen)) tempDefault := fmt.Sprintf(`default %s null`, strings.Repeat(" ", finalLen))
_, err := tx.ExecContext(ctx, fmt.Sprintf(` _, err := tx.ExecContext(ctx, fmt.Sprintf(`
alter table %s add column %s %s %s;`, tableName, columnName, columnType, tempDefault)) alter table %s add column %s %s %s;`, tableName, columnName, columnType, tempDefault))

View file

@ -144,8 +144,9 @@ func optimizeAt(ctx context.Context, db *sql.DB, now time.Time) error {
return nil return nil
} }
// One ANALYZE per index (whole table if WITHOUT ROWID or lacking a non-partial index) yields the // analyzeTargetsSQL picks one ANALYZE target per index (whole table if WITHOUT ROWID or lacking a
// same sqlite_stat1 rows as a full ANALYZE, but frees the write lock between steps. // non-partial index). That yields the same sqlite_stat1 rows as a full ANALYZE, but frees the write lock
// between steps.
const analyzeTargetsSQL = ` const analyzeTargetsSQL = `
SELECT i.name FROM sqlite_schema i JOIN pragma_table_list t ON t.schema = 'main' AND t.name = i.tbl_name SELECT i.name FROM sqlite_schema i JOIN pragma_table_list t ON t.schema = 'main' AND t.name = i.tbl_name
WHERE i.type = 'index' AND t.wr = 0 AND EXISTS (SELECT 1 FROM pragma_index_list(t.name) l WHERE l.partial = 0) WHERE i.type = 'index' AND t.wr = 0 AND EXISTS (SELECT 1 FROM pragma_index_list(t.name) l WHERE l.partial = 0)

View file

@ -170,7 +170,7 @@ var _ = Describe("Repair", func() {
Expect(rows.Scan(&name, &ddl)).To(Succeed()) Expect(rows.Scan(&name, &ddl)).To(Succeed())
schema[name] = ws.ReplaceAllString(ddl, " ") schema[name] = ws.ReplaceAllString(ddl, " ")
} }
Expect(rows.Err()).ToNot(HaveOccurred()) Expect(rows.Err()).To(Succeed())
return schema return schema
} }

View file

@ -77,7 +77,7 @@ var _ = Describe("Logger", func() {
It("can get data from the request's context", func() { It("can get data from the request's context", func() {
ctx = NewContext(ctx, "foo", "bar") ctx = NewContext(ctx, "foo", "bar")
req := httptest.NewRequest("get", "/", nil).WithContext(ctx) req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx)
Error(req, "Simple Message", "key1", "value1") Error(req, "Simple Message", "key1", "value1")
@ -206,12 +206,12 @@ var _ = Describe("Logger", func() {
Describe("extractLogger", func() { Describe("extractLogger", func() {
It("returns an error if the context is nil", func() { It("returns an error if the context is nil", func() {
_, err := extractLogger(nil) _, err := extractLogger(nil)
Expect(err).ToNot(BeNil()) Expect(err).To(HaveOccurred())
}) })
It("returns an error if the context is a string", func() { It("returns an error if the context is a string", func() {
_, err := extractLogger("any msg") _, err := extractLogger("any msg")
Expect(err).ToNot(BeNil()) Expect(err).To(HaveOccurred())
}) })
It("returns the logger from context if it has one", func() { It("returns the logger from context if it has one", func() {
@ -224,7 +224,7 @@ var _ = Describe("Logger", func() {
It("returns the logger from request's context if it has one", func() { It("returns the logger from request's context if it has one", func() {
logger := logrus.NewEntry(logrus.New()) logger := logrus.NewEntry(logrus.New())
ctx = context.WithValue(ctx, loggerCtxKey, logger) ctx = context.WithValue(ctx, loggerCtxKey, logger)
req := httptest.NewRequest("get", "/", nil).WithContext(ctx) req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx)
Expect(extractLogger(req)).To(Equal(logger)) Expect(extractLogger(req)).To(Equal(logger))
}) })

View file

@ -33,13 +33,11 @@ func TestLevels(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
fn := func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
h.AcceptedLevels = test.acceptedLevels h.AcceptedLevels = test.acceptedLevels
levels := h.Levels() levels := h.Levels()
assert.Equal(t, test.expected, levels, test.description) assert.Equal(t, test.expected, levels, test.description)
} })
t.Run(test.name, fn)
} }
} }
@ -54,7 +52,7 @@ type levelThresholdTest struct {
// above and including the level given. If the provided level does not exit, // above and including the level given. If the provided level does not exit,
// an empty slice is returned. // an empty slice is returned.
func levelThreshold(l logrus.Level) []logrus.Level { func levelThreshold(l logrus.Level) []logrus.Level {
if l < 0 || int(l) > len(logrus.AllLevels) { if int(l) >= len(logrus.AllLevels) {
return []logrus.Level{} return []logrus.Level{}
} }
return logrus.AllLevels[:l+1] return logrus.AllLevels[:l+1]
@ -68,6 +66,12 @@ func TestLevelThreshold(t *testing.T) {
expected: []logrus.Level{}, expected: []logrus.Level{},
description: "An empty Level slice was expected but was not returned", description: "An empty Level slice was expected but was not returned",
}, },
{
name: "levelPastLast",
level: logrus.Level(len(logrus.AllLevels)),
expected: []logrus.Level{},
description: "An empty Level slice was expected for the first level past TraceLevel",
},
{ {
name: "errorLogLevel", name: "errorLogLevel",
level: logrus.ErrorLevel, level: logrus.ErrorLevel,
@ -77,12 +81,10 @@ func TestLevelThreshold(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
fn := func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
levels := levelThreshold(test.level) levels := levelThreshold(test.level)
assert.Equal(t, test.expected, levels, test.description) assert.Equal(t, test.expected, levels, test.description)
} })
t.Run(test.name, fn)
} }
} }
@ -130,7 +132,7 @@ func TestEntryDataValues(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
fn := func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
logEntry := &logrus.Entry{ logEntry := &logrus.Entry{
Data: test.logFields, Data: test.logFields,
} }
@ -139,8 +141,7 @@ func TestEntryDataValues(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, test.expected, logEntry.Data) assert.Equal(t, test.expected, logEntry.Data)
} })
t.Run(test.name, fn)
} }
} }

View file

@ -38,11 +38,11 @@ var _ = Describe("Albums", func() {
}) })
It("marshals correctly", func() { It("marshals correctly", func() {
data, err := json.Marshal(albums) data, err := json.Marshal(albums)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
var albums2 Albums var albums2 Albums
err = json.Unmarshal(data, &albums2) err = json.Unmarshal(data, &albums2)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(albums2).To(Equal(albums)) Expect(albums2).To(Equal(albums))
}) })
}) })

View file

@ -117,7 +117,8 @@ const (
ArtworkPriorityBump = 100 ArtworkPriorityBump = 100
) )
// Delete* takes the rows to remove; Purge* finds them itself and reports how many went. // ArtworkRepository stores the artwork images. Delete* takes the rows to remove; Purge* finds them itself
// and reports how many went.
type ArtworkRepository interface { type ArtworkRepository interface {
GetImage(ctx context.Context, hash string) (*Artwork, error) GetImage(ctx context.Context, hash string) (*Artwork, error)
PutImage(ctx context.Context, a *Artwork) error PutImage(ctx context.Context, a *Artwork) error

View file

@ -116,7 +116,7 @@ func isImageHash(s string) bool {
return false return false
} }
for _, c := range s { for _, c := range s {
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
return false return false
} }
} }

Some files were not shown because too many files have changed in this diff Show more