mirror of
https://github.com/navidrome/navidrome.git
synced 2026-11-18 16:18:52 +01:00
Compare commits
4 commits
master
...
fix/6285-l
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e62d83756 |
||
|
|
be7a8cafcf | ||
|
|
df918ee275 | ||
|
|
bf72f00760 |
323 changed files with 1992 additions and 2891 deletions
|
|
@ -14,29 +14,21 @@ 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
|
||||||
- staticcheck
|
|
||||||
- thelper
|
|
||||||
- unconvert
|
- unconvert
|
||||||
- usestdlibvars
|
|
||||||
- usetesting
|
|
||||||
- whitespace
|
- whitespace
|
||||||
|
disable:
|
||||||
|
- staticcheck
|
||||||
settings:
|
settings:
|
||||||
depguard:
|
depguard:
|
||||||
rules:
|
rules:
|
||||||
|
|
@ -131,22 +123,6 @@ 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:
|
||||||
|
|
@ -157,9 +133,6 @@ 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$'
|
||||||
|
|
@ -178,19 +151,6 @@ 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:
|
||||||
|
|
@ -209,11 +169,6 @@ 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
|
||||||
|
|
|
||||||
|
|
@ -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, http.MethodGet, apiBaseURL+"/search/artist", nil)
|
req, err := http.NewRequestWithContext(ctx, "GET", 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 != http.StatusOK {
|
if resp.StatusCode != 200 {
|
||||||
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, http.MethodGet, fmt.Sprintf("%s/artist/%d/related", apiBaseURL, artistID), nil)
|
req, err := http.NewRequestWithContext(ctx, "GET", 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, http.MethodGet, fmt.Sprintf("%s/artist/%d/top", apiBaseURL, artistID), nil)
|
req, err := http.NewRequestWithContext(ctx, "GET", 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, http.MethodPost, pipeAPIURL, bytes.NewReader(body))
|
req, err := http.NewRequestWithContext(ctx, "POST", 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 != http.StatusOK {
|
if resp.StatusCode != 200 {
|
||||||
return "", fmt.Errorf("deezer: failed to fetch biography: %s", resp.Status)
|
return "", fmt.Errorf("deezer: failed to fetch biography: %s", resp.Status)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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, http.MethodGet, authBaseURL+"/login/anonymous?jo=p&rto=c", nil)
|
req, err := http.NewRequestWithContext(ctx, "GET", 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 != http.StatusOK {
|
if resp.StatusCode != 200 {
|
||||||
return "", fmt.Errorf("deezer: failed to get JWT token: %s", resp.Status)
|
return "", fmt.Errorf("deezer: failed to get JWT token: %s", resp.Status)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
|
testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: http.StatusOK,
|
StatusCode: 200,
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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: http.StatusInternalServerError,
|
StatusCode: 500,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
// 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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
Expect(token2).To(Equal(secondJWT))
|
Expect(token2).To(Equal(secondJWT))
|
||||||
Expect(token2).ToNot(Equal(token1))
|
Expect(token2).ToNot(Equal(token1))
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: http.StatusOK})
|
httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: 200})
|
||||||
|
|
||||||
artists, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20)
|
artists, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: http.StatusOK})
|
httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: 200})
|
||||||
|
|
||||||
tracks, err := client.getTopTracks(GinkgoT().Context(), 27, 5)
|
tracks, err := client.getTopTracks(GinkgoT().Context(), 27, 5)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
|
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
|
||||||
|
|
||||||
bio, err := client.getArtistBio(GinkgoT().Context(), 27, "en")
|
bio, err := client.getArtistBio(GinkgoT().Context(), 27, "en")
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
|
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
|
||||||
|
|
||||||
_, err = client.getArtistBio(GinkgoT().Context(), 27, "fr")
|
_, err = client.getArtistBio(GinkgoT().Context(), 27, "fr")
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
|
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
|
||||||
|
|
||||||
_, err = client.getArtistBio(GinkgoT().Context(), 27, "en")
|
_, err = client.getArtistBio(GinkgoT().Context(), 27, "en")
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
// 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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusInternalServerError,
|
StatusCode: 500,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, expiredJWT))),
|
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, expiredJWT))),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK}
|
httpClient.searchResponse = &http.Response{Body: fSearch, StatusCode: 200}
|
||||||
|
|
||||||
// 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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusOK}
|
httpClient.bioResponses["fr"] = &http.Response{Body: fFr, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: 200}
|
||||||
// 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: http.StatusOK}
|
httpClient.bioResponses["en"] = &http.Response{Body: fEn, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: 200}
|
||||||
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: http.StatusOK}
|
httpClient.bioResponses["xx"] = &http.Response{Body: fXx, StatusCode: 200}
|
||||||
|
|
||||||
_, 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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusInternalServerError,
|
StatusCode: 500,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"data":{"artist":{"bio":{"full":""}}}}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"data":{"artist":{"bio":{"full":""}}}}`)),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
err = json.Unmarshal(body, &resp)
|
err = json.Unmarshal(body, &resp)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
err = json.Unmarshal(body, &resp)
|
err = json.Unmarshal(body, &resp)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
err = json.Unmarshal(body, &resp)
|
err = json.Unmarshal(body, &resp)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
Expect(resp.Data).To(HaveLen(5))
|
Expect(resp.Data).To(HaveLen(5))
|
||||||
track := resp.Data[0]
|
track := resp.Data[0]
|
||||||
|
|
|
||||||
|
|
@ -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.ModTime()
|
return t.FileInfo.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{
|
||||||
Name: name, SortArtistName: sortName, MbzArtistID: mbid,
|
Artist: model.Artist{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).ToNot(HaveOccurred())
|
Expect(err).To(Not(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(BeEmpty())
|
Expect(actual).To(HaveLen(0))
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -246,7 +246,7 @@ func parseASFAttributes(rawAttrs map[string][]string, tags map[string][]string)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// tiplMapping lists the only roles we support, based on Picard's tag map:
|
// These are 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",
|
||||||
|
|
|
||||||
|
|
@ -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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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.
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
|
||||||
// errNoArtistPage is not a RetryLaterError on purpose: parking the agent would also stall its
|
// Not a RetryLaterError on purpose: parking the agent would also stall its API-backed
|
||||||
// API-backed methods, which the page block does not affect.
|
// 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")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
|
||||||
_, 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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
_, 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: http.StatusOK}
|
httpClient.responses["pt"] = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
|
||||||
// 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: http.StatusOK}
|
httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
|
||||||
// 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: http.StatusOK}
|
httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: 200}
|
||||||
|
|
||||||
_, 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: http.StatusOK}
|
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
|
||||||
// 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: http.StatusOK}
|
httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
|
||||||
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: http.StatusOK}
|
httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
|
||||||
_, 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{
|
||||||
{ID: "ar-1", Name: "First Artist"},
|
{Artist: model.Artist{ID: "ar-1", Name: "First Artist"}},
|
||||||
{ID: "ar-2", Name: "Second Artist"},
|
{Artist: model.Artist{ID: "ar-2", Name: "Second Artist"}},
|
||||||
},
|
},
|
||||||
model.RoleAlbumArtist: []model.Participant{
|
model.RoleAlbumArtist: []model.Participant{
|
||||||
{ID: "ar-1", Name: "First Album Artist"},
|
{Artist: model.Artist{ID: "ar-1", Name: "First Album Artist"}},
|
||||||
{ID: "ar-2", Name: "Second Album Artist"},
|
{Artist: model.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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"scrobbles":{"scrobble":{"ignoredMessage":{"code":"0"}},"@attr":{"accepted":1}}}`)), StatusCode: 200}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusBadRequest,
|
StatusCode: 400,
|
||||||
}
|
}
|
||||||
|
|
||||||
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: http.StatusBadRequest,
|
StatusCode: 400,
|
||||||
}
|
}
|
||||||
|
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
|
|
||||||
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: http.StatusInternalServerError,
|
StatusCode: 500,
|
||||||
}
|
}
|
||||||
|
|
||||||
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: http.StatusBadRequest,
|
StatusCode: 400,
|
||||||
}
|
}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: 200}
|
||||||
_, 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: http.StatusOK}
|
apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
apiClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: 200}
|
||||||
_, 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: http.StatusOK}
|
apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200}
|
||||||
|
|
||||||
_, 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: http.StatusOK}
|
apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200}
|
||||||
|
|
||||||
_, 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: http.StatusOK}
|
apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{}`)),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -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(BeFalse())
|
Expect(body["status"]).To(Equal(false))
|
||||||
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())
|
||||||
|
|
|
||||||
|
|
@ -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 != http.StatusOK && jsonErr != nil {
|
if resp.StatusCode != 200 && 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 {
|
||||||
|
|
|
||||||
|
|
@ -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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
album, err := client.albumGetInfo(ctx, "Believe", "U2", "mbid-1234", "pt")
|
album, err := client.albumGetInfo(ctx, "Believe", "U2", "mbid-1234", "pt")
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
artist, err := client.artistGetInfo(ctx, "U2", "pt")
|
artist, err := client.artistGetInfo(ctx, "U2", "pt")
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
_, 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: http.StatusInternalServerError,
|
StatusCode: 500,
|
||||||
}
|
}
|
||||||
|
|
||||||
_, 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: http.StatusBadRequest,
|
StatusCode: 400,
|
||||||
}
|
}
|
||||||
|
|
||||||
_, 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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
|
|
||||||
_, 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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
|
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
similar, err := client.artistGetSimilar(ctx, "U2", 2)
|
similar, err := client.artistGetSimilar(ctx, "U2", 2)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
Expect(similar.Artists).To(HaveLen(2))
|
Expect(len(similar.Artists)).To(Equal(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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
top, err := client.artistGetTopTracks(ctx, "U2", 2)
|
top, err := client.artistGetTopTracks(ctx, "U2", 2)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
Expect(top.Track).To(HaveLen(2))
|
Expect(len(top.Track)).To(Equal(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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
Expect(similar.Track).To(HaveLen(5))
|
Expect(len(similar.Track)).To(Equal(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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
similar, err := client.trackGetSimilar(ctx, "UnknownTrack", "UnknownArtist", 3)
|
similar, err := client.trackGetSimilar(ctx, "UnknownTrack", "UnknownArtist", 3)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
|
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
|
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
|
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
|
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
req := httpClient.SavedRequest
|
req := httpClient.SavedRequest
|
||||||
Expect(req.Method).To(Equal(http.MethodPost))
|
Expect(req.Method).To(Equal(http.MethodPost))
|
||||||
|
|
|
||||||
|
|
@ -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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
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"))
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,6 @@ import (
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"reflect"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/conf"
|
"github.com/navidrome/navidrome/conf"
|
||||||
|
|
@ -48,8 +47,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{
|
||||||
{ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"},
|
{Artist: model.Artist{ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"}},
|
||||||
{ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"},
|
{Artist: model.Artist{ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"}},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
@ -82,7 +81,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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
|
||||||
|
|
||||||
err := agent.NowPlaying(ctx, "user-1", track, 0)
|
err := agent.NowPlaying(ctx, "user-1", track, 0)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
@ -102,14 +101,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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
|
||||||
|
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", sc)
|
err := agent.Scrobble(ctx, "user-1", sc)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
@ -130,7 +129,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: http.StatusServiceUnavailable,
|
StatusCode: 503,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", sc)
|
err := agent.Scrobble(ctx, "user-1", sc)
|
||||||
|
|
@ -140,7 +139,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: http.StatusInternalServerError,
|
StatusCode: 500,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", sc)
|
err := agent.Scrobble(ctx, "user-1", sc)
|
||||||
|
|
@ -150,7 +149,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: http.StatusInternalServerError,
|
StatusCode: 500,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", sc)
|
err := agent.Scrobble(ctx, "user-1", sc)
|
||||||
|
|
@ -160,7 +159,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: http.StatusBadRequest,
|
StatusCode: 400,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", sc)
|
err := agent.Scrobble(ctx, "user-1", sc)
|
||||||
|
|
@ -169,7 +168,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: http.StatusTooManyRequests,
|
StatusCode: 429,
|
||||||
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"}`)),
|
||||||
}
|
}
|
||||||
|
|
@ -193,7 +192,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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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"))
|
||||||
|
|
@ -201,7 +200,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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
_, 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))
|
||||||
|
|
@ -219,7 +218,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: http.StatusBadRequest,
|
StatusCode: 400,
|
||||||
}
|
}
|
||||||
_, 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())
|
||||||
|
|
@ -249,7 +248,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: http.StatusBadRequest,
|
StatusCode: 400,
|
||||||
}
|
}
|
||||||
_, err := agent.GetArtistTopSongs(ctx, "", "", "1", 1)
|
_, err := agent.GetArtistTopSongs(ctx, "", "", "1", 1)
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
|
|
@ -259,7 +258,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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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{
|
||||||
|
|
@ -286,7 +285,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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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{
|
||||||
|
|
@ -312,7 +311,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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: 200}
|
||||||
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))
|
||||||
|
|
@ -324,7 +323,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: http.StatusOK}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: 200}
|
||||||
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))
|
||||||
|
|
@ -356,7 +355,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: http.StatusBadRequest,
|
StatusCode: 400,
|
||||||
}
|
}
|
||||||
_, err := agent.GetSimilarArtists(ctx, "", "", "1", 1)
|
_, err := agent.GetSimilarArtists(ctx, "", "", "1", 1)
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
|
|
@ -366,7 +365,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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
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())
|
||||||
|
|
@ -380,7 +379,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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
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())
|
||||||
|
|
@ -416,7 +415,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: http.StatusBadRequest,
|
StatusCode: 400,
|
||||||
}
|
}
|
||||||
_, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", "1", 1)
|
_, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", "1", 1)
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
|
|
@ -426,7 +425,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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 2)
|
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 2)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
@ -458,7 +457,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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
|
|
||||||
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 1)
|
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 1)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
@ -501,9 +500,8 @@ var _ = Describe("register", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("builds no scrobbler and no agent", func() {
|
It("builds no scrobbler and no agent", func() {
|
||||||
// TypeOf is nil only for an untyped nil; a typed nil would pass callers' != nil checks
|
Expect(newScrobbler(ds) == nil).To(BeTrue())
|
||||||
Expect(reflect.TypeOf(newScrobbler(ds))).To(BeNil())
|
Expect(agents.Map[listenBrainzAgentName](ds) == nil).To(BeTrue())
|
||||||
Expect(reflect.TypeOf(agents.Map[listenBrainzAgentName](ds))).To(BeNil())
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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(http.MethodGet, "/listenbrainz/link", nil)
|
req = httptest.NewRequest("GET", "/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(Succeed())
|
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil())
|
||||||
Expect(parsed["status"]).To(BeFalse())
|
Expect(parsed["status"]).To(Equal(false))
|
||||||
})
|
})
|
||||||
|
|
||||||
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(http.MethodGet, "/listenbrainz/link", nil)
|
req = httptest.NewRequest("GET", "/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(Succeed())
|
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil())
|
||||||
Expect(parsed["status"]).To(BeTrue())
|
Expect(parsed["status"]).To(Equal(true))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
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(http.MethodPut, "/listenbrainz/link", strings.NewReader(`{}`))
|
req = httptest.NewRequest("PUT", "/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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
|
|
||||||
req = httptest.NewRequest(http.MethodPut, "/listenbrainz/link", strings.NewReader(`{"token": "invalid-tok-1"}`))
|
req = httptest.NewRequest("PUT", "/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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
|
|
||||||
req = httptest.NewRequest(http.MethodPut, "/listenbrainz/link", strings.NewReader(`{"token": "tok-1"}`))
|
req = httptest.NewRequest("PUT", "/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(Succeed())
|
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil())
|
||||||
Expect(parsed["status"]).To(BeTrue())
|
Expect(parsed["status"]).To(Equal(true))
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
|
|
||||||
req = httptest.NewRequest(http.MethodPut, "/listenbrainz/link", strings.NewReader(`{"token": "tok-1"}`))
|
req = httptest.NewRequest("PUT", "/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(http.MethodDelete, "/listenbrainz/link", nil)
|
req = httptest.NewRequest("DELETE", "/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(""))
|
||||||
|
|
|
||||||
|
|
@ -162,10 +162,7 @@ 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, err := json.Marshal(r.Body)
|
b, _ := 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
|
||||||
|
|
@ -174,7 +171,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", "Token "+r.ApiKey)
|
req.Header.Add("Authorization", fmt.Sprintf("Token %s", 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)
|
||||||
|
|
@ -191,7 +188,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 != http.StatusOK && jsonErr != nil {
|
if resp.StatusCode != 200 && 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 {
|
||||||
|
|
@ -226,7 +223,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 != http.StatusOK {
|
if resp.StatusCode != 200 {
|
||||||
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)
|
||||||
|
|
|
||||||
|
|
@ -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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -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(BeTrue())
|
Expect(res.Valid).To(Equal(true))
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
}
|
}
|
||||||
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: http.StatusBadRequest,
|
StatusCode: 400,
|
||||||
}
|
}
|
||||||
_, 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: http.StatusNotImplemented,
|
StatusCode: 501,
|
||||||
}
|
}
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusBadRequest,
|
StatusCode: 400,
|
||||||
}
|
}
|
||||||
_, 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: http.StatusInternalServerError,
|
StatusCode: 500,
|
||||||
}
|
}
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusBadRequest,
|
StatusCode: 400,
|
||||||
}
|
}
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusBadRequest,
|
StatusCode: 400,
|
||||||
}
|
}
|
||||||
_, 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
// 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: http.StatusOK}
|
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||||
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: http.StatusTooManyRequests,
|
StatusCode: 429,
|
||||||
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: http.StatusTooManyRequests,
|
StatusCode: 429,
|
||||||
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: http.StatusTooManyRequests,
|
StatusCode: 429,
|
||||||
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: http.StatusOK,
|
StatusCode: 200,
|
||||||
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: http.StatusTooManyRequests,
|
StatusCode: 429,
|
||||||
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"}`)),
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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, errors.New("no selector given: pass --kind, --source or --all")
|
return nil, fmt.Errorf("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 = " " + externalLookupLine(external)
|
cost = fmt.Sprintf(" %s", 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, errors.New("no selector given: pass --kind, --priority or --all")
|
return nil, nil, fmt.Errorf("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) {
|
||||||
|
|
|
||||||
|
|
@ -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{})).ToNot(Succeed())
|
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{})).To(HaveOccurred())
|
||||||
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"id1"})).To(Succeed())
|
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"id1"})).ToNot(HaveOccurred())
|
||||||
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"ar", "id1"})).To(Succeed())
|
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"ar", "id1"})).ToNot(HaveOccurred())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -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{})).To(Succeed())
|
Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{})).ToNot(HaveOccurred())
|
||||||
Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{"x"})).ToNot(Succeed())
|
Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{"x"})).To(HaveOccurred())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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 {
|
||||||
fmt.Fprintf(&res, "====================\nFile: %s\n\n", out[i].File)
|
res.WriteString(fmt.Sprintf("====================\nFile: %s\n\n", out[i].File))
|
||||||
t, _ := toml.Marshal(out[i].RawTags)
|
t, _ := toml.Marshal(out[i].RawTags)
|
||||||
fmt.Fprintf(&res, "Raw tags:\n%s\n\n", t)
|
res.WriteString(fmt.Sprintf("Raw tags:\n%s\n\n", t))
|
||||||
t, _ = toml.Marshal(out[i].MappedTags)
|
t, _ = toml.Marshal(out[i].MappedTags)
|
||||||
fmt.Fprintf(&res, "Mapped tags:\n%s\n\n", t)
|
res.WriteString(fmt.Sprintf("Mapped tags:\n%s\n\n", t))
|
||||||
}
|
}
|
||||||
return []byte(res.String()), nil
|
return []byte(res.String()), nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -94,10 +94,7 @@ func writeMissingList(w io.Writer, format string, mfs model.MediaFileCursor) err
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
j, err := json.Marshal(displayMissingFile{ID: mf.ID, LibraryID: mf.LibraryID, Title: mf.Title, Album: mf.Album, Artist: mf.Artist, Path: mf.Path})
|
j, _ := 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 = ","
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -247,10 +247,7 @@ func runList(ctx context.Context) {
|
||||||
display[idx].Public = playlist.Public
|
display[idx].Public = playlist.Public
|
||||||
}
|
}
|
||||||
|
|
||||||
j, err := json.Marshal(display)
|
j, _ := json.Marshal(display)
|
||||||
if err != nil {
|
|
||||||
log.Fatal(ctx, "Failed to encode playlists", err)
|
|
||||||
}
|
|
||||||
fmt.Printf("%s\n", j)
|
fmt.Printf("%s\n", j)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,6 @@ import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/csv"
|
"encoding/csv"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
|
|
@ -308,7 +307,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, strconv.FormatBool(p.Enabled), p.LastError})
|
_ = w.Write([]string{p.ID, name, version, fmt.Sprintf("%t", p.Enabled), p.LastError})
|
||||||
}
|
}
|
||||||
w.Flush()
|
w.Flush()
|
||||||
return sb.String(), w.Error()
|
return sb.String(), w.Error()
|
||||||
|
|
@ -441,7 +440,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 errors.New("nothing to update: provide at least one of --config/--users/--libraries/--write-access")
|
return fmt.Errorf("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 {
|
||||||
|
|
@ -500,18 +499,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 "", errors.New("invalid JSON in --users")
|
return "", fmt.Errorf("invalid JSON in --users")
|
||||||
}
|
}
|
||||||
return value, nil
|
return value, nil
|
||||||
}
|
}
|
||||||
var names []string
|
var names []string
|
||||||
for u := range strings.SplitSeq(value, ",") {
|
for _, u := range strings.Split(value, ",") {
|
||||||
if u = strings.TrimSpace(u); u != "" {
|
if u = strings.TrimSpace(u); u != "" {
|
||||||
names = append(names, u)
|
names = append(names, u)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
b, err := json.Marshal(names)
|
b, _ := json.Marshal(names)
|
||||||
return string(b), err
|
return string(b), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// librariesToJSON accepts either a JSON array (starts with '[') or a
|
// librariesToJSON accepts either a JSON array (starts with '[') or a
|
||||||
|
|
@ -522,12 +521,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 "", errors.New("invalid JSON in --libraries")
|
return "", fmt.Errorf("invalid JSON in --libraries")
|
||||||
}
|
}
|
||||||
return value, nil
|
return value, nil
|
||||||
}
|
}
|
||||||
ids := []int{}
|
ids := []int{}
|
||||||
for l := range strings.SplitSeq(value, ",") {
|
for _, l := range strings.Split(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 {
|
||||||
|
|
@ -536,8 +535,8 @@ func librariesToJSON(value string) (string, error) {
|
||||||
ids = append(ids, id)
|
ids = append(ids, id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
b, err := json.Marshal(ids)
|
b, _ := json.Marshal(ids)
|
||||||
return string(b), err
|
return string(b), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var pluginRescanCmd = &cobra.Command{
|
var pluginRescanCmd = &cobra.Command{
|
||||||
|
|
|
||||||
|
|
@ -449,7 +449,6 @@ 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)
|
||||||
|
|
|
||||||
|
|
@ -469,10 +469,7 @@ func runUserList(ctx context.Context) {
|
||||||
users[idx].Libraries = paths
|
users[idx].Libraries = paths
|
||||||
}
|
}
|
||||||
|
|
||||||
j, err := json.Marshal(users)
|
j, _ := json.Marshal(users)
|
||||||
if err != nil {
|
|
||||||
log.Fatal(ctx, "Failed to encode users", err)
|
|
||||||
}
|
|
||||||
fmt.Printf("%s\n", j)
|
fmt.Printf("%s\n", j)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ package conf
|
||||||
import (
|
import (
|
||||||
"cmp"
|
"cmp"
|
||||||
"encoding"
|
"encoding"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
|
@ -393,7 +392,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("Error creating log file directory: " + mkErr.Error())
|
logFatal(fmt.Sprintf("Error creating log file directory: %s", 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 {
|
||||||
|
|
@ -729,7 +728,7 @@ func asWrittenInConfigFile(keys []string) []string {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// configFileKeyRx matches keys and section headers in all supported config formats.
|
// 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,
|
||||||
|
|
@ -864,7 +863,7 @@ func (s *Options) validateEnforceNonRootUser() error {
|
||||||
}
|
}
|
||||||
|
|
||||||
if getEUID() == 0 {
|
if getEUID() == 0 {
|
||||||
return errors.New("EnforceNonRootUser is enabled but Navidrome is running as root")
|
return fmt.Errorf("EnforceNonRootUser is enabled but Navidrome is running as root")
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|
|
||||||
|
|
@ -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()).ToNot(Succeed())
|
Expect(fn()).To(HaveOccurred())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("rejects a URL without a host", func() {
|
It("rejects a URL without a host", func() {
|
||||||
|
|
|
||||||
|
|
@ -213,10 +213,12 @@ var HTTPUserAgent = "Navidrome/" + Version + " - https://github.com/navidrome"
|
||||||
|
|
||||||
var (
|
var (
|
||||||
VariousArtists = "Various Artists"
|
VariousArtists = "Various Artists"
|
||||||
VariousArtistsID = "63sqASlAfjbGMuLP4JhnZU" // TODO This will be dynamic when using disambiguation
|
// TODO This will be dynamic when using disambiguation
|
||||||
|
VariousArtistsID = "63sqASlAfjbGMuLP4JhnZU"
|
||||||
UnknownAlbum = "[Unknown Album]"
|
UnknownAlbum = "[Unknown Album]"
|
||||||
UnknownArtist = "[Unknown Artist]"
|
UnknownArtist = "[Unknown Artist]"
|
||||||
UnknownArtistID = id.NewHash(strings.ToLower(UnknownArtist)) // TODO This will be dynamic when using disambiguation
|
// 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 = " • "
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// gitTag will be set in build time. If not, version will be set to "dev"
|
// This will be set in build time. If not, version will be set to "dev"
|
||||||
gitTag string
|
gitTag string
|
||||||
gitSha string
|
gitSha string
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -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(Succeed())
|
Expect(sk.Put(ctx, user.ID, "test-stored-value")).To(BeNil())
|
||||||
})
|
})
|
||||||
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(Succeed())
|
Expect(sk.Delete(ctx, user.ID)).To(BeNil())
|
||||||
})
|
})
|
||||||
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")
|
||||||
|
|
|
||||||
|
|
@ -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())
|
||||||
}
|
}
|
||||||
|
|
||||||
// zipAlbums writes the songs matching filters to out. rootArt, when set, is added to the archive root.
|
// 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
|
||||||
}
|
}
|
||||||
|
|
||||||
// albumDisambiguators are tried in order; the first one whose values are distinct across the clashing
|
// Tried in order; the first one whose values are distinct across the clashing albums wins.
|
||||||
// albums wins. One album may have an empty value: it keeps the plain name, which the others can't clash with.
|
// 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
// coverArtExtension takes the type from the image bytes, because resizing may re-encode the image.
|
// Resizing may re-encode the image, so the type comes from its bytes.
|
||||||
func coverArtExtension(data []byte) string {
|
func coverArtExtension(data []byte) string {
|
||||||
switch http.DetectContentType(data) {
|
switch http.DetectContentType(data) {
|
||||||
case "image/jpeg":
|
case "image/jpeg":
|
||||||
|
|
|
||||||
|
|
@ -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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
|
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
Expect(zr.File).To(HaveLen(2))
|
Expect(len(zr.File)).To(Equal(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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
|
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
Expect(zr.File).To(HaveLen(2))
|
Expect(len(zr.File)).To(Equal(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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
// 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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
Expect(zr.File).To(HaveLen(2))
|
Expect(len(zr.File)).To(Equal(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{
|
||||||
{Path: "test_data/01 - track1.flac", Suffix: "flac", Artist: "Artist 1", Title: "track1"},
|
{MediaFile: model.MediaFile{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{
|
||||||
{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/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "AC/DC", Title: "track1"}},
|
||||||
{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "Artist 2", Title: "track2"},
|
{MediaFile: model.MediaFile{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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
|
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
Expect(zr.File).To(HaveLen(3))
|
Expect(len(zr.File)).To(Equal(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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
defer m3uFile.Close()
|
defer m3uFile.Close()
|
||||||
|
|
||||||
m3uContent, err := io.ReadAll(m3uFile)
|
m3uContent, err := io.ReadAll(m3uFile)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
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{
|
||||||
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Artist: "Artist 1", Title: "track1"},
|
{MediaFile: model.MediaFile{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)
|
||||||
|
|
|
||||||
|
|
@ -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(readAll(img)).ToNot(BeEmpty())
|
Expect(len(readAll(img))).To(BeNumerically(">", 0))
|
||||||
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))
|
||||||
|
|
|
||||||
|
|
@ -15,14 +15,8 @@ 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 {
|
{"jpeg", func(tb testing.TB, w, h int) []byte { return generateJPEG(tb, w, h, 75) }},
|
||||||
tb.Helper()
|
{"png", func(tb testing.TB, w, h int) []byte { return generatePNG(tb, w, h) }},
|
||||||
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 {
|
||||||
|
|
|
||||||
|
|
@ -200,7 +200,7 @@ func (d *discArtworkReader) fromDiscSubtitle(ctx context.Context, subtitle strin
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// globMetaChars excludes filepath.Match's '\' escape on purpose: treating it as a metachar
|
// filepath.Match's '\' escape is excluded 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 = "*?["
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,14 +10,14 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// bits per channel: 4 is coarse enough that near-identical pixels land together, fine enough that
|
// 4 bits per channel: 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)
|
||||||
// maxBins caps the bins kept: only the heaviest can win, and merging is O(n^2) over whatever survives.
|
// Only the heaviest bins can win, and merging is O(n^2) over whatever survives.
|
||||||
maxBins = 64
|
maxBins = 64
|
||||||
// mergeDist is the Oklab distance below which two bins are the same colour to the eye. Merging matters
|
// Oklab distance below which two bins are the same colour to the eye. Merging matters because a
|
||||||
// because a gradient splits across adjacent bins and would otherwise lose to a smaller flat region.
|
// gradient splits across adjacent bins and would otherwise lose to a smaller flat region.
|
||||||
mergeDist = 0.10
|
mergeDist = 0.10
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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(readAll(img)).ToNot(BeEmpty())
|
Expect(len(readAll(img))).To(BeNumerically(">", 0))
|
||||||
})
|
})
|
||||||
|
|
||||||
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(provisionalBytes).ToNot(BeEmpty())
|
Expect(len(provisionalBytes)).To(BeNumerically(">", 0))
|
||||||
|
|
||||||
_, 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")
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ package e2e
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"strconv"
|
|
||||||
"testing/fstest"
|
"testing/fstest"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/conf"
|
"github.com/navidrome/navidrome/conf"
|
||||||
|
|
@ -275,7 +274,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": strconv.Itoa(discNum)})
|
layout[prefix+"01 - Track.mp3"] = trackFile(1, fmt.Sprintf("T%d", discNum), map[string]any{"disc": fmt.Sprintf("%d", 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)
|
||||||
|
|
@ -314,7 +313,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": strconv.Itoa(i)})
|
layout[prefix+"01 - Track.mp3"] = trackFile(1, fmt.Sprintf("T%d", i), map[string]any{"disc": fmt.Sprintf("%d", 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)
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ package e2e
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"hash/fnv"
|
"hash/fnv"
|
||||||
"image"
|
"image"
|
||||||
|
|
@ -118,7 +117,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, errors.New("resize not exercised in e2e")
|
return nil, fmt.Errorf("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())
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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, "", errors.New("artist folder lookup unavailable")
|
return nil, "", fmt.Errorf("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)) {
|
||||||
|
|
|
||||||
|
|
@ -45,8 +45,6 @@ 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"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -180,9 +180,8 @@ func chainFetchesExternal(priority string) bool {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// fetchExternalAlbum and fetchExternalArtist are where album and artist fetches stop when the resolver is
|
// Album and artist fetches stop here when the resolver is local-only, rather than at each point in
|
||||||
// local-only, rather than at each point in the chain walk; resolvePlaylist gates the third network path,
|
// the chain walk; resolvePlaylist gates the third network path, the m3u image URL, itself.
|
||||||
// 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
|
||||||
|
|
|
||||||
|
|
@ -56,7 +56,7 @@ func fromExternalFile(ctx context.Context, libFS fs.FS, files []string, pattern
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// picTypeRegexes match the picture type in the file, in the order they are listed.
|
// These regexes are used to 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.*`),
|
||||||
|
|
|
||||||
|
|
@ -230,7 +230,7 @@ func pack(w, h int, hasAlpha bool, lx, ly int,
|
||||||
return hash
|
return hash
|
||||||
}
|
}
|
||||||
|
|
||||||
// toNRGBA returns NRGBA, not RGBA: ThumbHash requires non-premultiplied RGB and the pipeline hands us a
|
// 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
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,6 @@ import (
|
||||||
"slices"
|
"slices"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/log"
|
|
||||||
"github.com/navidrome/navidrome/utils/str"
|
"github.com/navidrome/navidrome/utils/str"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -95,10 +94,7 @@ 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, err := json.Marshal(out)
|
b, _ := json.Marshal(out) // []storedStep is all strings, so this cannot fail
|
||||||
if err != nil {
|
|
||||||
log.Error("Artwork: Could not encode resolution trace", err)
|
|
||||||
}
|
|
||||||
return string(b)
|
return string(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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(BeTrue())
|
Expect(claims.IsAdmin).To(Equal(true))
|
||||||
Expect(claims.ExpiresAt).To(BeTemporally(">", time.Now()))
|
Expect(claims.ExpiresAt).To(BeTemporally(">", time.Now()))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,6 @@ 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 {
|
||||||
|
|
|
||||||
6
core/external/provider.go
vendored
6
core/external/provider.go
vendored
|
|
@ -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 := gg.V(album.ExternalInfoUpdatedAt)
|
updatedAt := 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 := gg.V(artist.ExternalInfoUpdatedAt)
|
updatedAt := 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)
|
||||||
|
|
|
||||||
4
core/external/provider_similarsongs.go
vendored
4
core/external/provider_similarsongs.go
vendored
|
|
@ -19,8 +19,8 @@ import (
|
||||||
|
|
||||||
const (
|
const (
|
||||||
maxSeeds = 5
|
maxSeeds = 5
|
||||||
// maxSimilarSongs caps the client's count, which Subsonic passes through unbounded and ends up as a SQL
|
// Subsonic passes the client's count through unbounded, and it ends up as a SQL limit. 500 is
|
||||||
// limit. 500 is what the widest caller (similarAlbums, limit*5) legitimately asks for.
|
// what the widest caller (similarAlbums, limit*5) legitimately asks for.
|
||||||
maxSimilarSongs = 500
|
maxSimilarSongs = 500
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
||||||
8
core/external/provider_topsongs_test.go
vendored
8
core/external/provider_topsongs_test.go
vendored
|
|
@ -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{
|
||||||
{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"},
|
{Artist: model.Artist{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{
|
||||||
{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"},
|
{Artist: model.Artist{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{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}
|
participant1 := model.Participant{Artist: model.Artist{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{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}
|
participant1 := model.Participant{Artist: model.Artist{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}},
|
||||||
|
|
|
||||||
|
|
@ -293,7 +293,7 @@ func parseProbeOutput(data []byte) (*AudioProbeResult, error) {
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, errors.New("no audio stream found in ffprobe output")
|
return nil, fmt.Errorf("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 {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// createFFmpegCommand expects path to always be an absolute path
|
// Path will 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,7 +643,6 @@ 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)
|
||||||
|
|
|
||||||
|
|
@ -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")
|
||||||
t.Chdir(appPath)
|
_ = os.Chdir(appPath)
|
||||||
conf.LoadFromFile(confPath)
|
conf.LoadFromFile(confPath)
|
||||||
log.SetLevel(log.LevelFatal)
|
log.SetLevel(log.LevelFatal)
|
||||||
RegisterFailHandler(Fail)
|
RegisterFailHandler(Fail)
|
||||||
|
|
|
||||||
|
|
@ -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 errors.New("user not found in context")
|
return fmt.Errorf("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.Put(ctx, lib)
|
err := r.LibraryRepository.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.Put(ctx, lib, cols...)
|
err = r.LibraryRepository.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 errors.New("library path must be absolute")
|
return fmt.Errorf("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 errors.New("resources.library.validation.pathNotDirectory")
|
return fmt.Errorf("resources.library.validation.pathNotDirectory")
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,6 @@ 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
|
||||||
|
|
@ -499,7 +498,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(BeEmpty())
|
Expect(libraryRepo.Data).To(HaveLen(0))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("fails when library doesn't exist", func() {
|
It("fails when library doesn't exist", func() {
|
||||||
|
|
@ -658,7 +657,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()
|
||||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
}, "1s", "10ms").Should(Equal(1))
|
||||||
|
|
||||||
// Verify scan was called with correct parameters
|
// Verify scan was called with correct parameters
|
||||||
calls := scanner.GetScanAllCalls()
|
calls := scanner.GetScanAllCalls()
|
||||||
|
|
@ -684,7 +683,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()
|
||||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
}, "1s", "10ms").Should(Equal(1))
|
||||||
|
|
||||||
// Verify scan was called with correct parameters
|
// Verify scan was called with correct parameters
|
||||||
calls := scanner.GetScanAllCalls()
|
calls := scanner.GetScanAllCalls()
|
||||||
|
|
@ -705,7 +704,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()
|
||||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
}, "100ms", "10ms").Should(Equal(0))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("triggers scan when updating the library PID config", func() {
|
It("triggers scan when updating the library PID config", func() {
|
||||||
|
|
@ -716,7 +715,7 @@ var _ = Describe("Library Service", func() {
|
||||||
|
|
||||||
Eventually(func() int {
|
Eventually(func() int {
|
||||||
return scanner.GetScanAllCallCount()
|
return scanner.GetScanAllCallCount()
|
||||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
}, "1s", "10ms").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())
|
||||||
})
|
})
|
||||||
|
|
@ -730,7 +729,7 @@ var _ = Describe("Library Service", func() {
|
||||||
|
|
||||||
Consistently(func() int {
|
Consistently(func() int {
|
||||||
return scanner.GetScanAllCallCount()
|
return scanner.GetScanAllCallCount()
|
||||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
}, "100ms", "10ms").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() {
|
||||||
|
|
@ -742,12 +741,12 @@ var _ = Describe("Library Service", func() {
|
||||||
|
|
||||||
Consistently(func() int {
|
Consistently(func() int {
|
||||||
return scanner.GetScanAllCallCount()
|
return scanner.GetScanAllCallCount()
|
||||||
}, 200*time.Millisecond, 20*time.Millisecond).Should(Equal(0))
|
}, "200ms", "20ms").Should(Equal(0))
|
||||||
|
|
||||||
scanner.SetScanning(false)
|
scanner.SetScanning(false)
|
||||||
Eventually(func() int {
|
Eventually(func() int {
|
||||||
return scanner.GetScanAllCallCount()
|
return scanner.GetScanAllCallCount()
|
||||||
}, 3*time.Second, 20*time.Millisecond).Should(Equal(1))
|
}, "3s", "20ms").Should(Equal(1))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("does not trigger scan when library creation fails", func() {
|
It("does not trigger scan when library creation fails", func() {
|
||||||
|
|
@ -760,7 +759,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()
|
||||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
}, "100ms", "10ms").Should(Equal(0))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("does not trigger scan when library update fails", func() {
|
It("does not trigger scan when library update fails", func() {
|
||||||
|
|
@ -777,7 +776,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()
|
||||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
}, "100ms", "10ms").Should(Equal(0))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("triggers scan when deleting a library", func() {
|
It("triggers scan when deleting a library", func() {
|
||||||
|
|
@ -793,7 +792,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()
|
||||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
}, "1s", "10ms").Should(Equal(1))
|
||||||
|
|
||||||
// Verify scan was called with correct parameters
|
// Verify scan was called with correct parameters
|
||||||
calls := scanner.GetScanAllCalls()
|
calls := scanner.GetScanAllCalls()
|
||||||
|
|
@ -808,7 +807,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()
|
||||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
}, "100ms", "10ms").Should(Equal(0))
|
||||||
})
|
})
|
||||||
|
|
||||||
Context("Watcher Integration", func() {
|
Context("Watcher Integration", func() {
|
||||||
|
|
@ -821,7 +820,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()
|
||||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
}, "1s", "10ms").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"))
|
||||||
|
|
@ -850,7 +849,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()
|
||||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
}, "1s", "10ms").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))
|
||||||
|
|
@ -870,7 +869,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()
|
||||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
}, "100ms", "10ms").Should(Equal(0))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("stops watcher when library is deleted", func() {
|
It("stops watcher when library is deleted", func() {
|
||||||
|
|
@ -885,7 +884,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()
|
||||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
}, "1s", "10ms").Should(Equal(1))
|
||||||
|
|
||||||
Expect(watcherManager.StoppedWatchers[0]).To(Equal(1))
|
Expect(watcherManager.StoppedWatchers[0]).To(Equal(1))
|
||||||
})
|
})
|
||||||
|
|
@ -903,7 +902,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()
|
||||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
}, "100ms", "10ms").Should(Equal(0))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@ package lyrics_test
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"fmt"
|
||||||
"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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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 = errors.New("plugin error")
|
mockLoader.err = fmt.Errorf("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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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 = errors.New("no lyrics found from any provider")
|
mockLoader.err = fmt.Errorf("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())
|
||||||
|
|
|
||||||
|
|
@ -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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
Expect(lyrics).To(BeEmpty())
|
Expect(lyrics).To(HaveLen(0))
|
||||||
})
|
})
|
||||||
|
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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(BeEmpty())
|
Expect(lyrics).To(HaveLen(0))
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).ToNot(BeNil())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
Expect(lyrics).To(BeEmpty())
|
Expect(lyrics).To(HaveLen(0))
|
||||||
})
|
})
|
||||||
|
|
||||||
// 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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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())
|
||||||
|
|
|
||||||
|
|
@ -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()
|
||||||
|
|
|
||||||
|
|
@ -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{
|
||||||
ID: "a1", Name: "Artist", OrderArtistName: "artist", MbzArtistID: "mbz-artist",
|
Artist: model.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},
|
||||||
|
|
|
||||||
|
|
@ -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{
|
||||||
{ID: "a-bjork", Name: "Björk", OrderArtistName: "bjork"},
|
{Artist: model.Artist{ID: "a-bjork", Name: "Björk", OrderArtistName: "bjork"}},
|
||||||
},
|
},
|
||||||
model.RoleAlbumArtist: model.ParticipantList{
|
model.RoleAlbumArtist: model.ParticipantList{
|
||||||
{ID: "a-808", Name: "808 State", OrderArtistName: "808 state"},
|
{Artist: model.Artist{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",
|
||||||
Starred: true,
|
Annotations: model.Annotations{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",
|
||||||
Starred: true,
|
Annotations: model.Annotations{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",
|
||||||
Rating: 4,
|
Annotations: model.Annotations{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",
|
||||||
Starred: true,
|
Annotations: model.Annotations{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})
|
||||||
|
|
|
||||||
|
|
@ -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, http.MethodPost, consts.InsightsEndpoint, body)
|
req, err := http.NewRequestWithContext(ctx, "POST", 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
|
||||||
|
|
|
||||||
|
|
@ -24,11 +24,11 @@ func getOSVersion() (string, string) {
|
||||||
version := ""
|
version := ""
|
||||||
distro := ""
|
distro := ""
|
||||||
for _, line := range lines {
|
for _, line := range lines {
|
||||||
if v, ok := strings.CutPrefix(line, "VERSION_ID="); ok {
|
if strings.HasPrefix(line, "VERSION_ID=") {
|
||||||
version = strings.ReplaceAll(v, "\"", "")
|
version = strings.ReplaceAll(strings.TrimPrefix(line, "VERSION_ID="), "\"", "")
|
||||||
}
|
}
|
||||||
if v, ok := strings.CutPrefix(line, "ID="); ok {
|
if strings.HasPrefix(line, "ID=") {
|
||||||
distro = strings.ReplaceAll(v, "\"", "")
|
distro = strings.ReplaceAll(strings.TrimPrefix(line, "ID="), "\"", "")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return version, distro
|
return version, distro
|
||||||
|
|
|
||||||
|
|
@ -117,7 +117,7 @@ type prometheusMetrics struct {
|
||||||
pluginRequestDuration *prometheus.SummaryVec
|
pluginRequestDuration *prometheus.SummaryVec
|
||||||
}
|
}
|
||||||
|
|
||||||
// getPrometheusMetrics initializes Prometheus' metrics, which must not happen more than once
|
// Prometheus' metrics requires initialization. But not 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}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,6 @@ import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strconv"
|
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/core/playback/mpv"
|
"github.com/navidrome/navidrome/core/playback/mpv"
|
||||||
|
|
@ -223,7 +222,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: "+strconv.Itoa(index))
|
log.Error(ctx, "Index to remove out of range: "+fmt.Sprint(index))
|
||||||
}
|
}
|
||||||
return pd.getStatus(), nil
|
return pd.getStatus(), nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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{}, errors.New("no command arguments provided")
|
return Executor{}, fmt.Errorf("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 errors.New("there is non command to cancel")
|
return fmt.Errorf("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()
|
||||||
}
|
}
|
||||||
|
|
||||||
// createMPVCommand expects filename to always be an absolute path
|
// Path will 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
|
||||||
}
|
}
|
||||||
|
|
||||||
// mpvCommand is a 1:1 copy of the stuff in ffmpeg.go, need to be unified.
|
// This 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 != "" {
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,6 @@ package mpv
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
@ -37,7 +36,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, errors.New("no mpv command arguments provided")
|
return nil, fmt.Errorf("no mpv command arguments provided")
|
||||||
}
|
}
|
||||||
exe, err := start(ctx, args)
|
exe, err := start(ctx, args)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -77,7 +76,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetVolume controls the playback volume. A float value between 0.0 and 1.0.
|
// Used to control 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.
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,6 @@ package playback
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/conf"
|
"github.com/navidrome/navidrome/conf"
|
||||||
|
|
@ -107,7 +106,7 @@ func (ps *playbackServer) getDefaultDevice() (*playbackDevice, error) {
|
||||||
return &ps.playbackDevices[idx], nil
|
return &ps.playbackDevices[idx], nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil, errors.New("no default device found")
|
return nil, fmt.Errorf("no default device found")
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetMediaFile retrieves the MediaFile given by the id parameter
|
// GetMediaFile retrieves the MediaFile given by the id parameter
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ package playback
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/log"
|
"github.com/navidrome/navidrome/log"
|
||||||
|
|
@ -25,12 +24,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(strconv.Itoa(idx) + ":" + item.Path + " ")
|
filenames.WriteString(fmt.Sprint(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())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Current returns the current mediafile or nil
|
// 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
|
||||||
|
|
@ -43,7 +42,7 @@ func (pd *Queue) Current() *model.MediaFile {
|
||||||
return &pd.Items[pd.Index]
|
return &pd.Items[pd.Index]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get returns the whole queue
|
// returns the whole queue
|
||||||
func (pd *Queue) Get() model.MediaFiles {
|
func (pd *Queue) Get() model.MediaFiles {
|
||||||
return pd.Items
|
return pd.Items
|
||||||
}
|
}
|
||||||
|
|
@ -56,13 +55,13 @@ func (pd *Queue) IsEmpty() bool {
|
||||||
return len(pd.Items) < 1
|
return len(pd.Items) < 1
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set is similar to a clear followed by an add, but will not change the currently playing track.
|
// set is similar to a clear followed by a 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...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add appends mediafiles to the queue
|
// adding 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 {
|
||||||
|
|
@ -70,13 +69,13 @@ func (pd *Queue) Add(items model.MediaFiles) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear empties the whole queue
|
// empties whole queue
|
||||||
func (pd *Queue) Clear() {
|
func (pd *Queue) Clear() {
|
||||||
pd.Index = -1
|
pd.Index = -1
|
||||||
pd.Items = nil
|
pd.Items = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove removes the song at idx, a zero-based index.
|
// idx Zero-based index of the song to skip to or remove.
|
||||||
func (pd *Queue) Remove(idx int) {
|
func (pd *Queue) Remove(idx int) {
|
||||||
current := pd.Current()
|
current := pd.Current()
|
||||||
backupID := ""
|
backupID := ""
|
||||||
|
|
@ -120,18 +119,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetIndex sets the index to a new, valid value inside the Items. Values lower than zero are going to be
|
// Sets the index to a new, valid value inside the Items. Values lower than zero are going to be zero,
|
||||||
// zero, values above will be limited by number of items.
|
// 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))
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsAtLastElement reports whether we are at the last track.
|
// Are we 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
// IncreaseIndex moves to the next index, unless at the last track.
|
// Goto next index
|
||||||
func (pd *Queue) IncreaseIndex() {
|
func (pd *Queue) IncreaseIndex() {
|
||||||
if !pd.IsAtLastElement() {
|
if !pd.IsAtLastElement() {
|
||||||
pd.SetIndex(pd.Index + 1)
|
pd.SetIndex(pd.Index + 1)
|
||||||
|
|
|
||||||
|
|
@ -71,7 +71,7 @@ func (s *playlists) ImportFile(ctx context.Context, absolutePath string, sync bo
|
||||||
return pls, nil
|
return pls, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var errNotInLibrary = errors.New("path not in any library")
|
var errNotInLibrary = fmt.Errorf("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)
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ package playlists
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
|
@ -145,7 +144,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 "", errors.New("invalid path resolution")
|
return "", fmt.Errorf("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 {
|
||||||
|
|
|
||||||
|
|
@ -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"
|
||||||
|
|
@ -190,22 +190,15 @@ 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)
|
||||||
// Indexes refer to GetWithTracks' list, which hides missing and inaccessible-library tracks.
|
// Convert 0-based indices to 1-based position IDs and delete them directly,
|
||||||
visible, err := tracksRepo.GetPositionIDs(ctx, model.QueryOptions{Sort: "id", Filters: squirrel.Eq{"missing": false}})
|
// avoiding the need to load all tracks into memory.
|
||||||
if err != nil {
|
positions := make([]string, len(idxToRemove))
|
||||||
return err
|
for i, idx := range idxToRemove {
|
||||||
|
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
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,7 @@ import (
|
||||||
|
|
||||||
const timeout = 10 * time.Minute
|
const timeout = 10 * time.Minute
|
||||||
|
|
||||||
// maxPending bounds the number of live requests, because Initiate is unauthenticated.
|
// Initiate is unauthenticated, so the number of live requests must be bounded.
|
||||||
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{
|
||||||
Device: device, Secret: newSecret(), Code: qc.newCode(), DateAdded: now,
|
Request: Request{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)
|
||||||
}
|
}
|
||||||
|
|
||||||
// normalizeCode removes whitespace: users often type the code in groups ("123 456").
|
// 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), "")
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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{ID: "1", TimeStamp: time.Now()})
|
_ = bs.Scrobble(t.Context(), "user1", Scrobble{MediaFile: model.MediaFile{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{ID: "2", TimeStamp: time.Now()})
|
_ = bs.Scrobble(t.Context(), "user1", Scrobble{MediaFile: model.MediaFile{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{ID: "1", TimeStamp: time.Now()})
|
_ = bs.Scrobble(t.Context(), "user1", Scrobble{MediaFile: model.MediaFile{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)
|
||||||
|
|
|
||||||
|
|
@ -532,7 +532,7 @@ func (p *playTracker) incPlay(ctx context.Context, track *model.MediaFile, times
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// isFilteredOut must take its verdict before incPlay mutates what a filter reads, and independently of
|
// Take this 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 {
|
||||||
|
|
|
||||||
|
|
@ -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(BeEmpty())
|
Expect(mockScrobble.RecordedScrobbles).To(HaveLen(0))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
@ -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{ID: id, Name: name}
|
p := model.Participant{Artist: model.Artist{ID: id, Name: name}}
|
||||||
if len(sortName) > 0 {
|
if len(sortName) > 0 {
|
||||||
p.SortArtistName = sortName[0]
|
p.Artist.SortArtistName = sortName[0]
|
||||||
}
|
}
|
||||||
return p
|
return p
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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 := gg.V(share.ExpiresAt)
|
expiresAt := 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 gg.V(s.ExpiresAt).IsZero() {
|
if 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.SplitSeq(resourceIDs, ",") {
|
for _, id := range strings.Split(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 !gg.V(entity.ExpiresAt).IsZero() {
|
if !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...)
|
||||||
|
|
|
||||||
|
|
@ -134,8 +134,7 @@ 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, err := json.Marshal(tags)
|
data, _ := json.Marshal(tags)
|
||||||
gomega.Expect(err).ToNot(gomega.HaveOccurred())
|
|
||||||
f.Data = data
|
f.Data = data
|
||||||
ffs.Touch(filePath, when...)
|
ffs.Touch(filePath, when...)
|
||||||
}
|
}
|
||||||
|
|
@ -209,8 +208,7 @@ 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, err := json.Marshal(ts)
|
data, _ := 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))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -61,16 +61,14 @@ 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(src *Details, targetIsLossless bool) int {
|
func targetBitDepth(srcBitDepth int, srcCodec string, targetIsLossless bool) int {
|
||||||
switch {
|
if !targetIsLossless {
|
||||||
case !targetIsLossless:
|
|
||||||
return 0
|
return 0
|
||||||
case strings.EqualFold(src.Codec, "dsd"):
|
|
||||||
return 24
|
|
||||||
case !src.IsLossless:
|
|
||||||
return 16 // the most widely supported depth
|
|
||||||
}
|
}
|
||||||
return src.BitDepth
|
if strings.EqualFold(srcCodec, "dsd") {
|
||||||
|
return 24
|
||||||
|
}
|
||||||
|
return srcBitDepth
|
||||||
}
|
}
|
||||||
|
|
||||||
// codecFixedOutputSampleRate returns the mandatory output sample rate for codecs
|
// codecFixedOutputSampleRate returns the mandatory output sample rate for codecs
|
||||||
|
|
|
||||||
|
|
@ -257,12 +257,9 @@ func (s *deciderService) computeTranscodedStream(ctx context.Context, src *Detai
|
||||||
|
|
||||||
targetIsLossless := isLosslessFormat(targetFormat)
|
targetIsLossless := isLosslessFormat(targetFormat)
|
||||||
|
|
||||||
lossyToLossless := !src.IsLossless && targetIsLossless
|
// Reject lossy to lossless conversion
|
||||||
// Lossless output from a lossy source is far larger than the source, so no bitrate cap can be honored
|
if !src.IsLossless && targetIsLossless {
|
||||||
lossyToLosslessAllowed := clientInfo.AllowLossyToLossless && clientInfo.MaxAudioBitrate == 0
|
log.Trace(ctx, "Skipping transcoding profile: lossy to lossless not allowed", "targetFormat", targetFormat)
|
||||||
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, ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -277,7 +274,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, targetIsLossless),
|
BitDepth: targetBitDepth(src.BitDepth, src.Codec, targetIsLossless),
|
||||||
IsLossless: targetIsLossless,
|
IsLossless: targetIsLossless,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -389,7 +386,7 @@ func (s *deciderService) computeBitrate(ctx context.Context, src *Details, targe
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if !targetIsLossless {
|
} else {
|
||||||
ts.Bitrate = src.Bitrate
|
ts.Bitrate = src.Bitrate
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@ package stream
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"fmt"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/conf"
|
"github.com/navidrome/navidrome/conf"
|
||||||
"github.com/navidrome/navidrome/core/auth"
|
"github.com/navidrome/navidrome/core/auth"
|
||||||
|
|
@ -26,8 +26,7 @@ func withProbe(mf *model.MediaFile) *model.MediaFile {
|
||||||
BitDepth: gg.V(mf.BitDepth),
|
BitDepth: gg.V(mf.BitDepth),
|
||||||
Channels: mf.Channels,
|
Channels: mf.Channels,
|
||||||
}
|
}
|
||||||
data, err := json.Marshal(probe)
|
data, _ := json.Marshal(probe)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
|
||||||
mf.ProbeData = string(data)
|
mf.ProbeData = string(data)
|
||||||
return mf
|
return mf
|
||||||
}
|
}
|
||||||
|
|
@ -1282,7 +1281,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 = errors.New("should not be called")
|
ff.Error = fmt.Errorf("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)
|
||||||
|
|
@ -1292,7 +1291,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 = errors.New("ffprobe not found")
|
ff.Error = fmt.Errorf("ffprobe not found")
|
||||||
|
|
||||||
svc := NewTranscodeDecider(ds, ff).(*deciderService)
|
svc := NewTranscodeDecider(ds, ff).(*deciderService)
|
||||||
_, err := svc.ensureProbed(ctx, mf)
|
_, err := svc.ensureProbed(ctx, mf)
|
||||||
|
|
|
||||||
|
|
@ -42,7 +42,6 @@ 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
|
||||||
|
|
|
||||||
|
|
@ -285,16 +285,6 @@ 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})
|
||||||
|
|
||||||
|
|
@ -305,40 +295,6 @@ 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)})
|
||||||
|
|
|
||||||
|
|
@ -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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
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() }, 3*time.Second).Should(BeTrue())
|
Eventually(func() bool { return ffmpeg.IsClosed() }, "3s").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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
_, _ = io.ReadAll(s)
|
_, _ = io.ReadAll(s)
|
||||||
_ = s.Close()
|
_ = s.Close()
|
||||||
Eventually(func() bool { return ffmpeg.IsClosed() }, 3*time.Second).Should(BeTrue())
|
Eventually(func() bool { return ffmpeg.IsClosed() }, "3s").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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
Expect(s.Seekable()).To(BeTrue())
|
Expect(s.Seekable()).To(BeTrue())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -38,9 +38,6 @@ 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,
|
||||||
|
|
|
||||||
|
|
@ -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 errors.New("error trying to convert destination to sqlite connection")
|
return fmt.Errorf("error trying to convert destination to sqlite connection")
|
||||||
}
|
}
|
||||||
sqliteSource, sourceOk := rawSource.(*sqlite3.SQLiteConn)
|
sqliteSource, sourceOk := rawSource.(*sqlite3.SQLiteConn)
|
||||||
if !sourceOk {
|
if !sourceOk {
|
||||||
return errors.New("error trying to convert source to sqlite connection")
|
return fmt.Errorf("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 errors.New("backup not done with step -1")
|
return fmt.Errorf("backup not done with step -1")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = backupOp.Finish()
|
err = backupOp.Finish()
|
||||||
|
|
|
||||||
4
db/db.go
4
db/db.go
|
|
@ -34,8 +34,8 @@ var embedMigrations embed.FS
|
||||||
|
|
||||||
const migrationsFolder = "migrations"
|
const migrationsFolder = "migrations"
|
||||||
|
|
||||||
// registerDriverOnce guards sql.Register, which panics if called twice: the singleton instance can be
|
// sql.Register panics if called twice, so guard it: the singleton instance can be reset
|
||||||
// reset (tests/benchmarks) and rebuilt, but the driver is process-global and registers only once.
|
// (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 {
|
||||||
|
|
|
||||||
|
|
@ -126,10 +126,9 @@ create index folder_parent_id on folder(parent_id);
|
||||||
`)
|
`)
|
||||||
}
|
}
|
||||||
|
|
||||||
// upSupportNewScanner_PopulateTableFolder uses paths from `media_file` table to populate `folder` table.
|
// Use paths from `media_file` table to populate `folder` table. The `folder` table must contain all paths, including
|
||||||
// The `folder` table must contain all paths, including the ones that do not contain any media_file. We can
|
// the ones that do not contain any media_file. We can get all paths from the media_file table to populate a
|
||||||
// get all paths from the media_file table to populate a fstest.MapFS{}, and then walk the filesystem to
|
// fstest.MapFS{}, and then walk the filesystem to insert all folders into the DB, including empty parent ones.
|
||||||
// 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
|
||||||
|
|
|
||||||
|
|
@ -13,10 +13,10 @@ func init() {
|
||||||
goose.AddMigrationContext(upBackfillArtistSearchNormalized, downBackfillArtistSearchNormalized)
|
goose.AddMigrationContext(upBackfillArtistSearchNormalized, downBackfillArtistSearchNormalized)
|
||||||
}
|
}
|
||||||
|
|
||||||
// upBackfillArtistSearchNormalized recomputes artist.search_normalized in Go. The FTS5 migration
|
// The FTS5 migration back-filled artist.search_normalized with a SQL approximation that
|
||||||
// back-filled it with a SQL approximation that cannot transliterate atomic letters (Ø, æ, ß, ...),
|
// cannot transliterate atomic letters (Ø, æ, ß, ...), and the scanner never rewrote the
|
||||||
// and the scanner never rewrote the column, leaving artists like "GØGGS" unfindable by ASCII
|
// column, leaving artists like "GØGGS" unfindable by ASCII searches. Recompute it in Go;
|
||||||
// searches. The artist_fts update trigger re-indexes every row that changes.
|
// 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.")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -93,7 +93,7 @@ var _ = Describe("idColumns inventory", func() {
|
||||||
}
|
}
|
||||||
dangling = append(dangling, key)
|
dangling = append(dangling, key)
|
||||||
}
|
}
|
||||||
Expect(rows.Err()).To(Succeed())
|
Expect(rows.Err()).ToNot(HaveOccurred())
|
||||||
Expect(rows.Close()).To(Succeed())
|
Expect(rows.Close()).To(Succeed())
|
||||||
}
|
}
|
||||||
Expect(dangling).To(BeEmpty(),
|
Expect(dangling).To(BeEmpty(),
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,7 @@ import (
|
||||||
"github.com/navidrome/navidrome/log"
|
"github.com/navidrome/navidrome/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
// notice is for migrations that need to communicate something important (breaking changes, forced
|
// Use this in migrations that need to communicate something important (breaking changes, forced reindexes, etc...)
|
||||||
// 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)
|
||||||
|
|
@ -20,7 +19,7 @@ func notice(ctx context.Context, tx *sql.Tx, msg string) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// forceFullRescan is for migrations that require a full rescan
|
// Call this in migrations that requires 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');
|
||||||
|
|
@ -65,8 +64,8 @@ func createExecuteFunc(ctx context.Context, tx *sql.Tx) execStmtFunc {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// createAddColumnFunc is a hack to add a new `not null` column to a table, setting the initial value for
|
// Hack way to add a new `not null` column to a table, setting the initial value for existing rows based on a
|
||||||
// existing rows based on a SQL expression. It is done in 3 steps:
|
// 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
|
||||||
|
|
@ -77,7 +76,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(defaultValue + " not")
|
finalLen := len(fmt.Sprintf(`%s not`, defaultValue))
|
||||||
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))
|
||||||
|
|
|
||||||
|
|
@ -144,9 +144,8 @@ func optimizeAt(ctx context.Context, db *sql.DB, now time.Time) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// analyzeTargetsSQL picks one ANALYZE target per index (whole table if WITHOUT ROWID or lacking a
|
// One ANALYZE per index (whole table if WITHOUT ROWID or lacking a non-partial index) yields the
|
||||||
// non-partial index). That yields the same sqlite_stat1 rows as a full ANALYZE, but frees the write lock
|
// same sqlite_stat1 rows as a full ANALYZE, but frees the write lock between steps.
|
||||||
// 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)
|
||||||
|
|
|
||||||
|
|
@ -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()).To(Succeed())
|
Expect(rows.Err()).ToNot(HaveOccurred())
|
||||||
return schema
|
return schema
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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(http.MethodGet, "/", nil).WithContext(ctx)
|
req := httptest.NewRequest("get", "/", 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).To(HaveOccurred())
|
Expect(err).ToNot(BeNil())
|
||||||
})
|
})
|
||||||
|
|
||||||
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).To(HaveOccurred())
|
Expect(err).ToNot(BeNil())
|
||||||
})
|
})
|
||||||
|
|
||||||
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(http.MethodGet, "/", nil).WithContext(ctx)
|
req := httptest.NewRequest("get", "/", nil).WithContext(ctx)
|
||||||
|
|
||||||
Expect(extractLogger(req)).To(Equal(logger))
|
Expect(extractLogger(req)).To(Equal(logger))
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -33,11 +33,13 @@ func TestLevels(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
fn := 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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -52,7 +54,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 int(l) >= len(logrus.AllLevels) {
|
if l < 0 || int(l) > len(logrus.AllLevels) {
|
||||||
return []logrus.Level{}
|
return []logrus.Level{}
|
||||||
}
|
}
|
||||||
return logrus.AllLevels[:l+1]
|
return logrus.AllLevels[:l+1]
|
||||||
|
|
@ -66,12 +68,6 @@ 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,
|
||||||
|
|
@ -81,10 +77,12 @@ func TestLevelThreshold(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
fn := 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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -132,7 +130,7 @@ func TestEntryDataValues(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
fn := func(t *testing.T) {
|
||||||
logEntry := &logrus.Entry{
|
logEntry := &logrus.Entry{
|
||||||
Data: test.logFields,
|
Data: test.logFields,
|
||||||
}
|
}
|
||||||
|
|
@ -141,7 +139,8 @@ 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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
|
|
||||||
var albums2 Albums
|
var albums2 Albums
|
||||||
err = json.Unmarshal(data, &albums2)
|
err = json.Unmarshal(data, &albums2)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).To(BeNil())
|
||||||
Expect(albums2).To(Equal(albums))
|
Expect(albums2).To(Equal(albums))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -117,8 +117,7 @@ const (
|
||||||
ArtworkPriorityBump = 100
|
ArtworkPriorityBump = 100
|
||||||
)
|
)
|
||||||
|
|
||||||
// ArtworkRepository stores the artwork images. Delete* takes the rows to remove; Purge* finds them itself
|
// Delete* takes the rows to remove; Purge* finds them itself and reports how many went.
|
||||||
// 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
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -19,9 +19,9 @@ func jsonOf(v any) map[string]any {
|
||||||
|
|
||||||
var _ = Describe("ItemImage JSON", func() {
|
var _ = Describe("ItemImage JSON", func() {
|
||||||
It("exposes the artwork state a client needs to render a placeholder", func() {
|
It("exposes the artwork state a client needs to render a placeholder", func() {
|
||||||
al := model.Album{ID: "al-1", Name: "Album",
|
al := model.Album{ID: "al-1", Name: "Album"}
|
||||||
ImageHash: "0123456789abcdef",
|
al.ImageHash = "0123456789abcdef"
|
||||||
ThumbHash: "1QcSHQRn"}
|
al.ThumbHash = "1QcSHQRn"
|
||||||
al.ImageWidth, al.ImageHeight = 1200, 800
|
al.ImageWidth, al.ImageHeight = 1200, 800
|
||||||
|
|
||||||
Expect(jsonOf(al)).To(SatisfyAll(
|
Expect(jsonOf(al)).To(SatisfyAll(
|
||||||
|
|
@ -33,8 +33,8 @@ var _ = Describe("ItemImage JSON", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("keeps the blurhash off the native API, where nothing consumes it", func() {
|
It("keeps the blurhash off the native API, where nothing consumes it", func() {
|
||||||
al := model.Album{ID: "al-1", Name: "Album",
|
al := model.Album{ID: "al-1", Name: "Album"}
|
||||||
BlurHash: "LEHV6nWB2yk8"}
|
al.BlurHash = "LEHV6nWB2yk8"
|
||||||
Expect(jsonOf(al)).ToNot(HaveKey("blurHash"))
|
Expect(jsonOf(al)).ToNot(HaveKey("blurHash"))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -48,8 +48,8 @@ var _ = Describe("ItemImage JSON", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("exposes known-absent artwork so clients can skip the request", func() {
|
It("exposes known-absent artwork so clients can skip the request", func() {
|
||||||
ar := model.Artist{ID: "ar-1", Name: "Artist",
|
ar := model.Artist{ID: "ar-1", Name: "Artist"}
|
||||||
ImageAbsent: true}
|
ar.ImageAbsent = true
|
||||||
Expect(jsonOf(ar)).To(HaveKeyWithValue("imageAbsent", true))
|
Expect(jsonOf(ar)).To(HaveKeyWithValue("imageAbsent", true))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue