mirror of
https://github.com/navidrome/navidrome.git
synced 2026-11-17 07:38:46 +01:00
Compare commits
30 commits
artwork-ex
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
110567aaca |
||
|
|
1286fdfc9c |
||
|
|
3fca50b808 |
||
|
|
986000db44 |
||
|
|
e9c0efa446 |
||
|
|
232a598e75 |
||
|
|
f3e520d380 |
||
|
|
644ecf88ee |
||
|
|
35948d566d |
||
|
|
9b959c5404 |
||
|
|
2ae6defbc4 |
||
|
|
1f0238ce4b |
||
|
|
a4be9224db |
||
|
|
a8872b413b |
||
|
|
2e7e24a023 |
||
|
|
3679b6215d |
||
|
|
a6f3b91f87 |
||
|
|
dfe90ba384 |
||
|
|
69377527bc |
||
|
|
97df50888e |
||
|
|
84af2760ce |
||
|
|
01e4ef3e3b |
||
|
|
690a234388 |
||
|
|
a21d5b020a |
||
|
|
7bea40a25f |
||
|
|
2ce7ef53ca |
||
|
|
88adc02f74 |
||
|
|
3a40f29aa5 |
||
|
|
55e52b7ce4 |
||
|
|
6177c92e32 |
356 changed files with 4233 additions and 2275 deletions
48
.github/workflows/check-new-nolint.sh
vendored
Executable file
48
.github/workflows/check-new-nolint.sh
vendored
Executable file
|
|
@ -0,0 +1,48 @@
|
|||
#!/usr/bin/env bash
|
||||
# Fails when a PR adds a //nolint directive to a Go file; a directive kept on an edited line is not new.
|
||||
# Compares HEAD against $BASE_REF (default origin/master) and needs full history (fetch-depth: 0 in CI).
|
||||
set -euo pipefail
|
||||
|
||||
BASE_REF="${BASE_REF:-origin/master}"
|
||||
|
||||
git diff --unified=0 --no-color "$BASE_REF"...HEAD -- '*.go' | awk '
|
||||
function directives(s, out) {
|
||||
out = ""
|
||||
while (match(s, /\/\/nolint(:[A-Za-z0-9_,-]+)?/)) {
|
||||
out = out " " substr(s, RSTART, RLENGTH)
|
||||
s = substr(s, RSTART + RLENGTH)
|
||||
}
|
||||
return out
|
||||
}
|
||||
/^diff --git / { header = 1; next }
|
||||
/^@@/ {
|
||||
split($3, pos, ",")
|
||||
line = substr(pos[1], 2)
|
||||
header = 0
|
||||
delete removed
|
||||
next
|
||||
}
|
||||
header && /^\+\+\+ / { file = substr($0, 7); next }
|
||||
header { next }
|
||||
/^-/ {
|
||||
n = split(directives($0), ds, " ")
|
||||
for (i = 1; i <= n; i++) removed[ds[i]]++
|
||||
next
|
||||
}
|
||||
/^\+/ {
|
||||
n = split(directives($0), ds, " ")
|
||||
for (i = 1; i <= n; i++) {
|
||||
if (removed[ds[i]] > 0) { removed[ds[i]]--; continue }
|
||||
found++
|
||||
printf "%s:%d: new %s directive\n", file, line, ds[i]
|
||||
if (ENVIRON["GITHUB_ACTIONS"] == "true")
|
||||
printf "::error file=%s,line=%d::New %s directive. Fix the lint issue instead. If this is a real exception, a maintainer can add the allow-nolint label.\n", file, line, ds[i]
|
||||
}
|
||||
line++
|
||||
}
|
||||
END {
|
||||
if (found) {
|
||||
printf "\n%d new //nolint directive(s). Fix the lint issues instead; a maintainer can approve real exceptions with the allow-nolint label.\n", found
|
||||
exit 1
|
||||
}
|
||||
}'
|
||||
31
.github/workflows/nolint-gate.yml
vendored
Normal file
31
.github/workflows/nolint-gate.yml
vendored
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
name: New nolint gate
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, labeled, unlabeled]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check-new-nolint:
|
||||
name: Check for new //nolint directives
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Allowed by label
|
||||
if: contains(github.event.pull_request.labels.*.name, 'allow-nolint')
|
||||
run: echo "::notice::The allow-nolint label is set, so new //nolint directives are allowed."
|
||||
|
||||
- uses: actions/checkout@v7
|
||||
if: "!contains(github.event.pull_request.labels.*.name, 'allow-nolint')"
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Fetch latest base branch
|
||||
if: "!contains(github.event.pull_request.labels.*.name, 'allow-nolint')"
|
||||
run: git fetch --no-tags origin "+refs/heads/${{ github.event.pull_request.base.ref }}:refs/remotes/origin/${{ github.event.pull_request.base.ref }}"
|
||||
|
||||
- name: Fail on new //nolint directives
|
||||
if: "!contains(github.event.pull_request.labels.*.name, 'allow-nolint')"
|
||||
env:
|
||||
BASE_REF: origin/${{ github.event.pull_request.base.ref }}
|
||||
run: ./.github/workflows/check-new-nolint.sh
|
||||
145
.golangci.yml
145
.golangci.yml
|
|
@ -11,26 +11,131 @@ linters:
|
|||
- bodyclose
|
||||
- containedctx
|
||||
- copyloopvar
|
||||
- depguard
|
||||
- dogsled
|
||||
- durationcheck
|
||||
- errchkjson
|
||||
- errorlint
|
||||
- exhaustive
|
||||
- forbidigo
|
||||
- ginkgolinter
|
||||
- gocritic
|
||||
- gocyclo
|
||||
- goprintffuncname
|
||||
- gosec
|
||||
- misspell
|
||||
- modernize
|
||||
- nakedret
|
||||
- nilerr
|
||||
- nolintlint
|
||||
- rowserrcheck
|
||||
- unconvert
|
||||
- whitespace
|
||||
disable:
|
||||
- staticcheck
|
||||
- thelper
|
||||
- unconvert
|
||||
- usetesting
|
||||
- whitespace
|
||||
settings:
|
||||
depguard:
|
||||
rules:
|
||||
api-subsonic:
|
||||
list-mode: lax
|
||||
files:
|
||||
- "**/server/subsonic/**"
|
||||
- "!$test"
|
||||
deny:
|
||||
- pkg: github.com/navidrome/navidrome/server/nativeapi
|
||||
desc: &api_isolation "API packages must not import each other. Move shared code to a neutral package (for example server/filter or core/publicurl)."
|
||||
- pkg: github.com/navidrome/navidrome/server/jellyfin
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/apiv1
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/public
|
||||
desc: *api_isolation
|
||||
api-nativeapi:
|
||||
list-mode: lax
|
||||
files:
|
||||
- "**/server/nativeapi/**"
|
||||
- "!$test"
|
||||
deny:
|
||||
- pkg: github.com/navidrome/navidrome/server/subsonic
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/jellyfin
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/apiv1
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/public
|
||||
desc: *api_isolation
|
||||
api-jellyfin:
|
||||
list-mode: lax
|
||||
files:
|
||||
- "**/server/jellyfin/**"
|
||||
- "!$test"
|
||||
deny:
|
||||
- pkg: github.com/navidrome/navidrome/server/subsonic
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/nativeapi
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/apiv1
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/public
|
||||
desc: *api_isolation
|
||||
api-apiv1:
|
||||
list-mode: lax
|
||||
files:
|
||||
- "**/server/apiv1/**"
|
||||
- "!$test"
|
||||
deny:
|
||||
- pkg: github.com/navidrome/navidrome/server/subsonic
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/nativeapi
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/jellyfin
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/public
|
||||
desc: *api_isolation
|
||||
api-public:
|
||||
list-mode: lax
|
||||
files:
|
||||
- "**/server/public/**"
|
||||
- "!$test"
|
||||
deny:
|
||||
- pkg: github.com/navidrome/navidrome/server/subsonic
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/nativeapi
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/jellyfin
|
||||
desc: *api_isolation
|
||||
- pkg: github.com/navidrome/navidrome/server/apiv1
|
||||
desc: *api_isolation
|
||||
persistence-layer:
|
||||
list-mode: lax
|
||||
files:
|
||||
- "**/persistence/**"
|
||||
- "!$test"
|
||||
deny:
|
||||
- pkg: github.com/navidrome/navidrome/core
|
||||
desc: &persistence_layer "persistence implements the model repositories. Do not depend on business logic or HTTP layers; move the logic to core."
|
||||
- pkg: github.com/navidrome/navidrome/server
|
||||
desc: *persistence_layer
|
||||
- pkg: github.com/navidrome/navidrome/scanner
|
||||
desc: *persistence_layer
|
||||
- pkg: github.com/navidrome/navidrome/plugins
|
||||
desc: *persistence_layer
|
||||
- pkg: github.com/navidrome/navidrome/adapters
|
||||
desc: *persistence_layer
|
||||
- pkg: github.com/navidrome/navidrome/cmd
|
||||
desc: *persistence_layer
|
||||
errcheck:
|
||||
exclude-functions:
|
||||
- (*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
|
||||
gocritic:
|
||||
disable-all: true
|
||||
enabled-checks:
|
||||
|
|
@ -41,6 +146,9 @@ linters:
|
|||
- G401
|
||||
- G505
|
||||
- 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:
|
||||
forbid:
|
||||
- pattern: 'tx\.Exec$'
|
||||
|
|
@ -49,9 +157,29 @@ linters:
|
|||
msg: "use tx.QueryContext(ctx, ...) in migrations to propagate context"
|
||||
- pattern: 'tx\.QueryRow$'
|
||||
msg: "use tx.QueryRowContext(ctx, ...) in migrations to propagate context"
|
||||
- pattern: '^context\.(Background|TODO)$'
|
||||
msg: "in tests use the spec's ctx (from GinkgoT().Context()), t.Context() or b.Context()"
|
||||
- pattern: '^panic$'
|
||||
msg: "don't panic: return an error, or Expect(...)/Fail(...) in tests; log.Fatal only for startup failures that must stop the server"
|
||||
nolintlint:
|
||||
require-specific: true
|
||||
allow-unused: false
|
||||
govet:
|
||||
enable:
|
||||
- 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:
|
||||
rules:
|
||||
- linters:
|
||||
|
|
@ -61,9 +189,20 @@ linters:
|
|||
- path: _test\.go
|
||||
linters:
|
||||
- containedctx
|
||||
# forbidigo rules are scoped by their msg: "in migrations" or "in tests use"
|
||||
- path-except: 'db/migrations/'
|
||||
linters:
|
||||
- forbidigo
|
||||
text: "in migrations"
|
||||
- path-except: '(_test\.go|^tests/)'
|
||||
linters:
|
||||
- forbidigo
|
||||
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
|
||||
presets:
|
||||
- comments
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@ func (c *client) getJWT(ctx context.Context) (string, error) {
|
|||
}
|
||||
|
||||
type authResponse struct {
|
||||
JWT string `json:"jwt"` //nolint:gosec
|
||||
JWT string `json:"jwt"`
|
||||
}
|
||||
|
||||
var result authResponse
|
||||
|
|
|
|||
|
|
@ -20,9 +20,9 @@ var _ = Describe("JWT Authentication", func() {
|
|||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
httpClient = &fakeHttpClient{}
|
||||
client = newClient(httpClient)
|
||||
ctx = context.Background()
|
||||
})
|
||||
|
||||
Describe("getJWT", func() {
|
||||
|
|
@ -35,7 +35,7 @@ var _ = Describe("JWT Authentication", func() {
|
|||
})
|
||||
|
||||
token, err := client.getJWT(ctx)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(token).To(Equal(testJWT))
|
||||
})
|
||||
|
||||
|
|
@ -48,14 +48,14 @@ var _ = Describe("JWT Authentication", func() {
|
|||
|
||||
// First call should fetch from API
|
||||
token1, err := client.getJWT(ctx)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(token1).To(Equal(testJWT))
|
||||
Expect(httpClient.lastRequest.URL.Path).To(Equal("/login/anonymous"))
|
||||
|
||||
// Second call should return cached token without hitting API
|
||||
httpClient.lastRequest = nil // Clear last request to verify no new request is made
|
||||
token2, err := client.getJWT(ctx)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(token2).To(Equal(testJWT))
|
||||
Expect(httpClient.lastRequest).To(BeNil()) // No new request made
|
||||
})
|
||||
|
|
@ -65,9 +65,9 @@ var _ = Describe("JWT Authentication", func() {
|
|||
testToken, err := jwt.NewBuilder().
|
||||
Expiration(expectedExpiration).
|
||||
Build()
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||
StatusCode: 200,
|
||||
|
|
@ -75,7 +75,7 @@ var _ = Describe("JWT Authentication", func() {
|
|||
})
|
||||
|
||||
token, err := client.getJWT(ctx)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(token).ToNot(BeEmpty())
|
||||
|
||||
// Verify the token is cached until close to expiration
|
||||
|
|
@ -121,7 +121,7 @@ var _ = Describe("JWT Authentication", func() {
|
|||
})
|
||||
|
||||
token, err := client.getJWT(ctx)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(token).ToNot(BeEmpty())
|
||||
})
|
||||
})
|
||||
|
|
@ -176,14 +176,14 @@ var _ = Describe("JWT Authentication", func() {
|
|||
testToken, err := jwt.NewBuilder().
|
||||
Claim("custom", "value").
|
||||
Build()
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
// Verify token has no expiration
|
||||
_, hasExp := testToken.Expiration()
|
||||
Expect(hasExp).To(BeFalse())
|
||||
|
||||
testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||
StatusCode: 200,
|
||||
|
|
@ -206,7 +206,7 @@ var _ = Describe("JWT Authentication", func() {
|
|||
})
|
||||
|
||||
token1, err := client.getJWT(ctx)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(token1).To(Equal(firstJWT))
|
||||
|
||||
// Manually expire the cached token
|
||||
|
|
@ -220,7 +220,7 @@ var _ = Describe("JWT Authentication", func() {
|
|||
})
|
||||
|
||||
token2, err := client.getJWT(ctx)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(token2).To(Equal(secondJWT))
|
||||
Expect(token2).ToNot(Equal(token1))
|
||||
})
|
||||
|
|
@ -280,15 +280,12 @@ var _ = Describe("JWT Authentication", func() {
|
|||
|
||||
// createTestJWT creates a valid JWT token for testing purposes
|
||||
func createTestJWT(expiresIn time.Duration) string {
|
||||
GinkgoHelper()
|
||||
token, err := jwt.NewBuilder().
|
||||
Expiration(time.Now().Add(expiresIn)).
|
||||
Build()
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("failed to create test JWT: %v", err))
|
||||
}
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
signed, err := jwt.Sign(token, jwt.WithInsecureNoSignature())
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("failed to sign test JWT: %v", err))
|
||||
}
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
return string(signed)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,11 +26,11 @@ var _ = Describe("client", func() {
|
|||
Describe("ArtistImages", func() {
|
||||
It("returns artist images from a successful request", func() {
|
||||
f, err := os.Open("tests/fixtures/deezer.search.artist.json")
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: 200})
|
||||
|
||||
artists, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(artists).To(HaveLen(17))
|
||||
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"))
|
||||
|
|
@ -80,11 +80,11 @@ var _ = Describe("client", func() {
|
|||
Describe("TopTracks", 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")
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: 200})
|
||||
|
||||
tracks, err := client.getTopTracks(GinkgoT().Context(), 27, 5)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(tracks).To(HaveLen(5))
|
||||
|
||||
// Verify first track has all expected fields
|
||||
|
|
@ -111,11 +111,11 @@ var _ = Describe("client", func() {
|
|||
|
||||
It("returns artist bio from a successful request", func() {
|
||||
f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json")
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
|
||||
|
||||
bio, err := client.getArtistBio(GinkgoT().Context(), 27, "en")
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(bio).To(ContainSubstring("Schoolmates Thomas and Guy-Manuel"))
|
||||
Expect(bio).ToNot(ContainSubstring("<p>"))
|
||||
Expect(bio).ToNot(ContainSubstring("</p>"))
|
||||
|
|
@ -123,21 +123,21 @@ var _ = Describe("client", func() {
|
|||
|
||||
It("uses the provided language", func() {
|
||||
f, err := os.Open("tests/fixtures/deezer.artist.bio.fr.json")
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
|
||||
|
||||
_, err = client.getArtistBio(GinkgoT().Context(), 27, "fr")
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.lastRequest.Header.Get("Accept-Language")).To(Equal("fr"))
|
||||
})
|
||||
|
||||
It("includes the JWT token in the request", func() {
|
||||
f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json")
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
|
||||
|
||||
_, err = client.getArtistBio(GinkgoT().Context(), 27, "en")
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
// Verify that the Authorization header has the Bearer token format
|
||||
authHeader := httpClient.lastRequest.Header.Get("Authorization")
|
||||
Expect(authHeader).To(HavePrefix("Bearer "))
|
||||
|
|
@ -238,5 +238,6 @@ func (c *fakeHttpClient) Do(req *http.Request) (*http.Response, error) {
|
|||
if resp, ok := c.responses[u.String()]; ok {
|
||||
return resp, nil
|
||||
}
|
||||
panic("URL not mocked: " + u.String())
|
||||
Fail("URL not mocked: " + u.String())
|
||||
return nil, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ var _ = Describe("deezerAgent", func() {
|
|||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
conf.Update(func(c *conf.Options) { c.Deezer.Enabled = true })
|
||||
})
|
||||
|
||||
|
|
@ -290,5 +290,6 @@ func (c *langAwareHttpClient) Do(req *http.Request) (*http.Response, error) {
|
|||
}, nil
|
||||
}
|
||||
|
||||
panic("URL not mocked: " + req.URL.String())
|
||||
Fail("URL not mocked: " + req.URL.String())
|
||||
return nil, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,9 +13,9 @@ var _ = Describe("Responses", func() {
|
|||
It("parses the artist search result correctly ", func() {
|
||||
var resp SearchArtistResults
|
||||
body, err := os.ReadFile("tests/fixtures/deezer.search.artist.json")
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
err = json.Unmarshal(body, &resp)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(resp.Data).To(HaveLen(17))
|
||||
michael := resp.Data[0]
|
||||
|
|
@ -29,7 +29,7 @@ var _ = Describe("Responses", func() {
|
|||
var errorResp errorResponse
|
||||
body := []byte(`{"error":{"type":"MissingParameterException","message":"Missing parameters: q","code":501}}`)
|
||||
err := json.Unmarshal(body, &errorResp)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(errorResp.Error.Code).To(Equal(501))
|
||||
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() {
|
||||
var resp RelatedArtists
|
||||
body, err := os.ReadFile("tests/fixtures/deezer.artist.related.json")
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
err = json.Unmarshal(body, &resp)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(resp.Data).To(HaveLen(20))
|
||||
justice := resp.Data[0]
|
||||
|
|
@ -55,9 +55,9 @@ var _ = Describe("Responses", func() {
|
|||
It("parses the top tracks response correctly", func() {
|
||||
var resp TopTracks
|
||||
body, err := os.ReadFile("tests/fixtures/deezer.artist.top.json")
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
err = json.Unmarshal(body, &resp)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(resp.Data).To(HaveLen(5))
|
||||
track := resp.Data[0]
|
||||
|
|
|
|||
|
|
@ -20,13 +20,13 @@ func (t testFileInfo) BirthTime() time.Time {
|
|||
if ts := times.Get(t.FileInfo); ts.HasBirthTime() {
|
||||
return ts.BirthTime()
|
||||
}
|
||||
return t.FileInfo.ModTime()
|
||||
return t.ModTime()
|
||||
}
|
||||
|
||||
var _ = Describe("Extractor", func() {
|
||||
toP := func(name, sortName, mbid string) model.Participant {
|
||||
return model.Participant{
|
||||
Artist: model.Artist{Name: name, SortArtistName: sortName, MbzArtistID: mbid},
|
||||
Name: name, SortArtistName: sortName, MbzArtistID: mbid,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -156,7 +156,7 @@ var _ = Describe("Extractor", func() {
|
|||
mf := parseTestFile("tests/fixtures/" + file)
|
||||
|
||||
lyrics, err := mf.StructuredLyrics()
|
||||
Expect(err).To(Not(HaveOccurred()))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(lyrics).To(HaveLen(2))
|
||||
|
||||
unspec := makeLyrics("xxx", "unspecified")
|
||||
|
|
@ -250,7 +250,7 @@ var _ = Describe("Extractor", func() {
|
|||
|
||||
// WMA has no Arranger role
|
||||
if role == model.RoleArranger {
|
||||
Expect(actual).To(HaveLen(0))
|
||||
Expect(actual).To(BeEmpty())
|
||||
continue
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -78,7 +78,7 @@ var _ = Describe("Extractor", func() {
|
|||
|
||||
// Test OGG
|
||||
m = mds["tests/fixtures/test.ogg"]
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(m.Tags).To(HaveKeyWithValue("fbpm", []string{"141.7"}))
|
||||
|
||||
// TagLib 1.12 returns 18, previous versions return 39.
|
||||
|
|
|
|||
|
|
@ -49,10 +49,11 @@ type lastfmAgent struct {
|
|||
getInfoMutex sync.Mutex
|
||||
}
|
||||
|
||||
func lastFMEnabled() bool {
|
||||
return conf.Server().LastFM.Enabled && conf.Server().LastFM.ApiKey != "" && conf.Server().LastFM.Secret != ""
|
||||
}
|
||||
|
||||
func lastFMConstructor(ds model.DataStore) *lastfmAgent {
|
||||
if !conf.Server().LastFM.Enabled || conf.Server().LastFM.ApiKey == "" || conf.Server().LastFM.Secret == "" {
|
||||
return nil
|
||||
}
|
||||
l := &lastfmAgent{
|
||||
ds: ds,
|
||||
languages: conf.Server().LastFM.Languages,
|
||||
|
|
@ -388,10 +389,11 @@ func (l *lastfmAgent) Scrobble(ctx context.Context, userId string, s scrobbler.S
|
|||
return errors.Join(err, scrobbler.ErrNotAuthorized)
|
||||
}
|
||||
|
||||
if s.Duration <= 30 {
|
||||
if s.Duration <= float32(conf.Server().LastFM.MinScrobbleDuration.Seconds()) {
|
||||
log.Debug(ctx, "Skipping Last.fm scrobble for short song", "track", s.Title, "duration", s.Duration)
|
||||
return nil
|
||||
}
|
||||
|
||||
err = l.client.scrobble(ctx, sk, ScrobbleInfo{
|
||||
artist: l.getArtistForScrobble(&s.MediaFile, model.RoleArtist, s.Artist),
|
||||
track: s.Title,
|
||||
|
|
@ -430,22 +432,16 @@ func (l *lastfmAgent) PlaybackReport(context.Context, scrobbler.PlaybackSession)
|
|||
func init() {
|
||||
conf.AddHook(func() {
|
||||
agents.Register(lastFMAgentName, func(ds model.DataStore) agents.Interface {
|
||||
// This is a workaround for the fact that a (Interface)(nil) is not the same as a (*lastfmAgent)(nil)
|
||||
// See https://go.dev/doc/faq#nil_error
|
||||
a := lastFMConstructor(ds)
|
||||
if a != nil {
|
||||
return a
|
||||
if !lastFMEnabled() {
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
return lastFMConstructor(ds)
|
||||
})
|
||||
scrobbler.Register(lastFMAgentName, func(ds model.DataStore) scrobbler.Scrobbler {
|
||||
// Same as above - this is a workaround for the fact that a (Scrobbler)(nil) is not the same as a (*lastfmAgent)(nil)
|
||||
// See https://go.dev/doc/faq#nil_error
|
||||
a := lastFMConstructor(ds)
|
||||
if a != nil {
|
||||
return a
|
||||
if !lastFMEnabled() {
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
return lastFMConstructor(ds)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,8 +29,8 @@ var _ = Describe("lastfmAgent", func() {
|
|||
var ds model.DataStore
|
||||
var ctx context.Context
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
ds = &tests.MockDataStore{}
|
||||
ctx = context.Background()
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.LastFM.Enabled = true
|
||||
c.LastFM.ApiKey = "123"
|
||||
|
|
@ -47,24 +47,21 @@ var _ = Describe("lastfmAgent", func() {
|
|||
Expect(agent.languages).To(Equal([]string{"pt", "en"}))
|
||||
})
|
||||
})
|
||||
When("Agent is disabled", func() {
|
||||
It("returns nil", func() {
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.Enabled = false })
|
||||
Expect(lastFMConstructor(ds)).To(BeNil())
|
||||
})
|
||||
})
|
||||
When("ApiKey is empty", func() {
|
||||
It("returns nil", func() {
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.ApiKey = "" })
|
||||
Expect(lastFMConstructor(ds)).To(BeNil())
|
||||
})
|
||||
})
|
||||
When("Secret is empty", func() {
|
||||
It("returns nil", func() {
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.Secret = "" })
|
||||
Expect(lastFMConstructor(ds)).To(BeNil())
|
||||
})
|
||||
})
|
||||
|
||||
Describe("lastFMEnabled", func() {
|
||||
It("is true when enabled with an api key and secret", func() {
|
||||
Expect(lastFMEnabled()).To(BeTrue())
|
||||
})
|
||||
DescribeTable("is false when the configuration is incomplete",
|
||||
func(change func(*conf.Options)) {
|
||||
conf.Update(change)
|
||||
Expect(lastFMEnabled()).To(BeFalse())
|
||||
},
|
||||
Entry("disabled", func(c *conf.Options) { c.LastFM.Enabled = false }),
|
||||
Entry("no api key", func(c *conf.Options) { c.LastFM.ApiKey = "" }),
|
||||
Entry("no secret", func(c *conf.Options) { c.LastFM.Secret = "" }),
|
||||
)
|
||||
})
|
||||
|
||||
Describe("GetArtistBiography", func() {
|
||||
|
|
@ -373,12 +370,12 @@ var _ = Describe("lastfmAgent", func() {
|
|||
MbzRecordingID: "mbz-123",
|
||||
Participants: map[model.Role]model.ParticipantList{
|
||||
model.RoleArtist: []model.Participant{
|
||||
{Artist: model.Artist{ID: "ar-1", Name: "First Artist"}},
|
||||
{Artist: model.Artist{ID: "ar-2", Name: "Second Artist"}},
|
||||
{ID: "ar-1", Name: "First Artist"},
|
||||
{ID: "ar-2", Name: "Second Artist"},
|
||||
},
|
||||
model.RoleAlbumArtist: []model.Participant{
|
||||
{Artist: model.Artist{ID: "ar-1", Name: "First Album Artist"}},
|
||||
{Artist: model.Artist{ID: "ar-2", Name: "Second Album Artist"}},
|
||||
{ID: "ar-1", Name: "First Album Artist"},
|
||||
{ID: "ar-2", Name: "Second Album Artist"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -471,8 +468,8 @@ var _ = Describe("lastfmAgent", func() {
|
|||
})
|
||||
})
|
||||
|
||||
It("skips songs with less than 31 seconds", func() {
|
||||
track.Duration = 29
|
||||
It("skips songs at the 30-second minimum", func() {
|
||||
track.Duration = 30
|
||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
||||
|
||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||
|
|
@ -481,6 +478,46 @@ var _ = Describe("lastfmAgent", func() {
|
|||
Expect(httpClient.SavedRequest).To(BeNil())
|
||||
})
|
||||
|
||||
It("sends the duration parameter for a 30.5-second song", func() {
|
||||
track.Duration = 30.5
|
||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"scrobbles":{"scrobble":{"ignoredMessage":{"code":"0"}},"@attr":{"accepted":1}}}`)), StatusCode: 200}
|
||||
|
||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
body, _ := io.ReadAll(httpClient.SavedRequest.Body)
|
||||
sentParams, _ := url.ParseQuery(string(body))
|
||||
Expect(sentParams.Has("duration")).To(BeTrue())
|
||||
Expect(sentParams.Get("duration")).To(Equal("30"))
|
||||
})
|
||||
|
||||
It("skips songs according to the configured minimum duration", func() {
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 60 * time.Second })
|
||||
track.Duration = 59
|
||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
||||
|
||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest).To(BeNil())
|
||||
})
|
||||
|
||||
It("does not skip short songs when the minimum duration is disabled", func() {
|
||||
conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 0 })
|
||||
track.Duration = 29
|
||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
||||
|
||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest).ToNot(BeNil())
|
||||
|
||||
body, _ := io.ReadAll(httpClient.SavedRequest.Body)
|
||||
sentParams, _ := url.ParseQuery(string(body))
|
||||
Expect(sentParams.Has("duration")).To(BeFalse())
|
||||
})
|
||||
|
||||
It("returns ErrNotAuthorized if user is not linked", func() {
|
||||
err := agent.Scrobble(ctx, "user-2", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||
Expect(err).To(MatchError(scrobbler.ErrNotAuthorized))
|
||||
|
|
|
|||
|
|
@ -122,7 +122,7 @@ func (s *Router) callback(w http.ResponseWriter, r *http.Request) {
|
|||
if err != nil {
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte("An error occurred while authorizing with Last.fm. \n\nRequest ID: " + middleware.GetReqID(ctx))) //nolint:gosec
|
||||
_, _ = w.Write([]byte("An error occurred while authorizing with Last.fm. \n\nRequest ID: " + middleware.GetReqID(ctx)))
|
||||
return
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -74,7 +74,7 @@ var _ = Describe("auth_router", func() {
|
|||
var body map[string]any
|
||||
Expect(json.Unmarshal(rec.Body.Bytes(), &body)).To(Succeed())
|
||||
Expect(body["apiKey"]).To(Equal("API_KEY"))
|
||||
Expect(body["status"]).To(Equal(false))
|
||||
Expect(body["status"]).To(BeFalse())
|
||||
token, ok := body["linkToken"].(string)
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(token).ToNot(BeEmpty())
|
||||
|
|
|
|||
|
|
@ -182,7 +182,14 @@ func (c *client) scrobble(ctx context.Context, sessionKey string, info ScrobbleI
|
|||
params.Add("album", info.album)
|
||||
params.Add("trackNumber", strconv.Itoa(info.trackNumber))
|
||||
params.Add("mbid", info.mbid)
|
||||
params.Add("duration", strconv.Itoa(info.duration))
|
||||
|
||||
// Last.fm requires a minimum duration of 30 seconds to scrobble a track. To circumvent this, only send the duration if it is greater than or equal to 30 seconds.
|
||||
if info.duration >= 30 {
|
||||
params.Add("duration", strconv.Itoa(info.duration))
|
||||
} else {
|
||||
log.Debug(ctx, "LastFM: scrobble duration is less than 30 seconds, duration will not be transmitted", "duration", info.duration)
|
||||
}
|
||||
|
||||
params.Add("albumArtist", info.albumArtist)
|
||||
params.Add("sk", sessionKey)
|
||||
resp, err := c.makeRequest(ctx, http.MethodPost, params, true)
|
||||
|
|
|
|||
|
|
@ -19,8 +19,10 @@ import (
|
|||
var _ = Describe("client", func() {
|
||||
var httpClient *tests.FakeHttpClient
|
||||
var client *client
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
httpClient = &tests.FakeHttpClient{}
|
||||
client = newClient("API_KEY", "SECRET", httpClient)
|
||||
})
|
||||
|
|
@ -30,8 +32,8 @@ var _ = Describe("client", func() {
|
|||
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
|
||||
album, err := client.albumGetInfo(context.Background(), "Believe", "U2", "mbid-1234", "pt")
|
||||
Expect(err).To(BeNil())
|
||||
album, err := client.albumGetInfo(ctx, "Believe", "U2", "mbid-1234", "pt")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
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"))
|
||||
})
|
||||
|
|
@ -40,7 +42,7 @@ var _ = Describe("client", func() {
|
|||
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
|
||||
_, err := client.albumGetInfo(context.Background(), "Lungs", "Florence + the Machine", "", "en")
|
||||
_, err := client.albumGetInfo(ctx, "Lungs", "Florence + the Machine", "", "en")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("Florence + the Machine"))
|
||||
})
|
||||
|
|
@ -51,8 +53,8 @@ var _ = Describe("client", func() {
|
|||
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
|
||||
artist, err := client.artistGetInfo(context.Background(), "U2", "pt")
|
||||
Expect(err).To(BeNil())
|
||||
artist, err := client.artistGetInfo(ctx, "U2", "pt")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
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"))
|
||||
})
|
||||
|
|
@ -61,7 +63,7 @@ var _ = Describe("client", func() {
|
|||
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
|
||||
_, err := client.artistGetInfo(context.Background(), "Florence + the Machine", "en")
|
||||
_, err := client.artistGetInfo(ctx, "Florence + the Machine", "en")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("Florence %2B the Machine"))
|
||||
})
|
||||
|
|
@ -72,7 +74,7 @@ var _ = Describe("client", func() {
|
|||
StatusCode: 500,
|
||||
}
|
||||
|
||||
_, err := client.artistGetInfo(context.Background(), "U2", "pt")
|
||||
_, err := client.artistGetInfo(ctx, "U2", "pt")
|
||||
Expect(err).To(MatchError("last.fm http status: (500)"))
|
||||
})
|
||||
|
||||
|
|
@ -82,7 +84,7 @@ var _ = Describe("client", func() {
|
|||
StatusCode: 400,
|
||||
}
|
||||
|
||||
_, err := client.artistGetInfo(context.Background(), "U2", "pt")
|
||||
_, err := client.artistGetInfo(ctx, "U2", "pt")
|
||||
Expect(err).To(MatchError(&lastFMError{Code: 3, Message: "Invalid Method - No method with that name in this package"}))
|
||||
})
|
||||
|
||||
|
|
@ -92,14 +94,14 @@ var _ = Describe("client", func() {
|
|||
StatusCode: 200,
|
||||
}
|
||||
|
||||
_, err := client.artistGetInfo(context.Background(), "U2", "pt")
|
||||
_, err := client.artistGetInfo(ctx, "U2", "pt")
|
||||
Expect(err).To(MatchError(&lastFMError{Code: 6, Message: "The artist you supplied could not be found"}))
|
||||
})
|
||||
|
||||
It("fails if HttpClient.Do() returns error", func() {
|
||||
httpClient.Err = errors.New("generic error")
|
||||
|
||||
_, err := client.artistGetInfo(context.Background(), "U2", "pt")
|
||||
_, err := client.artistGetInfo(ctx, "U2", "pt")
|
||||
Expect(err).To(MatchError("generic error"))
|
||||
})
|
||||
|
||||
|
|
@ -109,7 +111,7 @@ var _ = Describe("client", func() {
|
|||
StatusCode: 200,
|
||||
}
|
||||
|
||||
_, err := client.artistGetInfo(context.Background(), "U2", "pt")
|
||||
_, err := client.artistGetInfo(ctx, "U2", "pt")
|
||||
Expect(err).To(MatchError("invalid character '<' looking for beginning of value"))
|
||||
})
|
||||
|
||||
|
|
@ -120,9 +122,9 @@ var _ = Describe("client", func() {
|
|||
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
|
||||
similar, err := client.artistGetSimilar(context.Background(), "U2", 2)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(len(similar.Artists)).To(Equal(2))
|
||||
similar, err := client.artistGetSimilar(ctx, "U2", 2)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(similar.Artists).To(HaveLen(2))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&limit=2&method=artist.getSimilar"))
|
||||
})
|
||||
|
||||
|
|
@ -130,7 +132,7 @@ var _ = Describe("client", func() {
|
|||
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
|
||||
_, err := client.artistGetSimilar(context.Background(), "+44", 2)
|
||||
_, err := client.artistGetSimilar(ctx, "+44", 2)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("%2B44"))
|
||||
})
|
||||
|
|
@ -141,9 +143,9 @@ var _ = Describe("client", func() {
|
|||
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
|
||||
top, err := client.artistGetTopTracks(context.Background(), "U2", 2)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(len(top.Track)).To(Equal(2))
|
||||
top, err := client.artistGetTopTracks(ctx, "U2", 2)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(top.Track).To(HaveLen(2))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&limit=2&method=artist.getTopTracks"))
|
||||
})
|
||||
|
||||
|
|
@ -151,7 +153,7 @@ var _ = Describe("client", func() {
|
|||
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
|
||||
_, err := client.artistGetTopTracks(context.Background(), "C+C Music Factory", 2)
|
||||
_, err := client.artistGetTopTracks(ctx, "C+C Music Factory", 2)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("C%2BC Music Factory"))
|
||||
})
|
||||
|
|
@ -162,9 +164,9 @@ var _ = Describe("client", func() {
|
|||
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
|
||||
similar, err := client.trackGetSimilar(context.Background(), "Just Can't Get Enough", "Depeche Mode", 5)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(len(similar.Track)).To(Equal(5))
|
||||
similar, err := client.trackGetSimilar(ctx, "Just Can't Get Enough", "Depeche Mode", 5)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(similar.Track).To(HaveLen(5))
|
||||
Expect(similar.Track[0].Name).To(Equal("Dreaming of Me"))
|
||||
Expect(similar.Track[0].Artist.Name).To(Equal("Depeche Mode"))
|
||||
Expect(similar.Track[0].Match).To(Equal(1.0))
|
||||
|
|
@ -175,7 +177,7 @@ var _ = Describe("client", func() {
|
|||
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
|
||||
_, err := client.trackGetSimilar(context.Background(), "1+1", "Queen + Paul Rodgers", 5)
|
||||
_, err := client.trackGetSimilar(ctx, "1+1", "Queen + Paul Rodgers", 5)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
query := httpClient.SavedRequest.URL.Query()
|
||||
Expect(query.Get("track")).To(Equal("1%2B1"))
|
||||
|
|
@ -186,8 +188,8 @@ var _ = Describe("client", func() {
|
|||
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
|
||||
similar, err := client.trackGetSimilar(context.Background(), "UnknownTrack", "UnknownArtist", 3)
|
||||
Expect(err).To(BeNil())
|
||||
similar, err := client.trackGetSimilar(ctx, "UnknownTrack", "UnknownArtist", 3)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(similar.Track).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
|
|
@ -199,7 +201,7 @@ var _ = Describe("client", func() {
|
|||
StatusCode: 200,
|
||||
}
|
||||
|
||||
Expect(client.GetToken(context.Background())).To(Equal("TOKEN"))
|
||||
Expect(client.GetToken(ctx)).To(Equal("TOKEN"))
|
||||
queryParams := httpClient.SavedRequest.URL.Query()
|
||||
Expect(queryParams.Get("method")).To(Equal("auth.getToken"))
|
||||
Expect(queryParams.Get("format")).To(Equal("json"))
|
||||
|
|
@ -215,7 +217,7 @@ var _ = Describe("client", func() {
|
|||
StatusCode: 200,
|
||||
}
|
||||
|
||||
Expect(client.getSession(context.Background(), "TOKEN")).To(Equal("SESSION_KEY"))
|
||||
Expect(client.getSession(ctx, "TOKEN")).To(Equal("SESSION_KEY"))
|
||||
queryParams := httpClient.SavedRequest.URL.Query()
|
||||
Expect(queryParams.Get("method")).To(Equal("auth.getSession"))
|
||||
Expect(queryParams.Get("format")).To(Equal("json"))
|
||||
|
|
@ -240,8 +242,8 @@ var _ = Describe("client", func() {
|
|||
duration: 276,
|
||||
albumArtist: "U2",
|
||||
}
|
||||
err := client.scrobble(context.Background(), "SESSION_KEY", info)
|
||||
Expect(err).To(BeNil())
|
||||
err := client.scrobble(ctx, "SESSION_KEY", info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
req := httpClient.SavedRequest
|
||||
Expect(req.Method).To(Equal(http.MethodPost))
|
||||
|
|
@ -274,8 +276,8 @@ var _ = Describe("client", func() {
|
|||
duration: 276,
|
||||
albumArtist: "U2",
|
||||
}
|
||||
err := client.updateNowPlaying(context.Background(), "SESSION_KEY", info)
|
||||
Expect(err).To(BeNil())
|
||||
err := client.updateNowPlaying(ctx, "SESSION_KEY", info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
req := httpClient.SavedRequest
|
||||
Expect(req.Method).To(Equal(http.MethodPost))
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ var _ = Describe("LastFM responses", func() {
|
|||
var resp Response
|
||||
body, _ := os.ReadFile("tests/fixtures/lastfm.artist.getinfo.json")
|
||||
err := json.Unmarshal(body, &resp)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(resp.Artist.Name).To(Equal("U2"))
|
||||
Expect(resp.Artist.MBID).To(Equal("a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432"))
|
||||
|
|
@ -28,7 +28,7 @@ var _ = Describe("LastFM responses", func() {
|
|||
var resp Response
|
||||
body, _ := os.ReadFile("tests/fixtures/lastfm.artist.getsimilar.json")
|
||||
err := json.Unmarshal(body, &resp)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(resp.SimilarArtists.Artists).To(HaveLen(2))
|
||||
Expect(resp.SimilarArtists.Artists[0].Name).To(Equal("Passengers"))
|
||||
|
|
@ -41,7 +41,7 @@ var _ = Describe("LastFM responses", func() {
|
|||
var resp Response
|
||||
body, _ := os.ReadFile("tests/fixtures/lastfm.artist.gettoptracks.json")
|
||||
err := json.Unmarshal(body, &resp)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(resp.TopTracks.Track).To(HaveLen(2))
|
||||
Expect(resp.TopTracks.Track[0].Name).To(Equal("Beautiful Day"))
|
||||
|
|
@ -56,7 +56,7 @@ var _ = Describe("LastFM responses", func() {
|
|||
var error Response
|
||||
body := []byte(`{"error":3,"message":"Invalid Method - No method with that name in this package"}`)
|
||||
err := json.Unmarshal(body, &error)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(error.Error).To(Equal(3))
|
||||
Expect(error.Message).To(Equal("Invalid Method - No method with that name in this package"))
|
||||
|
|
|
|||
|
|
@ -228,29 +228,30 @@ func (l *listenBrainzAgent) PlaybackReport(context.Context, scrobbler.PlaybackSe
|
|||
}
|
||||
|
||||
func init() {
|
||||
conf.AddHook(func() {
|
||||
if conf.Server().ListenBrainz.Enabled {
|
||||
scrobbler.Register(listenBrainzAgentName, func(ds model.DataStore) scrobbler.Scrobbler {
|
||||
// This is a workaround for the fact that a (Interface)(nil) is not the same as a (*listenBrainzAgent)(nil)
|
||||
// See https://go.dev/doc/faq#nil_error
|
||||
a := listenBrainzConstructor(ds)
|
||||
if a != nil {
|
||||
return a
|
||||
}
|
||||
return nil
|
||||
})
|
||||
conf.AddHook(register)
|
||||
}
|
||||
|
||||
agents.Register(listenBrainzAgentName, func(ds model.DataStore) agents.Interface {
|
||||
// This is a workaround for the fact that a (Interface)(nil) is not the same as a (*listenBrainzAgent)(nil)
|
||||
// See https://go.dev/doc/faq#nil_error
|
||||
a := listenBrainzConstructor(ds)
|
||||
if a != nil {
|
||||
return a
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
})
|
||||
func register() {
|
||||
scrobbler.Register(listenBrainzAgentName, newScrobbler)
|
||||
agents.Register(listenBrainzAgentName, newAgent)
|
||||
}
|
||||
|
||||
func listenBrainzEnabled() bool {
|
||||
return conf.Server().ListenBrainz.Enabled
|
||||
}
|
||||
|
||||
func newScrobbler(ds model.DataStore) scrobbler.Scrobbler {
|
||||
if !listenBrainzEnabled() {
|
||||
return nil
|
||||
}
|
||||
return listenBrainzConstructor(ds)
|
||||
}
|
||||
|
||||
func newAgent(ds model.DataStore) agents.Interface {
|
||||
if !listenBrainzEnabled() {
|
||||
return nil
|
||||
}
|
||||
return listenBrainzConstructor(ds)
|
||||
}
|
||||
|
||||
var (
|
||||
|
|
|
|||
|
|
@ -8,8 +8,10 @@ import (
|
|||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/consts"
|
||||
"github.com/navidrome/navidrome/core/agents"
|
||||
"github.com/navidrome/navidrome/core/scrobbler"
|
||||
|
|
@ -28,8 +30,8 @@ var _ = Describe("listenBrainzAgent", func() {
|
|||
var track *model.MediaFile
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
ds = &tests.MockDataStore{}
|
||||
ctx = context.Background()
|
||||
_ = ds.UserProps().Put(ctx, "user-1", sessionKeyProperty, "SK-1")
|
||||
httpClient = &tests.FakeHttpClient{}
|
||||
agent = listenBrainzConstructor(ds)
|
||||
|
|
@ -46,8 +48,8 @@ var _ = Describe("listenBrainzAgent", func() {
|
|||
Duration: 142.2,
|
||||
Participants: map[model.Role]model.ParticipantList{
|
||||
model.RoleArtist: []model.Participant{
|
||||
{Artist: model.Artist{ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"}},
|
||||
{Artist: model.Artist{ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"}},
|
||||
{ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"},
|
||||
{ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -477,3 +479,43 @@ var _ = Describe("listenBrainzAgent", func() {
|
|||
})
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("register", func() {
|
||||
var ds model.DataStore
|
||||
|
||||
BeforeEach(func() {
|
||||
ds = &tests.MockDataStore{}
|
||||
delete(agents.Map, listenBrainzAgentName)
|
||||
scrobbler.Unregister(listenBrainzAgentName)
|
||||
})
|
||||
|
||||
When("ListenBrainz is disabled", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Update(func(c *conf.Options) { c.ListenBrainz.Enabled = false })
|
||||
register()
|
||||
})
|
||||
|
||||
It("still registers the builtin name", func() {
|
||||
Expect(scrobbler.IsBuiltinScrobbler(listenBrainzAgentName)).To(BeTrue())
|
||||
Expect(agents.Map).To(HaveKey(listenBrainzAgentName))
|
||||
})
|
||||
|
||||
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(reflect.TypeOf(newScrobbler(ds))).To(BeNil())
|
||||
Expect(reflect.TypeOf(agents.Map[listenBrainzAgentName](ds))).To(BeNil())
|
||||
})
|
||||
})
|
||||
|
||||
When("ListenBrainz is enabled", func() {
|
||||
BeforeEach(func() {
|
||||
conf.Update(func(c *conf.Options) { c.ListenBrainz.Enabled = true })
|
||||
register()
|
||||
})
|
||||
|
||||
It("builds the scrobbler and the agent", func() {
|
||||
Expect(newScrobbler(ds)).To(BeAssignableToTypeOf(&listenBrainzAgent{}))
|
||||
Expect(agents.Map[listenBrainzAgentName](ds)).To(BeAssignableToTypeOf(&listenBrainzAgent{}))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -38,8 +38,8 @@ var _ = Describe("ListenBrainz Auth Router", func() {
|
|||
r.getLinkStatus(resp, req)
|
||||
Expect(resp.Code).To(Equal(http.StatusOK))
|
||||
var parsed map[string]any
|
||||
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil())
|
||||
Expect(parsed["status"]).To(Equal(false))
|
||||
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(Succeed())
|
||||
Expect(parsed["status"]).To(BeFalse())
|
||||
})
|
||||
|
||||
It("returns true when there is a stored session key", func() {
|
||||
|
|
@ -48,8 +48,8 @@ var _ = Describe("ListenBrainz Auth Router", func() {
|
|||
r.getLinkStatus(resp, req)
|
||||
Expect(resp.Code).To(Equal(http.StatusOK))
|
||||
var parsed map[string]any
|
||||
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil())
|
||||
Expect(parsed["status"]).To(Equal(true))
|
||||
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(Succeed())
|
||||
Expect(parsed["status"]).To(BeTrue())
|
||||
})
|
||||
})
|
||||
|
||||
|
|
@ -81,8 +81,8 @@ var _ = Describe("ListenBrainz Auth Router", func() {
|
|||
r.link(resp, req)
|
||||
Expect(resp.Code).To(Equal(http.StatusOK))
|
||||
var parsed map[string]any
|
||||
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil())
|
||||
Expect(parsed["status"]).To(Equal(true))
|
||||
Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(Succeed())
|
||||
Expect(parsed["status"]).To(BeTrue())
|
||||
Expect(parsed["user"]).To(Equal("ListenBrainzUser"))
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -64,7 +64,7 @@ type listenBrainzResponse struct {
|
|||
}
|
||||
|
||||
type listenBrainzRequest struct {
|
||||
ApiKey string //nolint:gosec
|
||||
ApiKey string
|
||||
Body listenBrainzRequestBody
|
||||
}
|
||||
|
||||
|
|
@ -162,7 +162,10 @@ func (c *client) path(endpoint string) (string, error) {
|
|||
}
|
||||
|
||||
func (c *client) makeAuthenticatedRequest(ctx context.Context, method string, endpoint string, r *listenBrainzRequest) (*listenBrainzResponse, error) {
|
||||
b, _ := json.Marshal(r.Body)
|
||||
b, err := json.Marshal(r.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encoding request body: %w", err)
|
||||
}
|
||||
uri, err := c.path(endpoint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
|
|||
|
|
@ -22,7 +22,9 @@ import (
|
|||
var _ = Describe("client", func() {
|
||||
var httpClient *tests.FakeHttpClient
|
||||
var client *client
|
||||
var ctx context.Context
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
httpClient = &tests.FakeHttpClient{}
|
||||
client = newClient("BASE_URL/", httpClient)
|
||||
})
|
||||
|
|
@ -51,7 +53,7 @@ var _ = Describe("client", func() {
|
|||
})
|
||||
|
||||
It("formats the request properly", func() {
|
||||
_, err := client.validateToken(context.Background(), "LB-TOKEN")
|
||||
_, err := client.validateToken(ctx, "LB-TOKEN")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/validate-token"))
|
||||
|
|
@ -60,9 +62,9 @@ var _ = Describe("client", func() {
|
|||
})
|
||||
|
||||
It("parses and returns the response", func() {
|
||||
res, err := client.validateToken(context.Background(), "LB-TOKEN")
|
||||
res, err := client.validateToken(ctx, "LB-TOKEN")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(res.Valid).To(Equal(true))
|
||||
Expect(res.Valid).To(BeTrue())
|
||||
Expect(res.UserName).To(Equal("ListenBrainzUser"))
|
||||
})
|
||||
})
|
||||
|
|
@ -93,7 +95,7 @@ var _ = Describe("client", func() {
|
|||
|
||||
Describe("updateNowPlaying", func() {
|
||||
It("formats the request properly", func() {
|
||||
Expect(client.updateNowPlaying(context.Background(), "LB-TOKEN", li)).To(Succeed())
|
||||
Expect(client.updateNowPlaying(ctx, "LB-TOKEN", li)).To(Succeed())
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodPost))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens"))
|
||||
Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
|
||||
|
|
@ -111,7 +113,7 @@ var _ = Describe("client", func() {
|
|||
})
|
||||
|
||||
It("formats the request properly", func() {
|
||||
Expect(client.scrobble(context.Background(), "LB-TOKEN", li)).To(Succeed())
|
||||
Expect(client.scrobble(ctx, "LB-TOKEN", li)).To(Succeed())
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodPost))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens"))
|
||||
Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
|
||||
|
|
@ -131,7 +133,7 @@ var _ = Describe("client", func() {
|
|||
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)),
|
||||
StatusCode: 400,
|
||||
}
|
||||
_, err := client.getArtistUrl(context.Background(), "1")
|
||||
_, err := client.getArtistUrl(ctx, "1")
|
||||
Expect(err.Error()).To(Equal("ListenBrainz error(400): artist mbid 1 is not valid."))
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=1"))
|
||||
|
|
@ -143,7 +145,7 @@ var _ = Describe("client", func() {
|
|||
Body: io.NopCloser(bytes.NewBufferString(``)),
|
||||
StatusCode: 501,
|
||||
}
|
||||
_, err := client.getArtistUrl(context.Background(), "1")
|
||||
_, err := client.getArtistUrl(ctx, "1")
|
||||
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (501)"))
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=1"))
|
||||
|
|
@ -153,7 +155,7 @@ var _ = Describe("client", 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")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
_, err := client.getArtistUrl(context.Background(), "7c2cc610-f998-43ef-a08f-dae3344b8973")
|
||||
_, err := client.getArtistUrl(ctx, "7c2cc610-f998-43ef-a08f-dae3344b8973")
|
||||
Expect(err.Error()).To(Equal("listenbrainz: not found"))
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=7c2cc610-f998-43ef-a08f-dae3344b8973"))
|
||||
|
|
@ -163,7 +165,7 @@ var _ = Describe("client", func() {
|
|||
It("It returns data when the artist has a homepage", func() {
|
||||
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
url, err := client.getArtistUrl(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")
|
||||
url, err := client.getArtistUrl(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(url).To(Equal("http://projectmili.com/"))
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
|
|
@ -180,7 +182,7 @@ var _ = Describe("client", func() {
|
|||
Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)),
|
||||
StatusCode: 400,
|
||||
}
|
||||
_, err := client.getArtistTopSongs(context.Background(), "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(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1"))
|
||||
|
|
@ -192,7 +194,7 @@ var _ = Describe("client", func() {
|
|||
Body: io.NopCloser(bytes.NewBufferString(``)),
|
||||
StatusCode: 500,
|
||||
}
|
||||
_, err := client.getArtistTopSongs(context.Background(), "1", 1)
|
||||
_, err := client.getArtistTopSongs(ctx, "1", 1)
|
||||
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (500)"))
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1"))
|
||||
|
|
@ -202,7 +204,7 @@ var _ = Describe("client", func() {
|
|||
It("It returns all tracks when given the opportunity", func() {
|
||||
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
data, err := client.getArtistTopSongs(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 5)
|
||||
data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 5)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]trackInfo{
|
||||
{
|
||||
|
|
@ -232,7 +234,7 @@ var _ = Describe("client", func() {
|
|||
It("It returns a subset of tracks when allowed", func() {
|
||||
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
data, err := client.getArtistTopSongs(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
|
||||
data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(data).To(Equal([]trackInfo{
|
||||
{
|
||||
|
|
@ -269,7 +271,7 @@ var _ = Describe("client", func() {
|
|||
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
|
||||
StatusCode: 400,
|
||||
}
|
||||
_, err := client.getSimilarArtists(context.Background(), "1", 2)
|
||||
_, err := client.getSimilarArtists(ctx, "1", 2)
|
||||
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)"))
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl("1")))
|
||||
|
|
@ -279,7 +281,7 @@ var _ = Describe("client", func() {
|
|||
It("handles real data properly", func() {
|
||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
resp, err := client.getSimilarArtists(context.Background(), mbid, 2)
|
||||
resp, err := client.getSimilarArtists(ctx, mbid, 2)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||
|
|
@ -293,7 +295,7 @@ var _ = Describe("client", func() {
|
|||
It("truncates data when requested", func() {
|
||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
resp, err := client.getSimilarArtists(context.Background(), "db92a151-1ac2-438b-bc43-b82e149ddd50", 1)
|
||||
resp, err := client.getSimilarArtists(ctx, "db92a151-1ac2-438b-bc43-b82e149ddd50", 1)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||
|
|
@ -309,7 +311,7 @@ var _ = Describe("client", func() {
|
|||
|
||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
resp, err := client.getSimilarArtists(context.Background(), mbid, 2)
|
||||
resp, err := client.getSimilarArtists(ctx, mbid, 2)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||
|
|
@ -339,7 +341,7 @@ var _ = Describe("client", func() {
|
|||
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
|
||||
StatusCode: 400,
|
||||
}
|
||||
_, err := client.getSimilarRecordings(context.Background(), "1", 2)
|
||||
_, err := client.getSimilarRecordings(ctx, "1", 2)
|
||||
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)"))
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl("1")))
|
||||
|
|
@ -349,7 +351,7 @@ var _ = Describe("client", func() {
|
|||
It("handles real data properly", func() {
|
||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
resp, err := client.getSimilarRecordings(context.Background(), mbid, 2)
|
||||
resp, err := client.getSimilarRecordings(ctx, mbid, 2)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||
|
|
@ -377,7 +379,7 @@ var _ = Describe("client", func() {
|
|||
It("truncates data when requested", func() {
|
||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
resp, err := client.getSimilarRecordings(context.Background(), mbid, 1)
|
||||
resp, err := client.getSimilarRecordings(ctx, mbid, 1)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||
|
|
@ -398,7 +400,7 @@ var _ = Describe("client", func() {
|
|||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings-real-out-of-order.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
// There are actually 5 items. The dedup should happen FIRST
|
||||
resp, err := client.getSimilarRecordings(context.Background(), mbid, 4)
|
||||
resp, err := client.getSimilarRecordings(ctx, mbid, 4)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||
|
|
@ -445,7 +447,7 @@ var _ = Describe("client", func() {
|
|||
|
||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
||||
resp, err := client.getSimilarRecordings(context.Background(), mbid, 1)
|
||||
resp, err := client.getSimilarRecordings(ctx, mbid, 1)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||
|
|
@ -470,7 +472,7 @@ var _ = Describe("client", func() {
|
|||
Header: http.Header{"X-Ratelimit-Reset-In": []string{"3"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)),
|
||||
}
|
||||
_, err := client.validateToken(context.Background(), "token")
|
||||
_, err := client.validateToken(ctx, "token")
|
||||
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
||||
retry, ok := errors.AsType[*agents.RetryLaterError](err)
|
||||
Expect(ok).To(BeTrue())
|
||||
|
|
@ -482,7 +484,7 @@ var _ = Describe("client", func() {
|
|||
StatusCode: 429,
|
||||
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
|
||||
}
|
||||
_, err := client.validateToken(context.Background(), "token")
|
||||
_, err := client.validateToken(ctx, "token")
|
||||
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
||||
retry, _ := errors.AsType[*agents.RetryLaterError](err)
|
||||
Expect(retry.RetryIn).To(BeZero())
|
||||
|
|
@ -495,7 +497,7 @@ var _ = Describe("client", func() {
|
|||
Header: http.Header{"X-Ratelimit-Reset-In": []string{header}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
|
||||
}
|
||||
_, err := client.validateToken(context.Background(), "token")
|
||||
_, err := client.validateToken(ctx, "token")
|
||||
retry, _ := errors.AsType[*agents.RetryLaterError](err)
|
||||
Expect(retry.RetryIn).To(Equal(time.Hour))
|
||||
},
|
||||
|
|
@ -511,7 +513,7 @@ var _ = Describe("client", func() {
|
|||
Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)),
|
||||
}
|
||||
_, err := client.validateToken(context.Background(), "token")
|
||||
_, err := client.validateToken(ctx, "token")
|
||||
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
||||
retry, ok := errors.AsType[*agents.RetryLaterError](err)
|
||||
Expect(ok).To(BeTrue())
|
||||
|
|
@ -524,7 +526,7 @@ var _ = Describe("client", func() {
|
|||
Header: http.Header{"X-Ratelimit-Reset-In": []string{"5"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
|
||||
}
|
||||
_, err := client.getArtistUrl(context.Background(), "1")
|
||||
_, err := client.getArtistUrl(ctx, "1")
|
||||
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
||||
retry, ok := errors.AsType[*agents.RetryLaterError](err)
|
||||
Expect(ok).To(BeTrue())
|
||||
|
|
|
|||
|
|
@ -55,9 +55,10 @@ var _ = Describe("parseArtworkKind", func() {
|
|||
|
||||
var _ = Describe("resolveArtworkTargets", func() {
|
||||
var ds *tests.MockDataStore
|
||||
ctx := context.Background()
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
artists := tests.CreateMockArtistRepo()
|
||||
artists.SetData(model.Artists{{ID: "artist1"}})
|
||||
ds = &tests.MockDataStore{MockedArtist: artists}
|
||||
|
|
@ -424,9 +425,9 @@ var _ = Describe("explainConfig", func() {
|
|||
|
||||
var _ = Describe("artwork refresh command", func() {
|
||||
It("requires at least one argument", func() {
|
||||
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{})).To(HaveOccurred())
|
||||
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"id1"})).ToNot(HaveOccurred())
|
||||
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"ar", "id1"})).ToNot(HaveOccurred())
|
||||
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{})).ToNot(Succeed())
|
||||
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"id1"})).To(Succeed())
|
||||
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"ar", "id1"})).To(Succeed())
|
||||
})
|
||||
})
|
||||
|
||||
|
|
@ -474,7 +475,10 @@ var _ = Describe("artwork reprocess selection", func() {
|
|||
})
|
||||
|
||||
var _ = Describe("explain/reprocess source round trip", func() {
|
||||
ctx := context.Background()
|
||||
var ctx context.Context
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
})
|
||||
|
||||
// storedSource reads back the Source line explain printed, as an operator would copy it.
|
||||
storedSource := func(out string) string {
|
||||
|
|
@ -566,7 +570,7 @@ var _ = Describe("reprocessArtwork", func() {
|
|||
var queue *tests.MockArtworkQueueRepo
|
||||
var out strings.Builder
|
||||
var imageAgents artwork.ImageAgentCount
|
||||
ctx := context.Background()
|
||||
var ctx context.Context
|
||||
kinds := []model.Kind{model.KindArtistArtwork, model.KindAlbumArtwork}
|
||||
accept := func(io.Writer, int64, int64) bool { return true }
|
||||
decline := func(io.Writer, int64, int64) bool { return false }
|
||||
|
|
@ -577,6 +581,7 @@ var _ = Describe("reprocessArtwork", func() {
|
|||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "cover.*, external"
|
||||
c.ArtistArtPriority = "artist.*, external"
|
||||
|
|
@ -805,8 +810,8 @@ var _ = Describe("reprocessArtwork", func() {
|
|||
|
||||
var _ = Describe("artwork status command", func() {
|
||||
It("takes no arguments", func() {
|
||||
Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{})).ToNot(HaveOccurred())
|
||||
Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{"x"})).To(HaveOccurred())
|
||||
Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{})).To(Succeed())
|
||||
Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{"x"})).ToNot(Succeed())
|
||||
})
|
||||
})
|
||||
|
||||
|
|
@ -814,9 +819,10 @@ var _ = Describe("collectStatus", func() {
|
|||
var ds *tests.MockDataStore
|
||||
var art *tests.MockArtworkRepo
|
||||
var queue *tests.MockArtworkQueueRepo
|
||||
ctx := context.Background()
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
ds = &tests.MockDataStore{}
|
||||
art = ds.Artwork().(*tests.MockArtworkRepo)
|
||||
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo)
|
||||
|
|
@ -969,9 +975,10 @@ var _ = Describe("refreshItems", func() {
|
|||
var queue *tests.MockArtworkQueueRepo
|
||||
var art *tests.MockArtworkRepo
|
||||
var out strings.Builder
|
||||
ctx := context.Background()
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
albums := tests.CreateMockAlbumRepo()
|
||||
albums.SetData(model.Albums{{ID: "al-1"}, {ID: "al-3"}})
|
||||
ds = &tests.MockDataStore{MockedAlbum: albums}
|
||||
|
|
@ -1143,11 +1150,12 @@ var _ = Describe("cancelArtwork", func() {
|
|||
var ds *tests.MockDataStore
|
||||
var queue *tests.MockArtworkQueueRepo
|
||||
var out strings.Builder
|
||||
ctx := context.Background()
|
||||
var ctx context.Context
|
||||
accept := func(io.Writer, int64, int64) bool { return true }
|
||||
decline := func(io.Writer, int64, int64) bool { return false }
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
ds = &tests.MockDataStore{}
|
||||
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo)
|
||||
out.Reset()
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ var _ = Describe("doctor", func() {
|
|||
// A file-backed DB so specs can corrupt raw pages; a table named like a real FTS
|
||||
// search table so IsFTSCorruptionOnly matches, plus a parent/child pair for FK checks.
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
dbPath = filepath.Join(GinkgoT().TempDir(), "doctor.db")
|
||||
reopen = func() {
|
||||
var err error
|
||||
|
|
|
|||
|
|
@ -50,11 +50,11 @@ func prettyMarshal(v any) ([]byte, error) {
|
|||
out := v.([]core.InspectOutput)
|
||||
var res strings.Builder
|
||||
for i := range out {
|
||||
res.WriteString(fmt.Sprintf("====================\nFile: %s\n\n", out[i].File))
|
||||
fmt.Fprintf(&res, "====================\nFile: %s\n\n", out[i].File)
|
||||
t, _ := toml.Marshal(out[i].RawTags)
|
||||
res.WriteString(fmt.Sprintf("Raw tags:\n%s\n\n", t))
|
||||
fmt.Fprintf(&res, "Raw tags:\n%s\n\n", t)
|
||||
t, _ = toml.Marshal(out[i].MappedTags)
|
||||
res.WriteString(fmt.Sprintf("Mapped tags:\n%s\n\n", t))
|
||||
fmt.Fprintf(&res, "Mapped tags:\n%s\n\n", t)
|
||||
}
|
||||
return []byte(res.String()), nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -94,7 +94,10 @@ func writeMissingList(w io.Writer, format string, mfs model.MediaFileCursor) err
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
j, _ := json.Marshal(displayMissingFile{ID: mf.ID, LibraryID: mf.LibraryID, Title: mf.Title, Album: mf.Album, Artist: mf.Artist, Path: mf.Path})
|
||||
j, err := json.Marshal(displayMissingFile{ID: mf.ID, LibraryID: mf.LibraryID, Title: mf.Title, Album: mf.Album, Artist: mf.Artist, Path: mf.Path})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = fmt.Fprintf(bw, "%s%s", sep, j)
|
||||
sep = ","
|
||||
}
|
||||
|
|
|
|||
|
|
@ -247,7 +247,10 @@ func runList(ctx context.Context) {
|
|||
display[idx].Public = playlist.Public
|
||||
}
|
||||
|
||||
j, _ := json.Marshal(display)
|
||||
j, err := json.Marshal(display)
|
||||
if err != nil {
|
||||
log.Fatal(ctx, "Failed to encode playlists", err)
|
||||
}
|
||||
fmt.Printf("%s\n", j)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -504,13 +504,13 @@ func usersToJSON(value string) (string, error) {
|
|||
return value, nil
|
||||
}
|
||||
var names []string
|
||||
for _, u := range strings.Split(value, ",") {
|
||||
for u := range strings.SplitSeq(value, ",") {
|
||||
if u = strings.TrimSpace(u); u != "" {
|
||||
names = append(names, u)
|
||||
}
|
||||
}
|
||||
b, _ := json.Marshal(names)
|
||||
return string(b), nil
|
||||
b, err := json.Marshal(names)
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
// librariesToJSON accepts either a JSON array (starts with '[') or a
|
||||
|
|
@ -526,7 +526,7 @@ func librariesToJSON(value string) (string, error) {
|
|||
return value, nil
|
||||
}
|
||||
ids := []int{}
|
||||
for _, l := range strings.Split(value, ",") {
|
||||
for l := range strings.SplitSeq(value, ",") {
|
||||
if l = strings.TrimSpace(l); l != "" {
|
||||
id, err := strconv.Atoi(l)
|
||||
if err != nil {
|
||||
|
|
@ -535,8 +535,8 @@ func librariesToJSON(value string) (string, error) {
|
|||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
b, _ := json.Marshal(ids)
|
||||
return string(b), nil
|
||||
b, err := json.Marshal(ids)
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
var pluginRescanCmd = &cobra.Command{
|
||||
|
|
|
|||
|
|
@ -65,16 +65,21 @@ var _ = Describe("formatPluginList", func() {
|
|||
})
|
||||
|
||||
var _ = Describe("enable/disable plugin", func() {
|
||||
var ctx context.Context
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
})
|
||||
|
||||
It("calls EnablePlugin on the manager", func() {
|
||||
mgr := &tests.MockPluginManager{}
|
||||
err := enablePlugin(context.Background(), mgr, "alpha")
|
||||
err := enablePlugin(ctx, mgr, "alpha")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mgr.EnablePluginCalls).To(Equal([]string{"alpha"}))
|
||||
})
|
||||
|
||||
It("calls DisablePlugin on the manager", func() {
|
||||
mgr := &tests.MockPluginManager{}
|
||||
err := disablePlugin(context.Background(), mgr, "beta")
|
||||
err := disablePlugin(ctx, mgr, "beta")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mgr.DisablePluginCalls).To(Equal([]string{"beta"}))
|
||||
})
|
||||
|
|
@ -82,14 +87,16 @@ var _ = Describe("enable/disable plugin", func() {
|
|||
|
||||
var _ = Describe("applyPluginEdit", func() {
|
||||
var cur *model.Plugin
|
||||
var ctx context.Context
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
cur = &model.Plugin{ID: "alpha", Users: `["bob"]`, Libraries: `[1,2]`, AllowWriteAccess: true}
|
||||
})
|
||||
|
||||
It("validates then updates config when config is provided", func() {
|
||||
mgr := &tests.MockPluginManager{}
|
||||
cfg := `{"key":"val"}`
|
||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{config: &cfg})
|
||||
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{config: &cfg})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mgr.ValidatePluginConfigCalls).To(HaveLen(1))
|
||||
Expect(mgr.ValidatePluginConfigCalls[0].ConfigJSON).To(Equal(cfg))
|
||||
|
|
@ -100,7 +107,7 @@ var _ = Describe("applyPluginEdit", func() {
|
|||
It("updates users with allUsers flag", func() {
|
||||
mgr := &tests.MockPluginManager{}
|
||||
all := true
|
||||
err := applyPluginEdit(context.Background(), mgr, cur,
|
||||
err := applyPluginEdit(ctx, mgr, cur,
|
||||
pluginEditOptions{allUsers: &all})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mgr.UpdatePluginUsersCalls).To(HaveLen(1))
|
||||
|
|
@ -111,7 +118,7 @@ var _ = Describe("applyPluginEdit", func() {
|
|||
mgr := &tests.MockPluginManager{}
|
||||
all := true
|
||||
wr := true
|
||||
err := applyPluginEdit(context.Background(), mgr, cur,
|
||||
err := applyPluginEdit(ctx, mgr, cur,
|
||||
pluginEditOptions{allLibraries: &all, writeAccess: &wr})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mgr.UpdatePluginLibrariesCalls).To(HaveLen(1))
|
||||
|
|
@ -122,7 +129,7 @@ var _ = Describe("applyPluginEdit", func() {
|
|||
It("preserves existing fields when only the write-access flag changes", func() {
|
||||
mgr := &tests.MockPluginManager{}
|
||||
no := false
|
||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{writeAccess: &no})
|
||||
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{writeAccess: &no})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mgr.UpdatePluginLibrariesCalls).To(HaveLen(1))
|
||||
Expect(mgr.UpdatePluginLibrariesCalls[0].LibrariesJSON).To(Equal(`[1,2]`)) // not wiped
|
||||
|
|
@ -132,7 +139,7 @@ var _ = Describe("applyPluginEdit", func() {
|
|||
It("preserves existing users when only the all-users flag changes", func() {
|
||||
mgr := &tests.MockPluginManager{}
|
||||
all := true
|
||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{allUsers: &all})
|
||||
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{allUsers: &all})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["bob"]`)) // not wiped
|
||||
})
|
||||
|
|
@ -140,7 +147,7 @@ var _ = Describe("applyPluginEdit", func() {
|
|||
It("parses a comma-separated users value into a JSON array", func() {
|
||||
mgr := &tests.MockPluginManager{}
|
||||
users := "alice, bob"
|
||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{users: &users})
|
||||
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{users: &users})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["alice","bob"]`))
|
||||
})
|
||||
|
|
@ -148,7 +155,7 @@ var _ = Describe("applyPluginEdit", func() {
|
|||
It("passes a JSON-array users value through unchanged", func() {
|
||||
mgr := &tests.MockPluginManager{}
|
||||
users := `["alice","bob"]`
|
||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{users: &users})
|
||||
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{users: &users})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["alice","bob"]`))
|
||||
})
|
||||
|
|
@ -156,7 +163,7 @@ var _ = Describe("applyPluginEdit", func() {
|
|||
It("rejects a malformed JSON-array users value", func() {
|
||||
mgr := &tests.MockPluginManager{}
|
||||
users := `["alice"`
|
||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{users: &users})
|
||||
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{users: &users})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(mgr.UpdatePluginUsersCalls).To(BeEmpty())
|
||||
})
|
||||
|
|
@ -164,7 +171,7 @@ var _ = Describe("applyPluginEdit", func() {
|
|||
It("parses a comma-separated libraries value into a JSON array of ints", func() {
|
||||
mgr := &tests.MockPluginManager{}
|
||||
libs := "1, 2"
|
||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{libraries: &libs})
|
||||
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{libraries: &libs})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mgr.UpdatePluginLibrariesCalls[0].LibrariesJSON).To(Equal(`[1,2]`))
|
||||
})
|
||||
|
|
@ -172,7 +179,7 @@ var _ = Describe("applyPluginEdit", func() {
|
|||
It("rejects a non-integer library ID", func() {
|
||||
mgr := &tests.MockPluginManager{}
|
||||
libs := "1,abc"
|
||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{libraries: &libs})
|
||||
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{libraries: &libs})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(mgr.UpdatePluginLibrariesCalls).To(BeEmpty())
|
||||
})
|
||||
|
|
@ -181,7 +188,7 @@ var _ = Describe("applyPluginEdit", func() {
|
|||
mgr := &tests.MockPluginManager{}
|
||||
cur.AllUsers = true
|
||||
users := "alice"
|
||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{users: &users})
|
||||
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{users: &users})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["alice"]`))
|
||||
Expect(mgr.UpdatePluginUsersCalls[0].AllUsers).To(BeFalse())
|
||||
|
|
@ -191,7 +198,7 @@ var _ = Describe("applyPluginEdit", func() {
|
|||
mgr := &tests.MockPluginManager{}
|
||||
cur.AllLibraries = true
|
||||
libs := "1"
|
||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{libraries: &libs})
|
||||
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{libraries: &libs})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mgr.UpdatePluginLibrariesCalls[0].LibrariesJSON).To(Equal(`[1]`))
|
||||
Expect(mgr.UpdatePluginLibrariesCalls[0].AllLibraries).To(BeFalse())
|
||||
|
|
@ -199,14 +206,14 @@ var _ = Describe("applyPluginEdit", func() {
|
|||
|
||||
It("does nothing and errors when no fields are set", func() {
|
||||
mgr := &tests.MockPluginManager{}
|
||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{})
|
||||
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
|
||||
It("aborts the config update when validation fails", func() {
|
||||
mgr := &tests.MockPluginManager{ValidateError: errors.New("bad config")}
|
||||
cfg := `{"key":"val"}`
|
||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{config: &cfg})
|
||||
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{config: &cfg})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(mgr.ValidatePluginConfigCalls).To(HaveLen(1))
|
||||
Expect(mgr.UpdatePluginConfigCalls).To(BeEmpty())
|
||||
|
|
@ -353,7 +360,7 @@ var _ = Describe("formatManifestInfo enriched text", func() {
|
|||
var _ = Describe("rescanPlugins", func() {
|
||||
It("calls RescanPlugins on the manager", func() {
|
||||
mgr := &tests.MockPluginManager{}
|
||||
err := rescanPlugins(context.Background(), mgr)
|
||||
err := rescanPlugins(GinkgoT().Context(), mgr)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mgr.RescanPluginsCalls).To(Equal(1))
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
|
|
@ -18,7 +17,7 @@ var _ = Describe("trackScanInteractively", func() {
|
|||
progress <- &scanner.ProgressInfo{Error: "scan failed"}
|
||||
close(progress)
|
||||
|
||||
changesDetected, err := trackScanInteractively(context.Background(), progress)
|
||||
changesDetected, err := trackScanInteractively(GinkgoT().Context(), progress)
|
||||
Expect(changesDetected).To(BeTrue())
|
||||
Expect(err).To(MatchError("scan failed"))
|
||||
})
|
||||
|
|
|
|||
|
|
@ -469,7 +469,10 @@ func runUserList(ctx context.Context) {
|
|||
users[idx].Libraries = paths
|
||||
}
|
||||
|
||||
j, _ := json.Marshal(users)
|
||||
j, err := json.Marshal(users)
|
||||
if err != nil {
|
||||
log.Fatal(ctx, "Failed to encode users", err)
|
||||
}
|
||||
fmt.Printf("%s\n", j)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -176,6 +176,7 @@ type scannerOptions struct {
|
|||
GroupAlbumReleases bool // Deprecated: Use PID.Album instead
|
||||
FollowSymlinks bool // Whether to follow symlinks when scanning directories
|
||||
IgnoreDotFolders bool // Whether to ignore folders whose name starts with a dot when scanning
|
||||
RespectNoMedia bool // Whether to skip folders (and their subfolders) containing a .nomedia file
|
||||
PurgeMissing string // Values: "never", "always", "full"
|
||||
}
|
||||
|
||||
|
|
@ -206,10 +207,11 @@ type TagConf struct {
|
|||
|
||||
type lastfmOptions struct {
|
||||
Enabled bool
|
||||
ApiKey string //nolint:gosec
|
||||
Secret string //nolint:gosec
|
||||
ApiKey string
|
||||
Secret string
|
||||
Language string
|
||||
ScrobbleFirstArtistOnly bool
|
||||
MinScrobbleDuration time.Duration
|
||||
|
||||
// Computed values
|
||||
Languages []string `conf:"-"` // Computed from Language, split by comma
|
||||
|
|
@ -251,7 +253,7 @@ type httpHeaderOptions struct {
|
|||
type prometheusOptions struct {
|
||||
Enabled bool
|
||||
MetricsPath string
|
||||
Password string //nolint:gosec
|
||||
Password string
|
||||
}
|
||||
|
||||
type AudioDeviceDefinition []string
|
||||
|
|
@ -424,6 +426,8 @@ func Load(noConfigDump bool) {
|
|||
durationNonNegativeOrDefault(&s.DevInsightsInitialDelay, consts.InsightsInitialDelay)
|
||||
durationNonNegativeOrDefault(&s.DevPluginCompilationTimeout, consts.DefaultPluginCompilationTimeout)
|
||||
|
||||
durationNonNegativeOrDefault(&s.LastFM.MinScrobbleDuration, consts.DefaultMinScrobbleDuration)
|
||||
|
||||
// Log deprecated, removed and unknown options
|
||||
for _, o := range deprecatedOptions {
|
||||
logDeprecatedOptions(o.name, o.replacement)
|
||||
|
|
@ -1054,6 +1058,7 @@ func setViperDefaults() {
|
|||
viper.SetDefault("scanner.groupalbumreleases", false)
|
||||
viper.SetDefault("scanner.followsymlinks", true)
|
||||
viper.SetDefault("scanner.ignoredotfolders", true)
|
||||
viper.SetDefault("scanner.respectnomedia", false)
|
||||
viper.SetDefault("scanner.purgemissing", consts.PurgeMissingNever)
|
||||
viper.SetDefault("subsonic.appendsubtitle", true)
|
||||
viper.SetDefault("subsonic.appendalbumversion", true)
|
||||
|
|
@ -1071,6 +1076,7 @@ func setViperDefaults() {
|
|||
viper.SetDefault("lastfm.apikey", "")
|
||||
viper.SetDefault("lastfm.secret", "")
|
||||
viper.SetDefault("lastfm.scrobblefirstartistonly", false)
|
||||
viper.SetDefault("lastfm.minscrobbleduration", consts.DefaultMinScrobbleDuration)
|
||||
viper.SetDefault("deezer.enabled", true)
|
||||
viper.SetDefault("deezer.language", consts.DefaultInfoLanguage)
|
||||
viper.SetDefault("listenbrainz.enabled", true)
|
||||
|
|
|
|||
|
|
@ -34,10 +34,7 @@ var _ = Describe("Configuration", func() {
|
|||
viper.SetDefault("loglevel", "error")
|
||||
conf.ResetConf()
|
||||
|
||||
// Panic instead of exiting on fatal errors to allow testing error conditions
|
||||
DeferCleanup(conf.SetLogFatal(func(args ...any) {
|
||||
panic(fmt.Sprint(args...))
|
||||
}))
|
||||
DeferCleanup(conf.PanicOnLogFatal())
|
||||
})
|
||||
|
||||
Describe("ParseLanguages", func() {
|
||||
|
|
@ -112,7 +109,7 @@ var _ = Describe("Configuration", func() {
|
|||
|
||||
It("rejects a URL that cannot be parsed", func() {
|
||||
fn := conf.ValidateURL("TestOption", "://invalid")
|
||||
Expect(fn()).To(HaveOccurred())
|
||||
Expect(fn()).ToNot(Succeed())
|
||||
})
|
||||
|
||||
It("rejects a URL without a host", func() {
|
||||
|
|
@ -404,6 +401,31 @@ var _ = Describe("Configuration", func() {
|
|||
})
|
||||
})
|
||||
|
||||
Describe("MinScrobbleDuration", func() {
|
||||
It("defaults to 30 seconds", func() {
|
||||
conf.Load(true)
|
||||
Expect(conf.Server().LastFM.MinScrobbleDuration).To(Equal(consts.DefaultMinScrobbleDuration))
|
||||
})
|
||||
|
||||
It("sets negative values to default", func() {
|
||||
viper.SetDefault("lastfm.minscrobbleduration", "-10s")
|
||||
conf.Load(true)
|
||||
Expect(conf.Server().LastFM.MinScrobbleDuration).To(Equal(consts.DefaultMinScrobbleDuration))
|
||||
})
|
||||
|
||||
It("disables with zero value", func() {
|
||||
viper.SetDefault("lastfm.minscrobbleduration", "0s")
|
||||
conf.Load(true)
|
||||
Expect(conf.Server().LastFM.MinScrobbleDuration).To(Equal(time.Duration(0)))
|
||||
})
|
||||
|
||||
It("preserves positive values", func() {
|
||||
viper.SetDefault("lastfm.minscrobbleduration", "45s")
|
||||
conf.Load(true)
|
||||
Expect(conf.Server().LastFM.MinScrobbleDuration).To(Equal(45 * time.Second))
|
||||
})
|
||||
})
|
||||
|
||||
Describe("Scanner.Extractor", func() {
|
||||
BeforeEach(func() {
|
||||
viper.Reset()
|
||||
|
|
|
|||
|
|
@ -82,20 +82,14 @@ var _ = Describe("Dir", func() {
|
|||
})
|
||||
|
||||
It("calls logFatal on error", func() {
|
||||
var fatalMsg []any
|
||||
restore := conf.SetLogFatal(func(args ...any) {
|
||||
fatalMsg = args
|
||||
panic("logFatal called")
|
||||
})
|
||||
DeferCleanup(restore)
|
||||
DeferCleanup(conf.PanicOnLogFatal())
|
||||
|
||||
f := GinkgoT().TempDir() + "/blocker"
|
||||
Expect(os.WriteFile(f, []byte("x"), 0600)).To(Succeed())
|
||||
invalid := f + "/subdir"
|
||||
|
||||
d := conf.NewDir(invalid)
|
||||
Expect(func() { d.MustPath() }).To(Panic())
|
||||
Expect(fatalMsg).ToNot(BeEmpty())
|
||||
Expect(func() { d.MustPath() }).To(PanicWith(ContainSubstring("creating directory")))
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
package conf
|
||||
|
||||
import "fmt"
|
||||
|
||||
func ResetConf() {
|
||||
current.Store(&Options{})
|
||||
}
|
||||
|
|
@ -33,6 +35,13 @@ func SetLogFatal(f func(...any)) func() {
|
|||
return func() { logFatal = old }
|
||||
}
|
||||
|
||||
// PanicOnLogFatal stops the caller the way os.Exit would, so specs can assert on the fatal message.
|
||||
func PanicOnLogFatal() func() {
|
||||
return SetLogFatal(func(args ...any) {
|
||||
panic(fmt.Sprint(args...)) //nolint:forbidigo
|
||||
})
|
||||
}
|
||||
|
||||
var UnknownConfigKeys = unknownConfigKeys
|
||||
|
||||
var SuggestOptions = suggestOptions
|
||||
|
|
|
|||
|
|
@ -83,6 +83,8 @@ const (
|
|||
|
||||
DefaultInfoLanguage = "en"
|
||||
|
||||
DefaultMinScrobbleDuration = 30 * time.Second
|
||||
|
||||
ArtistInfoTimeToLive = 24 * time.Hour
|
||||
AlbumInfoTimeToLive = 7 * 24 * time.Hour
|
||||
UpdateLastAccessFrequency = time.Minute
|
||||
|
|
@ -90,6 +92,7 @@ const (
|
|||
|
||||
I18nFolder = "i18n"
|
||||
ScanIgnoreFile = ".ndignore"
|
||||
NoMediaFile = ".nomedia"
|
||||
ArtworkFolder = "artwork"
|
||||
// HashedArtworkFolder is a subtree of ArtworkFolder, kept apart from the name-addressed
|
||||
// upload folders beside it so Prune's sweep never reaches them.
|
||||
|
|
|
|||
|
|
@ -157,7 +157,7 @@ func (a *Agents) getAgent(ea enabledAgent) Interface {
|
|||
if agent != nil {
|
||||
return agent
|
||||
}
|
||||
log.Debug("Built-in agent not available. Missing configuration?", "name", ea.name)
|
||||
log.Debug("Built-in agent not available. Disabled or missing configuration?", "name", ea.name)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -55,10 +55,12 @@ var _ ArtistMBIDRetriever = (*MockAgent)(nil)
|
|||
var _ PluginLoader = (*MockPluginLoader)(nil)
|
||||
|
||||
var _ = Describe("Agents with Plugin Loading", func() {
|
||||
var ctx context.Context
|
||||
var mockLoader *MockPluginLoader
|
||||
var agents *Agents
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
mockLoader = NewMockPluginLoader()
|
||||
|
||||
// Create the agents instance with our mock loader
|
||||
|
|
@ -144,8 +146,6 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
|||
})
|
||||
|
||||
It("should load plugin agents on demand", func() {
|
||||
ctx := context.Background()
|
||||
|
||||
// Configure to use our plugin
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "plugin_agent" })
|
||||
|
||||
|
|
@ -236,8 +236,6 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
|||
})
|
||||
|
||||
It("should NOT call LoadMediaAgent for built-in agents", func() {
|
||||
ctx := context.Background()
|
||||
|
||||
// Create a mock built-in agent
|
||||
Register("builtin_agent", func(ds model.DataStore) Interface {
|
||||
return &MockAgent{
|
||||
|
|
@ -263,8 +261,6 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
|||
})
|
||||
|
||||
It("should NOT call LoadMediaAgent for invalid agent names", func() {
|
||||
ctx := context.Background()
|
||||
|
||||
// Configure with an invalid agent name (not built-in, not a plugin)
|
||||
conf.Update(func(c *conf.Options) { c.Agents = "invalid_agent" })
|
||||
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ var _ = Describe("Agents", func() {
|
|||
var ds model.DataStore
|
||||
var mfRepo *tests.MockMediaFileRepo
|
||||
BeforeEach(func() {
|
||||
ctx, cancel = context.WithCancel(context.Background())
|
||||
ctx, cancel = context.WithCancel(GinkgoT().Context())
|
||||
mfRepo = tests.CreateMockMediaFileRepo()
|
||||
ds = &tests.MockDataStore{MockedMediaFile: mfRepo}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ var _ = Describe("localAgent GetSimilarSongsByTrack", func() {
|
|||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
mfRepo = &tests.MockMediaFileRepo{}
|
||||
ds = &tests.MockDataStore{MockedMediaFile: mfRepo}
|
||||
agent = &localAgent{ds: ds}
|
||||
|
|
|
|||
|
|
@ -11,16 +11,20 @@ import (
|
|||
)
|
||||
|
||||
var _ = Describe("SessionKeys", func() {
|
||||
ctx := context.Background()
|
||||
var ctx context.Context
|
||||
user := model.User{ID: "u-1"}
|
||||
ds := &tests.MockDataStore{MockedUserProps: &tests.MockedUserPropsRepo{}}
|
||||
sk := SessionKeys{DataStore: ds, KeyName: "fakeSessionKey"}
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
})
|
||||
|
||||
It("uses the assigned key name", func() {
|
||||
Expect(sk.KeyName).To(Equal("fakeSessionKey"))
|
||||
})
|
||||
It("stores a value in the DB", func() {
|
||||
Expect(sk.Put(ctx, user.ID, "test-stored-value")).To(BeNil())
|
||||
Expect(sk.Put(ctx, user.ID, "test-stored-value")).To(Succeed())
|
||||
})
|
||||
It("fetches the stored value", func() {
|
||||
value, err := sk.Get(ctx, user.ID)
|
||||
|
|
@ -28,7 +32,7 @@ var _ = Describe("SessionKeys", func() {
|
|||
Expect(value).To(Equal("test-stored-value"))
|
||||
})
|
||||
It("deletes the stored value", func() {
|
||||
Expect(sk.Delete(ctx, user.ID)).To(BeNil())
|
||||
Expect(sk.Delete(ctx, user.ID)).To(Succeed())
|
||||
})
|
||||
It("handles a not found value", func() {
|
||||
_, err := sk.Get(ctx, "u-2")
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ import (
|
|||
|
||||
var _ = Describe("Archiver", func() {
|
||||
var (
|
||||
ctx context.Context
|
||||
arch core.Archiver
|
||||
ms *mockMediaStreamer
|
||||
dc *fakeDecider
|
||||
|
|
@ -32,6 +33,7 @@ var _ = Describe("Archiver", func() {
|
|||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
ms = &mockMediaStreamer{}
|
||||
dc = &fakeDecider{}
|
||||
sh = &mockShare{}
|
||||
|
|
@ -57,13 +59,13 @@ var _ = Describe("Archiver", func() {
|
|||
ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(3)
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
err := arch.ZipAlbum(context.Background(), "1", "mp3", 128, out)
|
||||
Expect(err).To(BeNil())
|
||||
err := arch.ZipAlbum(ctx, "1", "mp3", 128, out)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(len(zr.File)).To(Equal(2))
|
||||
Expect(zr.File).To(HaveLen(2))
|
||||
Expect(zr.File[0].Name).To(Equal("Album_Promo/01 - track1.mp3"))
|
||||
Expect(zr.File[1].Name).To(Equal("Album_Promo/02 - track2.mp3"))
|
||||
})
|
||||
|
|
@ -106,13 +108,13 @@ var _ = Describe("Archiver", func() {
|
|||
ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2)
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
err := arch.ZipArtist(context.Background(), "1", "mp3", 128, out)
|
||||
Expect(err).To(BeNil())
|
||||
err := arch.ZipArtist(ctx, "1", "mp3", 128, out)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(len(zr.File)).To(Equal(2))
|
||||
Expect(zr.File).To(HaveLen(2))
|
||||
Expect(zr.File[0].Name).To(Equal("Album 1/01 - track1.mp3"))
|
||||
Expect(zr.File[1].Name).To(Equal("Album 1/02 - track2.mp3"))
|
||||
})
|
||||
|
|
@ -127,9 +129,9 @@ var _ = Describe("Archiver", func() {
|
|||
ms.On("NewStream", mock.Anything, mock.Anything, mock.Anything).Return(io.NopCloser(strings.NewReader("test")), nil)
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
Expect(arch.ZipArtist(context.Background(), "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()))
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
names := make([]string, len(zr.File))
|
||||
for i, f := range zr.File {
|
||||
names[i] = f.Name
|
||||
|
|
@ -267,7 +269,7 @@ var _ = Describe("Archiver", func() {
|
|||
Return(nil, stream.ErrTooManyTranscodes).Once()
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
err := arch.ZipAlbum(context.Background(), "1", "mp3", 128, out)
|
||||
err := arch.ZipAlbum(ctx, "1", "mp3", 128, out)
|
||||
Expect(err).To(MatchError(stream.ErrTooManyTranscodes))
|
||||
// NewStream should only have been called once: the loop must bail
|
||||
// out on the rejection instead of trying every remaining track.
|
||||
|
|
@ -293,17 +295,17 @@ var _ = Describe("Archiver", func() {
|
|||
ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2)
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
err := arch.ZipShare(context.Background(), share, out)
|
||||
Expect(err).To(BeNil())
|
||||
err := arch.ZipShare(ctx, share, out)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
// Share.Load records a visit; re-loading here would double-count
|
||||
// every download.
|
||||
sh.AssertNotCalled(GinkgoT(), "Load", mock.Anything, mock.Anything)
|
||||
|
||||
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(len(zr.File)).To(Equal(2))
|
||||
Expect(zr.File).To(HaveLen(2))
|
||||
Expect(zr.File[0].Name).To(Equal("01 - Artist 1 - track1.mp3"))
|
||||
Expect(zr.File[1].Name).To(Equal("02 - Artist 2 - track2.mp3"))
|
||||
|
||||
|
|
@ -313,7 +315,7 @@ var _ = Describe("Archiver", func() {
|
|||
Context("ZipPlaylist", 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{
|
||||
{MediaFile: model.MediaFile{Path: "test_data/01 - track1.flac", Suffix: "flac", Artist: "Artist 1", Title: "track1"}},
|
||||
{Path: "test_data/01 - track1.flac", Suffix: "flac", Artist: "Artist 1", Title: "track1"},
|
||||
}}
|
||||
plRepo := &mockPlaylistRepository{}
|
||||
plRepo.On("GetWithTracks", "1", true, false).Return(pls, nil)
|
||||
|
|
@ -337,8 +339,8 @@ var _ = Describe("Archiver", func() {
|
|||
|
||||
It("zips a playlist correctly", func() {
|
||||
tracks := []model.PlaylistTrack{
|
||||
{MediaFile: model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "AC/DC", Title: "track1"}},
|
||||
{MediaFile: model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "Artist 2", Title: "track2"}},
|
||||
{Path: "test_data/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"},
|
||||
}
|
||||
|
||||
pls := &model.Playlist{
|
||||
|
|
@ -353,24 +355,24 @@ var _ = Describe("Archiver", func() {
|
|||
ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2)
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
err := arch.ZipPlaylist(context.Background(), "1", "mp3", 128, out)
|
||||
Expect(err).To(BeNil())
|
||||
err := arch.ZipPlaylist(ctx, "1", "mp3", 128, out)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(len(zr.File)).To(Equal(3))
|
||||
Expect(zr.File).To(HaveLen(3))
|
||||
Expect(zr.File[0].Name).To(Equal("01 - AC_DC - track1.mp3"))
|
||||
Expect(zr.File[1].Name).To(Equal("02 - Artist 2 - track2.mp3"))
|
||||
Expect(zr.File[2].Name).To(Equal("Test Playlist.m3u"))
|
||||
|
||||
// Verify M3U content
|
||||
m3uFile, err := zr.File[2].Open()
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
defer m3uFile.Close()
|
||||
|
||||
m3uContent, err := io.ReadAll(m3uFile)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
expectedM3U := "#EXTM3U\n#PLAYLIST:Test Playlist\n#EXTINF:0,AC/DC - track1\n01 - AC_DC - track1.mp3\n#EXTINF:0,Artist 2 - track2\n02 - Artist 2 - track2.mp3\n"
|
||||
Expect(string(m3uContent)).To(Equal(expectedM3U))
|
||||
|
|
@ -396,7 +398,7 @@ var _ = Describe("Archiver", func() {
|
|||
})
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
Expect(arch.ZipAlbum(context.Background(), "1", "mp3", 128, out)).To(Succeed())
|
||||
Expect(arch.ZipAlbum(ctx, "1", "mp3", 128, out)).To(Succeed())
|
||||
|
||||
files := readZip(out)
|
||||
Expect(files).To(HaveLen(2))
|
||||
|
|
@ -417,7 +419,7 @@ var _ = Describe("Archiver", func() {
|
|||
})
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
Expect(arch.ZipArtist(context.Background(), "1", "mp3", 128, out)).To(Succeed())
|
||||
Expect(arch.ZipArtist(ctx, "1", "mp3", 128, out)).To(Succeed())
|
||||
|
||||
files := readZip(out)
|
||||
Expect(files).To(HaveLen(5))
|
||||
|
|
@ -438,7 +440,7 @@ var _ = Describe("Archiver", func() {
|
|||
})
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
Expect(arch.ZipArtist(context.Background(), "1", "mp3", 128, out)).To(Succeed())
|
||||
Expect(arch.ZipArtist(ctx, "1", "mp3", 128, out)).To(Succeed())
|
||||
|
||||
files := readZip(out)
|
||||
Expect(files).To(HaveKeyWithValue("Greatest Hits [2001]/folder.jpg", jpegData))
|
||||
|
|
@ -452,14 +454,14 @@ var _ = Describe("Archiver", func() {
|
|||
ID: "1",
|
||||
Name: "Test Playlist",
|
||||
Tracks: []model.PlaylistTrack{
|
||||
{MediaFile: model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Artist: "Artist 1", Title: "track1"}},
|
||||
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Artist: "Artist 1", Title: "track1"},
|
||||
},
|
||||
}, nil)
|
||||
ds.On("Playlist", mock.Anything).Return(plRepo)
|
||||
ms.On("NewStream", mock.Anything, mock.Anything, mock.Anything).Return(io.NopCloser(strings.NewReader("test")), nil)
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
Expect(arch.ZipPlaylist(context.Background(), "1", "mp3", 128, out)).To(Succeed())
|
||||
Expect(arch.ZipPlaylist(ctx, "1", "mp3", 128, out)).To(Succeed())
|
||||
|
||||
files := readZip(out)
|
||||
Expect(files).To(HaveLen(3))
|
||||
|
|
@ -483,7 +485,7 @@ var _ = Describe("Archiver", func() {
|
|||
}
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
Expect(arch.ZipShare(context.Background(), share, out)).To(Succeed())
|
||||
Expect(arch.ZipShare(ctx, share, out)).To(Succeed())
|
||||
|
||||
files := readZip(out)
|
||||
Expect(files).To(HaveLen(2))
|
||||
|
|
@ -498,7 +500,7 @@ var _ = Describe("Archiver", func() {
|
|||
})
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
Expect(arch.ZipAlbum(context.Background(), "1", "mp3", 128, out)).To(Succeed())
|
||||
Expect(arch.ZipAlbum(ctx, "1", "mp3", 128, out)).To(Succeed())
|
||||
|
||||
files := readZip(out)
|
||||
Expect(files).To(HaveLen(1))
|
||||
|
|
|
|||
|
|
@ -75,7 +75,7 @@ var _ = Describe("agent images", func() {
|
|||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte("image-bytes"))
|
||||
}))
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@ var _ = Describe("Animation detection", func() {
|
|||
|
||||
// createAnimatedGIF creates a minimal animated GIF with the given number of frames.
|
||||
func createAnimatedGIF(frames int) []byte {
|
||||
GinkgoHelper()
|
||||
g := &gif.GIF{
|
||||
LoopCount: 0,
|
||||
}
|
||||
|
|
@ -74,10 +75,7 @@ func createAnimatedGIF(frames int) []byte {
|
|||
g.Delay = append(g.Delay, 10)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
err := gif.EncodeAll(&buf, g)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
Expect(gif.EncodeAll(&buf, g)).To(Succeed())
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
|
|
@ -151,11 +149,9 @@ func createAPNGBytes() []byte {
|
|||
|
||||
// createStaticPNGBytes creates a minimal valid static PNG.
|
||||
func createStaticPNGBytes() []byte {
|
||||
GinkgoHelper()
|
||||
img := image.NewRGBA(image.Rect(0, 0, 2, 2))
|
||||
var buf bytes.Buffer
|
||||
err := png.Encode(&buf, img)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
Expect(png.Encode(&buf, img)).To(Succeed())
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -70,7 +70,7 @@ var _ = Describe("Artwork", func() {
|
|||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
var err error
|
||||
repoRoot, err = os.Getwd()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
|
@ -114,7 +114,7 @@ var _ = Describe("Artwork", func() {
|
|||
It("serves a store-backed found image sized (cache miss resizes, second call is a cache hit)", func() {
|
||||
seedFoundStore("al", "al1", coverBytes)
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("al-al1"), 100, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("al-al1"), 100, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
// A resized response versions its ETag with the encode settings, not the pixel hash.
|
||||
Expect(img.ETag).To(Equal(representationTag(img.Hash, 100, false)))
|
||||
|
|
@ -128,7 +128,7 @@ var _ = Describe("Artwork", func() {
|
|||
hash, _ := hashImage(bytes.NewReader(coverBytes))
|
||||
Expect(os.Remove(store.path(hash, "image/jpeg"))).To(Succeed())
|
||||
Eventually(func(g Gomega) {
|
||||
img2, err := svc.Get(ctx, model.MustParseArtworkID("al-al1"), 100, false)
|
||||
img2, err := svc.Get(ctx, tests.MustParseArtworkID("al-al1"), 100, false)
|
||||
g.Expect(err).ToNot(HaveOccurred())
|
||||
g.Expect(readAll(img2)).To(Equal(resized))
|
||||
}).Should(Succeed())
|
||||
|
|
@ -137,7 +137,7 @@ var _ = Describe("Artwork", func() {
|
|||
It("treats a negative size as a full-size request, not a giant resize", func() {
|
||||
seedFoundStore("al", "alneg", coverBytes)
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("al-alneg"), -2000000000, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("al-alneg"), -2000000000, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(readAll(img)).To(Equal(coverBytes), "original bytes, no resize (would OOM)")
|
||||
})
|
||||
|
|
@ -154,7 +154,7 @@ var _ = Describe("Artwork", func() {
|
|||
Source: "folder", SourcePath: imgPath, RefMtime: mtime,
|
||||
})).To(Succeed())
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("al-al2"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("al-al2"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(readAll(img)).To(Equal(coverBytes))
|
||||
})
|
||||
|
|
@ -170,7 +170,7 @@ var _ = Describe("Artwork", func() {
|
|||
Source: "folder", SourcePath: secretPath, RefMtime: fileMtime(secretPath),
|
||||
})).To(Succeed())
|
||||
|
||||
_, err := svc.Get(ctx, model.MustParseArtworkID("al-alni"), 0, false)
|
||||
_, err := svc.Get(ctx, tests.MustParseArtworkID("al-alni"), 0, false)
|
||||
Expect(err).To(MatchError(ErrUnavailable))
|
||||
Expect(queueRepo.Data[primaryKey("al", "alni")].Priority).To(Equal(model.ArtworkPriorityScan))
|
||||
})
|
||||
|
|
@ -201,7 +201,7 @@ var _ = Describe("Artwork", func() {
|
|||
_ = s.Close()
|
||||
}).Should(Succeed())
|
||||
|
||||
_, err = svc.Get(ctx, model.MustParseArtworkID("al-alnic"), 100, false)
|
||||
_, err = svc.Get(ctx, tests.MustParseArtworkID("al-alnic"), 100, false)
|
||||
Expect(err).To(MatchError(ErrUnavailable))
|
||||
Expect(queueRepo.Data[primaryKey("al", "alnic")].Priority).To(Equal(model.ArtworkPriorityScan))
|
||||
})
|
||||
|
|
@ -217,7 +217,7 @@ var _ = Describe("Artwork", func() {
|
|||
Source: "folder", SourcePath: imgPath, RefMtime: fileMtime(imgPath) + 999,
|
||||
})).To(Succeed())
|
||||
|
||||
_, err := svc.Get(ctx, model.MustParseArtworkID("al-al3"), 0, false)
|
||||
_, err := svc.Get(ctx, tests.MustParseArtworkID("al-al3"), 0, false)
|
||||
Expect(err).To(MatchError(ErrUnavailable))
|
||||
Expect(queueRepo.Data[primaryKey("al", "al3")].Priority).To(Equal(model.ArtworkPriorityScan))
|
||||
ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al3", model.ImageTypePrimary)
|
||||
|
|
@ -236,7 +236,7 @@ var _ = Describe("Artwork", func() {
|
|||
Source: "folder", SourcePath: imgPath, RefMtime: fileMtime(imgPath) + 999,
|
||||
})).To(Succeed())
|
||||
|
||||
_, err := svc.Get(ctx, model.MustParseArtworkID("al-al3b"), 100, false)
|
||||
_, err := svc.Get(ctx, tests.MustParseArtworkID("al-al3b"), 100, false)
|
||||
Expect(err).To(MatchError(ErrUnavailable))
|
||||
Expect(queueRepo.Data[primaryKey("al", "al3b")].Priority).To(Equal(model.ArtworkPriorityScan))
|
||||
})
|
||||
|
|
@ -247,7 +247,7 @@ var _ = Describe("Artwork", func() {
|
|||
Expect(hash).ToNot(BeEmpty())
|
||||
albumRepo.SetData(model.Albums{}) // the album is deleted; its artwork row survives
|
||||
|
||||
_, err := svc.Get(ctx, model.MustParseArtworkID("al-alzz"), 0, false)
|
||||
_, err := svc.Get(ctx, tests.MustParseArtworkID("al-alzz"), 0, false)
|
||||
Expect(err).To(MatchError(ErrUnavailable))
|
||||
})
|
||||
|
||||
|
|
@ -256,7 +256,7 @@ var _ = Describe("Artwork", func() {
|
|||
ItemKind: "al", ItemID: "al4", AttemptedAt: time.Now().Add(-365 * 24 * time.Hour),
|
||||
})).To(Succeed())
|
||||
|
||||
_, err := svc.Get(ctx, model.MustParseArtworkID("al-al4"), 0, false)
|
||||
_, err := svc.Get(ctx, tests.MustParseArtworkID("al-al4"), 0, false)
|
||||
Expect(err).To(MatchError(ErrUnavailable))
|
||||
Expect(queueRepo.Data).To(BeEmpty())
|
||||
})
|
||||
|
|
@ -267,7 +267,7 @@ var _ = Describe("Artwork", func() {
|
|||
folderRepo.result = []model.Folder{{Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"}}}
|
||||
albumRepo.SetData(model.Albums{{ID: "al5", Name: "Album", FolderIDs: []string{"f1"}}})
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("al-al5"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("al-al5"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(readAll(img)).To(Equal(coverBytes))
|
||||
|
||||
|
|
@ -280,7 +280,7 @@ var _ = Describe("Artwork", func() {
|
|||
folderRepo.result = nil
|
||||
albumRepo.SetData(model.Albums{{ID: "al6", Name: "Album"}})
|
||||
|
||||
_, err := svc.Get(ctx, model.MustParseArtworkID("al-al6"), 0, false)
|
||||
_, err := svc.Get(ctx, tests.MustParseArtworkID("al-al6"), 0, false)
|
||||
Expect(err).To(MatchError(ErrUnavailable))
|
||||
Expect(queueRepo.Data[primaryKey("al", "al6")].Priority).To(Equal(model.ArtworkPriorityBump))
|
||||
_, err = artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al6", model.ImageTypePrimary)
|
||||
|
|
@ -292,7 +292,7 @@ var _ = Describe("Artwork", func() {
|
|||
It("serves a track's own found art", func() {
|
||||
seedFoundStore("mf", "mf1", coverBytes)
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("mf-mf1"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf1"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(readAll(img)).To(Equal(coverBytes))
|
||||
})
|
||||
|
|
@ -303,7 +303,7 @@ var _ = Describe("Artwork", func() {
|
|||
seedFoundStore("al", "albz", coverBytes)
|
||||
mfRepo.SetData(model.MediaFiles{{ID: "mf7", AlbumID: "albz"}})
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("mf-mf7"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf7"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(readAll(img)).To(Equal(coverBytes), "album art, not the persisted embedded art")
|
||||
})
|
||||
|
|
@ -313,7 +313,7 @@ var _ = Describe("Artwork", func() {
|
|||
Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "mf", ItemID: "mf2"})).To(Succeed())
|
||||
mfRepo.SetData(model.MediaFiles{{ID: "mf2", AlbumID: "albm"}})
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("mf-mf2"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf2"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(readAll(img)).To(Equal(coverBytes))
|
||||
_, mfEnq := queueRepo.Data[primaryKey("mf", "mf2")]
|
||||
|
|
@ -325,7 +325,7 @@ var _ = Describe("Artwork", func() {
|
|||
seedFoundStore("al", "albn", coverBytes)
|
||||
mfRepo.SetData(model.MediaFiles{{ID: "mf3", AlbumID: "albn", HasCoverArt: false}})
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("mf-mf3"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf3"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(readAll(img)).To(Equal(coverBytes))
|
||||
_, mfEnq := queueRepo.Data[primaryKey("mf", "mf3")]
|
||||
|
|
@ -339,9 +339,9 @@ var _ = Describe("Artwork", func() {
|
|||
Path: "tests/fixtures/artist/an-album/test.mp3", LibraryID: 0,
|
||||
}})
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("mf-mf4"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf4"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(len(readAll(img))).To(BeNumerically(">", 0))
|
||||
Expect(readAll(img)).ToNot(BeEmpty())
|
||||
Expect(queueRepo.Data[primaryKey("mf", "mf4")].Priority).To(Equal(model.ArtworkPriorityBump))
|
||||
_, err = artRepo.GetItemArtwork(ctx, model.KindMediaFileArtwork, "mf4", model.ImageTypePrimary)
|
||||
Expect(err).To(MatchError(model.ErrNotFound))
|
||||
|
|
@ -353,7 +353,7 @@ var _ = Describe("Artwork", func() {
|
|||
seedFoundStore("al", "aldd", []byte("album-art-distinct")) // album's own found art differs
|
||||
mfRepo.SetData(model.MediaFiles{{ID: "mf5", AlbumID: "aldd", DiscNumber: 1, HasCoverArt: false}})
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("mf-mf5"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf5"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
// The disc-folder image, not the album's own art: proof it routed through serveDisc.
|
||||
Expect(readAll(img)).To(Equal(coverBytes))
|
||||
|
|
@ -369,7 +369,7 @@ var _ = Describe("Artwork", func() {
|
|||
albumRepo.SetData(model.Albums{{ID: "albad", Name: "Album"}})
|
||||
seedFoundStore("al", "albad", coverBytes)
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("mf-mfbad"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mfbad"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(readAll(img)).To(Equal(coverBytes), "a placeholder here would be worse than the album cover")
|
||||
})
|
||||
|
|
@ -381,7 +381,7 @@ var _ = Describe("Artwork", func() {
|
|||
seedFoundStore("al", "alsd", []byte("album-art-distinct"))
|
||||
mfRepo.SetData(model.MediaFiles{{ID: "mf6", AlbumID: "alsd", DiscNumber: 1, HasCoverArt: false}})
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("mf-mf6"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf6"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(readAll(img)).To(Equal(coverBytes))
|
||||
})
|
||||
|
|
@ -529,7 +529,7 @@ var _ = Describe("EntityExists", func() {
|
|||
var ds *tests.MockDataStore
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
albumRepo := tests.CreateMockAlbumRepo()
|
||||
albumRepo.SetData(model.Albums{{ID: "al1"}})
|
||||
artistRepo := tests.CreateMockArtistRepo()
|
||||
|
|
@ -541,7 +541,7 @@ var _ = Describe("EntityExists", func() {
|
|||
|
||||
DescribeTable("reports whether the owning entity is still there",
|
||||
func(id string, expected bool) {
|
||||
Expect(entityExists(ctx, ds, model.MustParseArtworkID(id))).To(Equal(expected))
|
||||
Expect(entityExists(ctx, ds, tests.MustParseArtworkID(id))).To(Equal(expected))
|
||||
},
|
||||
Entry("existing album", "al-al1", true),
|
||||
Entry("deleted album", "al-gone", false),
|
||||
|
|
|
|||
|
|
@ -15,8 +15,14 @@ func BenchmarkImageDecode(b *testing.B) {
|
|||
name string
|
||||
gen func(tb testing.TB, w, h int) []byte
|
||||
}{
|
||||
{"jpeg", func(tb testing.TB, w, h int) []byte { return generateJPEG(tb, w, h, 75) }},
|
||||
{"png", func(tb testing.TB, w, h int) []byte { return generatePNG(tb, w, h) }},
|
||||
{"jpeg", func(tb testing.TB, w, h int) []byte {
|
||||
tb.Helper()
|
||||
return generateJPEG(tb, w, h, 75)
|
||||
}},
|
||||
{"png", func(tb testing.TB, w, h int) []byte {
|
||||
tb.Helper()
|
||||
return generatePNG(tb, w, h)
|
||||
}},
|
||||
}
|
||||
|
||||
for _, format := range formats {
|
||||
|
|
|
|||
|
|
@ -13,6 +13,12 @@ import (
|
|||
)
|
||||
|
||||
var _ = Describe("Disc Artwork Reader", func() {
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
})
|
||||
|
||||
Describe("extractDiscNumber", func() {
|
||||
DescribeTable("extracts disc number from filename based on glob pattern",
|
||||
func(pattern, filename string, expectedNum int, expectedOk bool) {
|
||||
|
|
@ -66,13 +72,9 @@ var _ = Describe("Disc Artwork Reader", func() {
|
|||
})
|
||||
|
||||
Describe("fromExternalFile", func() {
|
||||
var (
|
||||
ctx context.Context
|
||||
tmpDir string
|
||||
)
|
||||
var tmpDir string
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
tmpDir = GinkgoT().TempDir()
|
||||
})
|
||||
|
||||
|
|
@ -349,13 +351,9 @@ var _ = Describe("Disc Artwork Reader", func() {
|
|||
})
|
||||
|
||||
Describe("fromDiscSubtitle", func() {
|
||||
var (
|
||||
ctx context.Context
|
||||
tmpDir string
|
||||
)
|
||||
var tmpDir string
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
tmpDir = GinkgoT().TempDir()
|
||||
})
|
||||
|
||||
|
|
@ -453,10 +451,10 @@ var _ = Describe("Disc Artwork Reader", func() {
|
|||
|
||||
Describe("selectImage", func() {
|
||||
It("abandons the walk when the context is cancelled", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancelled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
|
||||
res, err := reader.selectImage(ctx, nil, "disc*.*, cover.*", &chainState{})
|
||||
res, err := reader.selectImage(cancelled, nil, "disc*.*, cover.*", &chainState{})
|
||||
|
||||
Expect(err).To(MatchError(context.Canceled))
|
||||
Expect(res.reader).To(BeNil())
|
||||
|
|
@ -470,7 +468,7 @@ var _ = Describe("Disc Artwork Reader", func() {
|
|||
Expect(os.MkdirAll(filepath.Dir(track), 0755)).To(Succeed())
|
||||
Expect(os.WriteFile(track, []byte("not audio"), 0600)).To(Succeed())
|
||||
|
||||
res, err := reader.selectImage(context.Background(), tests.NewMockFFmpeg(""), "embedded",
|
||||
res, err := reader.selectImage(ctx, tests.NewMockFFmpeg(""), "embedded",
|
||||
&chainState{trace: trace})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
|
@ -482,7 +480,7 @@ var _ = Describe("Disc Artwork Reader", func() {
|
|||
trace := &ChainTrace{}
|
||||
reader.firstTrackRel = ""
|
||||
|
||||
res, err := reader.selectImage(context.Background(), tests.NewMockFFmpeg(""), "embedded",
|
||||
res, err := reader.selectImage(ctx, tests.NewMockFFmpeg(""), "embedded",
|
||||
&chainState{trace: trace})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
|
@ -493,19 +491,19 @@ var _ = Describe("Disc Artwork Reader", func() {
|
|||
|
||||
Describe("discCandidates", func() {
|
||||
It("returns a resolvable candidate for glob patterns", func() {
|
||||
cc := reader.discCandidates(context.Background(), nil, "disc*.*")
|
||||
cc := reader.discCandidates(ctx, nil, "disc*.*")
|
||||
Expect(cc).To(HaveLen(1))
|
||||
Expect(cc[0].resolve).ToNot(BeNil())
|
||||
})
|
||||
|
||||
It("returns one candidate per entry, in order", func() {
|
||||
cc := reader.discCandidates(context.Background(), nil, "disc*.*, cd*.*, embedded")
|
||||
cc := reader.discCandidates(ctx, nil, "disc*.*, cd*.*, embedded")
|
||||
Expect(slice.Map(cc, func(c discCandidate) string { return c.pattern })).
|
||||
To(Equal([]string{"disc*.*", "cd*.*", "embedded"}))
|
||||
})
|
||||
|
||||
It("skips an empty entry rather than building a glob that matches nothing", func() {
|
||||
cc := reader.discCandidates(context.Background(), nil, "disc*.*,")
|
||||
cc := reader.discCandidates(ctx, nil, "disc*.*,")
|
||||
Expect(cc).To(HaveLen(1))
|
||||
})
|
||||
|
||||
|
|
@ -514,7 +512,7 @@ var _ = Describe("Disc Artwork Reader", func() {
|
|||
DescribeTable("keeps an entry that maps to no source, with its reason",
|
||||
func(setup func(), priority, reason string) {
|
||||
setup()
|
||||
cc := reader.discCandidates(context.Background(), nil, priority)
|
||||
cc := reader.discCandidates(ctx, nil, priority)
|
||||
Expect(cc).To(HaveLen(1))
|
||||
Expect(cc[0].resolve).To(BeNil())
|
||||
Expect(cc[0].skip).To(Equal(reason))
|
||||
|
|
@ -530,7 +528,7 @@ var _ = Describe("Disc Artwork Reader", func() {
|
|||
|
||||
It("returns source func for discsubtitle pattern", func() {
|
||||
reader.album = model.Album{Discs: model.Discs{2: "Bonus Tracks"}}
|
||||
cc := reader.discCandidates(context.Background(), nil, "discsubtitle")
|
||||
cc := reader.discCandidates(ctx, nil, "discsubtitle")
|
||||
Expect(cc).To(HaveLen(1))
|
||||
Expect(cc[0].resolve).ToNot(BeNil())
|
||||
})
|
||||
|
|
|
|||
|
|
@ -63,7 +63,7 @@ var _ = Describe("Acquisition → serve loop", func() {
|
|||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
repoRoot, err := os.Getwd()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
coverBytes = readFixture(coverFixture)
|
||||
|
|
@ -130,7 +130,7 @@ var _ = Describe("Acquisition → serve loop", func() {
|
|||
bump("al", "al1")
|
||||
runWorkerUntil(ctx, worker, itemFound(model.KindAlbumArtwork, "al1"))
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("al-al1"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("al-al1"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(img.Placeholder).To(BeFalse())
|
||||
Expect(readAll(img)).To(Equal(jxlFixture))
|
||||
|
|
@ -145,7 +145,7 @@ var _ = Describe("Acquisition → serve loop", func() {
|
|||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(ia.Source).To(Equal("folder"))
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("al-al1"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("al-al1"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(img.Hash).To(Equal(ia.Hash))
|
||||
Expect(img.Placeholder).To(BeFalse())
|
||||
|
|
@ -162,7 +162,7 @@ var _ = Describe("Acquisition → serve loop", func() {
|
|||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(ia.Source).To(Equal("upload"))
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("ar-ar1"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("ar-ar1"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(img.Hash).To(Equal(ia.Hash))
|
||||
Expect(readAll(img)).To(Equal(readFixture(artistPngFixture)))
|
||||
|
|
@ -179,13 +179,13 @@ var _ = Describe("Acquisition → serve loop", func() {
|
|||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(ia.Source).To(Equal("generated"))
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("pl-pl1"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("pl-pl1"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(img.Hash).To(Equal(ia.Hash))
|
||||
art, err := artRepo.GetImage(ctx, ia.Hash)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(art.Mime).To(Equal("image/png"))
|
||||
Expect(len(readAll(img))).To(BeNumerically(">", 0))
|
||||
Expect(readAll(img)).ToNot(BeEmpty())
|
||||
})
|
||||
|
||||
It("acquires a radio station's uploaded image and serves it", func() {
|
||||
|
|
@ -198,7 +198,7 @@ var _ = Describe("Acquisition → serve loop", func() {
|
|||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(ia.Source).To(Equal("upload"))
|
||||
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("ra-ra1"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("ra-ra1"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(img.Hash).To(Equal(ia.Hash))
|
||||
Expect(readAll(img)).To(Equal(coverBytes))
|
||||
|
|
@ -209,12 +209,12 @@ var _ = Describe("Acquisition → serve loop", func() {
|
|||
ID: "mf1", AlbumID: "al1", HasCoverArt: true, LibraryID: 0, Path: mp3Fixture,
|
||||
}})
|
||||
|
||||
provisional, err := svc.Get(ctx, model.MustParseArtworkID("mf-mf1"), 0, false)
|
||||
provisional, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf1"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(provisional.Placeholder).To(BeFalse())
|
||||
Expect(provisional.Hash).ToNot(BeEmpty())
|
||||
provisionalBytes := readAll(provisional)
|
||||
Expect(len(provisionalBytes)).To(BeNumerically(">", 0))
|
||||
Expect(provisionalBytes).ToNot(BeEmpty())
|
||||
|
||||
_, err = artRepo.GetItemArtwork(ctx, model.KindMediaFileArtwork, "mf1", model.ImageTypePrimary)
|
||||
Expect(err).To(MatchError(model.ErrNotFound), "provisional serving must not write a state row")
|
||||
|
|
@ -226,7 +226,7 @@ var _ = Describe("Acquisition → serve loop", func() {
|
|||
Expect(ia.Source).To(Equal("embedded"))
|
||||
Expect(ia.Hash).To(Equal(provisional.Hash))
|
||||
|
||||
resolved, err := svc.Get(ctx, model.MustParseArtworkID("mf-mf1"), 0, false)
|
||||
resolved, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf1"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(resolved.Hash).To(Equal(ia.Hash))
|
||||
Expect(readAll(resolved)).To(Equal(provisionalBytes))
|
||||
|
|
@ -284,7 +284,7 @@ var _ = Describe("Acquisition → serve loop", func() {
|
|||
ia2, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al2", model.ImageTypePrimary)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(ia1.Hash).To(Equal(ia2.Hash), "identical bytes must share one content hash")
|
||||
Expect(readAll(mustGet(svc.Get(ctx, model.MustParseArtworkID("al-al2"), 0, false)))).To(Equal(coverBytes))
|
||||
Expect(readAll(mustGet(svc.Get(ctx, tests.MustParseArtworkID("al-al2"), 0, false)))).To(Equal(coverBytes))
|
||||
})
|
||||
|
||||
It("stops serving a file-backed image once its source file changes underneath", func() {
|
||||
|
|
@ -303,7 +303,7 @@ var _ = Describe("Acquisition → serve loop", func() {
|
|||
Expect(os.Chtimes(path, newer, newer)).To(Succeed())
|
||||
|
||||
// The mtime no longer matches the state row, so the stale bytes are not served.
|
||||
_, err = svc.Get(ctx, model.MustParseArtworkID("ra-ra1"), 0, false)
|
||||
_, err = svc.Get(ctx, tests.MustParseArtworkID("ra-ra1"), 0, false)
|
||||
Expect(err).To(MatchError(artwork.ErrUnavailable))
|
||||
|
||||
// That failed read enqueued a re-resolution.
|
||||
|
|
@ -311,7 +311,7 @@ var _ = Describe("Acquisition → serve loop", func() {
|
|||
cur, gerr := artRepo.GetItemArtwork(ctx, model.KindRadioArtwork, "ra1", model.ImageTypePrimary)
|
||||
return gerr == nil && cur.Hash != "" && cur.Hash != staleHash
|
||||
})
|
||||
img, err := svc.Get(ctx, model.MustParseArtworkID("ra-ra1"), 0, false)
|
||||
img, err := svc.Get(ctx, tests.MustParseArtworkID("ra-ra1"), 0, false)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(readAll(img)).To(Equal(readFixture(artistPngFixture)))
|
||||
})
|
||||
|
|
@ -321,7 +321,7 @@ var _ = Describe("Acquisition → serve loop", func() {
|
|||
bump("al", "alx")
|
||||
runWorkerUntil(ctx, worker, itemAbsent(model.KindAlbumArtwork, "alx"))
|
||||
|
||||
_, err := svc.Get(ctx, model.MustParseArtworkID("al-alx"), 0, false)
|
||||
_, err := svc.Get(ctx, tests.MustParseArtworkID("al-alx"), 0, false)
|
||||
Expect(err).To(MatchError(artwork.ErrUnavailable))
|
||||
|
||||
img, err := svc.GetOrPlaceholder(ctx, "al-alx", 0, false)
|
||||
|
|
|
|||
|
|
@ -71,13 +71,13 @@ var _ = BeforeSuite(func() {
|
|||
c.DataFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
})
|
||||
db.Db().SetMaxOpenConns(1)
|
||||
db.Init(request.WithUser(context.Background(), model.User{ID: "admin-1", IsAdmin: true}))
|
||||
db.Init(request.WithUser(GinkgoT().Context(), model.User{ID: "admin-1", IsAdmin: true}))
|
||||
|
||||
userTables = harness.ResettableTables()
|
||||
})
|
||||
|
||||
var _ = AfterSuite(func() {
|
||||
db.Close(context.Background())
|
||||
db.Close(GinkgoT().Context())
|
||||
})
|
||||
|
||||
func setupResolutionHarness() {
|
||||
|
|
@ -324,19 +324,14 @@ func loadEmbeddedFixture() {
|
|||
}
|
||||
|
||||
func extractEmbeddedArt(mp3 []byte) []byte {
|
||||
GinkgoHelper()
|
||||
tf, err := taglib.OpenStream(bytes.NewReader(mp3))
|
||||
if err != nil {
|
||||
panic("embedded-art fixture: taglib.OpenStream failed: " + err.Error())
|
||||
}
|
||||
Expect(err).ToNot(HaveOccurred(), "embedded-art fixture: taglib.OpenStream failed")
|
||||
defer tf.Close()
|
||||
images := tf.Properties().Images
|
||||
if len(images) == 0 {
|
||||
panic("embedded-art fixture has no embedded images")
|
||||
}
|
||||
Expect(tf.Properties().Images).ToNot(BeEmpty(), "embedded-art fixture has no embedded images")
|
||||
data, err := tf.Image(0)
|
||||
if err != nil || len(data) == 0 {
|
||||
panic("embedded-art fixture: could not read image 0")
|
||||
}
|
||||
Expect(err).ToNot(HaveOccurred(), "embedded-art fixture: could not read image 0")
|
||||
Expect(data).ToNot(BeEmpty(), "embedded-art fixture: image 0 is empty")
|
||||
return data
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ var _ = Describe("loadAlbumFoldersPaths", func() {
|
|||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
now = time.Now().Truncate(time.Second)
|
||||
repo = &fakeFolderRepo{}
|
||||
ds = &tests.MockDataStore{MockedFolder: repo}
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ var _ = Describe("loadArtistFolder", func() {
|
|||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
updatedAt = time.Now().Truncate(time.Second).Add(5 * time.Minute)
|
||||
repo = &fakeFolderRepo{result: []model.Folder{{ImagesUpdatedAt: updatedAt}}}
|
||||
libRepo := &tests.MockLibraryRepo{}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ var _ = Describe("findImageInFolder", func() {
|
|||
var files fstest.MapFS
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
files = fstest.MapFS{"artist.jpg": &fstest.MapFile{Data: []byte("img")}}
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ var _ = Describe("Housekeeping", func() {
|
|||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.CoverArtPriority = "embedded, folder"
|
||||
c.ArtistArtPriority = "artist.jpg"
|
||||
|
|
@ -150,7 +150,7 @@ var _ = Describe("ItemName", func() {
|
|||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
albumRepo := tests.CreateMockAlbumRepo()
|
||||
albumRepo.SetData(model.Albums{
|
||||
{ID: "al-1", Name: "Kid A"},
|
||||
|
|
|
|||
|
|
@ -11,6 +11,12 @@ import (
|
|||
)
|
||||
|
||||
var _ = Describe("resizedItem", func() {
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
})
|
||||
|
||||
Describe("Reader", func() {
|
||||
newItem := func(open func() (io.ReadCloser, error)) *resizedItem {
|
||||
return &resizedItem{hash: "abc123", size: 300, open: open}
|
||||
|
|
@ -19,20 +25,20 @@ var _ = Describe("resizedItem", func() {
|
|||
It("reports a nil reader as unavailable instead of panicking on it", func() {
|
||||
// Every caller is expected to report "no image" as an error, but a nil reader reaches
|
||||
// the deferred Close as a nil interface, which takes the whole request down.
|
||||
_, err := newItem(func() (io.ReadCloser, error) { return nil, nil }).Reader(context.Background())
|
||||
_, err := newItem(func() (io.ReadCloser, error) { return nil, nil }).Reader(ctx)
|
||||
Expect(err).To(MatchError(ErrUnavailable))
|
||||
})
|
||||
|
||||
It("propagates the open error", func() {
|
||||
boom := errors.New("boom")
|
||||
_, err := newItem(func() (io.ReadCloser, error) { return nil, boom }).Reader(context.Background())
|
||||
_, err := newItem(func() (io.ReadCloser, error) { return nil, boom }).Reader(ctx)
|
||||
Expect(err).To(MatchError(boom))
|
||||
})
|
||||
|
||||
It("serves the original bytes when they cannot be resized", func() {
|
||||
rc, err := newItem(func() (io.ReadCloser, error) {
|
||||
return io.NopCloser(strings.NewReader("not an image")), nil
|
||||
}).Reader(context.Background())
|
||||
}).Reader(ctx)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
defer rc.Close()
|
||||
Expect(io.ReadAll(rc)).To(Equal([]byte("not an image")))
|
||||
|
|
|
|||
|
|
@ -19,9 +19,9 @@ var _ = Describe("ImageStore", func() {
|
|||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
root = GinkgoT().TempDir()
|
||||
store = NewImageStore(root)
|
||||
ctx = context.Background()
|
||||
})
|
||||
|
||||
It("hashes deterministically", func() {
|
||||
|
|
|
|||
|
|
@ -45,6 +45,8 @@ func (o outcome) String() string {
|
|||
return "foundStale"
|
||||
case outcomeAbsent:
|
||||
return "absent"
|
||||
case outcomeFailed:
|
||||
fallthrough
|
||||
default:
|
||||
return "failed"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ var _ = Describe("processor.acquire", func() {
|
|||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
var err error
|
||||
repoRoot, err = os.Getwd()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ var _ = Describe("Prune", func() {
|
|||
"ar": {"live-artist": true},
|
||||
}
|
||||
|
||||
Expect(prune(context.Background(), ds, store)).To(Succeed())
|
||||
Expect(prune(ctx, ds, store)).To(Succeed())
|
||||
|
||||
_, err := awRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "gone-album", model.ImageTypePrimary)
|
||||
Expect(err).To(MatchError(model.ErrNotFound))
|
||||
|
|
@ -70,7 +70,7 @@ var _ = Describe("Prune", func() {
|
|||
queueRepo.ExistingIDs = map[string]map[string]bool{"al": {"live-album": true}}
|
||||
ds.MockedArtworkQueue = queueRepo
|
||||
|
||||
Expect(prune(context.Background(), ds, store)).To(Succeed())
|
||||
Expect(prune(ctx, ds, store)).To(Succeed())
|
||||
|
||||
Expect(findQueued(queueRepo, "al", "gone-album")).To(BeNil())
|
||||
Expect(findQueued(queueRepo, "al", "live-album")).ToNot(BeNil())
|
||||
|
|
@ -90,7 +90,7 @@ var _ = Describe("Prune", func() {
|
|||
Expect(store.Write(hk, "image/jpeg", bytes.NewReader(kept))).To(Succeed())
|
||||
Expect(awRepo.PutImage(ctx, &model.Artwork{Hash: hk, Mime: "image/jpeg"})).To(Succeed())
|
||||
|
||||
Expect(prune(context.Background(), ds, store)).To(Succeed())
|
||||
Expect(prune(ctx, ds, store)).To(Succeed())
|
||||
|
||||
_, err := awRepo.GetImage(ctx, h)
|
||||
Expect(err).To(MatchError(model.ErrNotFound))
|
||||
|
|
@ -110,7 +110,7 @@ var _ = Describe("Prune", func() {
|
|||
Expect(awRepo.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "al", ItemID: "a1",
|
||||
ImageType: model.ImageTypePrimary, Hash: h, Source: "folder"})).To(Succeed())
|
||||
|
||||
Expect(prune(context.Background(), ds, store)).To(Succeed())
|
||||
Expect(prune(ctx, ds, store)).To(Succeed())
|
||||
|
||||
_, err := awRepo.GetImage(ctx, h)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
|
@ -126,7 +126,7 @@ var _ = Describe("Prune", func() {
|
|||
// Reacquisition refreshed created_at, so the row is unreferenced but too young to drop.
|
||||
Expect(awRepo.PutImage(ctx, &model.Artwork{Hash: h, Mime: "image/jpeg"})).To(Succeed())
|
||||
|
||||
Expect(prune(context.Background(), ds, store)).To(Succeed())
|
||||
Expect(prune(ctx, ds, store)).To(Succeed())
|
||||
|
||||
_, err := awRepo.GetImage(ctx, h)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
|
@ -143,7 +143,7 @@ var _ = Describe("Prune", func() {
|
|||
ageArtwork(h, time.Now().Add(-2*time.Hour))
|
||||
// The row is orphaned, but a concurrent acquisition just touched the file's mtime.
|
||||
|
||||
Expect(prune(context.Background(), ds, store)).To(Succeed())
|
||||
Expect(prune(ctx, ds, store)).To(Succeed())
|
||||
|
||||
rc, err := store.Open(h, "image/jpeg")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
|
@ -157,7 +157,7 @@ var _ = Describe("Prune", func() {
|
|||
old := time.Now().Add(-2 * time.Hour)
|
||||
Expect(os.Chtimes(store.path(h, "image/jpeg"), old, old)).To(Succeed())
|
||||
|
||||
Expect(prune(context.Background(), ds, store)).To(Succeed())
|
||||
Expect(prune(ctx, ds, store)).To(Succeed())
|
||||
|
||||
_, err := store.Open(h, "image/jpeg")
|
||||
Expect(os.IsNotExist(err)).To(BeTrue())
|
||||
|
|
@ -174,7 +174,7 @@ var _ = Describe("Prune", func() {
|
|||
// The row records the current mime; the .png file is a superseded variant.
|
||||
Expect(awRepo.PutImage(ctx, &model.Artwork{Hash: h, Mime: "image/jpeg"})).To(Succeed())
|
||||
|
||||
Expect(prune(context.Background(), ds, store)).To(Succeed())
|
||||
Expect(prune(ctx, ds, store)).To(Succeed())
|
||||
|
||||
_, err := store.Open(h, "image/png")
|
||||
Expect(os.IsNotExist(err)).To(BeTrue())
|
||||
|
|
@ -210,7 +210,7 @@ var _ = Describe("Prune", func() {
|
|||
Expect(os.Chmod(shardDir, 0500)).To(Succeed())
|
||||
DeferCleanup(func() { _ = os.Chmod(shardDir, 0755) })
|
||||
|
||||
Expect(prune(context.Background(), ds, store)).To(Succeed())
|
||||
Expect(prune(ctx, ds, store)).To(Succeed())
|
||||
|
||||
_, err := awRepo.GetImage(ctx, hg)
|
||||
Expect(err).To(MatchError(model.ErrNotFound))
|
||||
|
|
@ -232,7 +232,7 @@ var _ = Describe("Prune", func() {
|
|||
h, _ := hashImage(bytes.NewReader(data))
|
||||
Expect(store.Write(h, "image/jpeg", bytes.NewReader(data))).To(Succeed())
|
||||
|
||||
Expect(prune(context.Background(), ds, store)).ToNot(Succeed())
|
||||
Expect(prune(ctx, ds, store)).ToNot(Succeed())
|
||||
|
||||
rc, err := store.Open(h, "image/jpeg")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ var _ = Describe("resolveItem", func() {
|
|||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
var err error
|
||||
repoRoot, err = os.Getwd()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import (
|
|||
"slices"
|
||||
"sync"
|
||||
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/utils/str"
|
||||
)
|
||||
|
||||
|
|
@ -94,7 +95,10 @@ func encodeSteps(steps []TraceStep, sourcePath string) string {
|
|||
}
|
||||
out = append(out, storedStep{C: s.Candidate, O: s.Outcome, D: str.TruncateRunes(d, maxTraceDetail, "...")})
|
||||
}
|
||||
b, _ := json.Marshal(out) // []storedStep is all strings, so this cannot fail
|
||||
b, err := json.Marshal(out)
|
||||
if err != nil {
|
||||
log.Error("Artwork: Could not encode resolution trace", err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -81,13 +81,19 @@ var _ = Describe("encodeSteps/DecodeTrace", func() {
|
|||
})
|
||||
|
||||
var _ = Describe("chainTrace", func() {
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
})
|
||||
|
||||
It("returns nil when no trace is attached", func() {
|
||||
Expect(traceFrom(context.Background())).To(BeNil())
|
||||
Expect(traceFrom(ctx)).To(BeNil())
|
||||
})
|
||||
|
||||
It("collects steps in order", func() {
|
||||
t := &ChainTrace{}
|
||||
ctx := withTrace(context.Background(), t)
|
||||
ctx = withTrace(ctx, t)
|
||||
|
||||
traceFrom(ctx).add(TraceStep{Candidate: "cover.*", Outcome: OutcomeMiss})
|
||||
traceFrom(ctx).add(TraceStep{Candidate: "embedded", Outcome: OutcomeHit, Detail: "/music/a.flac"})
|
||||
|
|
@ -170,7 +176,7 @@ var _ = Describe("external agent tracing", func() {
|
|||
)
|
||||
BeforeEach(func() {
|
||||
t = &ChainTrace{}
|
||||
ctx = withTrace(context.Background(), t)
|
||||
ctx = withTrace(GinkgoT().Context(), t)
|
||||
body = io.NopCloser(strings.NewReader("x"))
|
||||
})
|
||||
|
||||
|
|
@ -226,7 +232,7 @@ var _ = Describe("resolveAlbum tracing", func() {
|
|||
ffm = tests.NewMockFFmpeg("")
|
||||
ag = agents.GetAgents(&tests.MockDataStore{}, nil)
|
||||
t = &ChainTrace{}
|
||||
ctx = withTrace(context.Background(), t)
|
||||
ctx = withTrace(GinkgoT().Context(), t)
|
||||
})
|
||||
|
||||
It("records a pattern skipped because the album folder holds no images", func() {
|
||||
|
|
@ -317,7 +323,7 @@ var _ = Describe("resolveArtist tracing", func() {
|
|||
ffm = tests.NewMockFFmpeg("")
|
||||
ag = agents.GetAgents(&tests.MockDataStore{}, nil)
|
||||
t = &ChainTrace{}
|
||||
ctx = withTrace(context.Background(), t)
|
||||
ctx = withTrace(GinkgoT().Context(), t)
|
||||
})
|
||||
|
||||
It("records the upload short-circuit as a hit", func() {
|
||||
|
|
@ -402,6 +408,7 @@ var _ = Describe("resolveArtist tracing", func() {
|
|||
|
||||
var _ = Describe("NewTracingResolver", func() {
|
||||
var (
|
||||
ctx context.Context
|
||||
ds *tests.MockDataStore
|
||||
albumRepo *tests.MockAlbumRepo
|
||||
artistRepo *tests.MockArtistRepo
|
||||
|
|
@ -412,6 +419,7 @@ var _ = Describe("NewTracingResolver", func() {
|
|||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
conf.Update(func(c *conf.Options) {
|
||||
c.DataFolder = conf.NewDir(GinkgoT().TempDir())
|
||||
c.CoverArtPriority = "external, embedded"
|
||||
|
|
@ -450,7 +458,7 @@ var _ = Describe("NewTracingResolver", func() {
|
|||
})
|
||||
|
||||
It("asks the agents and records what each answered", func() {
|
||||
source, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(context.Background(), model.KindAlbumArtwork, "al1")
|
||||
source, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(ctx, model.KindAlbumArtwork, "al1")
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(source).To(Equal("embedded"))
|
||||
|
|
@ -459,7 +467,7 @@ var _ = Describe("NewTracingResolver", func() {
|
|||
})
|
||||
|
||||
It("records the local chain steps too", func() {
|
||||
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(context.Background(), model.KindAlbumArtwork, "al1")
|
||||
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(ctx, model.KindAlbumArtwork, "al1")
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
last := t.Steps()[len(t.Steps())-1]
|
||||
|
|
@ -468,7 +476,7 @@ var _ = Describe("NewTracingResolver", func() {
|
|||
})
|
||||
|
||||
It("never persists artwork state", func() {
|
||||
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(context.Background(), model.KindAlbumArtwork, "al1")
|
||||
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(ctx, model.KindAlbumArtwork, "al1")
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(artworkRepo.ItemData).To(BeEmpty(),
|
||||
|
|
@ -477,7 +485,7 @@ var _ = Describe("NewTracingResolver", func() {
|
|||
})
|
||||
|
||||
It("resolves an artist without persisting anything", func() {
|
||||
source, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(context.Background(), model.KindArtistArtwork, "ar1")
|
||||
source, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(ctx, model.KindArtistArtwork, "ar1")
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(source).To(BeEmpty())
|
||||
|
|
@ -493,7 +501,7 @@ var _ = Describe("NewTracingResolver", func() {
|
|||
ID: "al2", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/no-such-file.mp3", FolderIDs: []string{"f1"},
|
||||
}})
|
||||
|
||||
source, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(context.Background(), model.KindAlbumArtwork, "al2")
|
||||
source, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(ctx, model.KindAlbumArtwork, "al2")
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(source).To(Equal("embedded"))
|
||||
|
|
@ -514,9 +522,9 @@ var _ = Describe("NewTracingResolver", func() {
|
|||
ds.MockedMediaFile = mfRepo
|
||||
offline := NewTracingResolver(ds, imageAgents(fake), ffm, t, false)
|
||||
|
||||
_, err := offline.Resolve(context.Background(), model.KindDiscArtwork, "al1:1")
|
||||
_, err := offline.Resolve(ctx, model.KindDiscArtwork, "al1:1")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = offline.Resolve(context.Background(), model.KindMediaFileArtwork, "mf1")
|
||||
_, err = offline.Resolve(ctx, model.KindMediaFileArtwork, "mf1")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
Expect(fake.albumCalls).To(BeZero())
|
||||
|
|
@ -524,7 +532,7 @@ var _ = Describe("NewTracingResolver", func() {
|
|||
})
|
||||
|
||||
It("propagates a lookup error", func() {
|
||||
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(context.Background(), model.KindAlbumArtwork, "nope")
|
||||
_, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(ctx, model.KindAlbumArtwork, "nope")
|
||||
Expect(err).To(MatchError(model.ErrNotFound))
|
||||
})
|
||||
})
|
||||
|
|
@ -558,7 +566,7 @@ var _ = Describe("resolveDisc tracing", func() {
|
|||
}
|
||||
ffm = tests.NewMockFFmpeg("")
|
||||
t = &ChainTrace{}
|
||||
ctx = withTrace(context.Background(), t)
|
||||
ctx = withTrace(GinkgoT().Context(), t)
|
||||
})
|
||||
|
||||
It("accounts for every configured entry, including the ones that map to no source", func() {
|
||||
|
|
@ -626,7 +634,7 @@ var _ = Describe("resolveMediaFile tracing", func() {
|
|||
ds = &tests.MockDataStore{MockedMediaFile: mfRepo, MockedLibrary: libRepo}
|
||||
ffm = tests.NewMockFFmpeg("")
|
||||
t = &ChainTrace{}
|
||||
ctx = withTrace(context.Background(), t)
|
||||
ctx = withTrace(GinkgoT().Context(), t)
|
||||
})
|
||||
|
||||
It("separates a disabled setting from a track with nothing embedded", func() {
|
||||
|
|
|
|||
|
|
@ -109,7 +109,7 @@ var _ = Describe("Uploader", func() {
|
|||
})
|
||||
|
||||
It("is a no-op for an unknown entity type", func() {
|
||||
svc.EnqueueArtwork(context.Background(), "unknown", "x-1")
|
||||
svc.EnqueueArtwork(ctx, "unknown", "x-1")
|
||||
Expect(queueRepo.DequeueBatch(ctx, 1000)).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -99,7 +99,7 @@ var _ = Describe("Worker soak", func() {
|
|||
start := time.Now()
|
||||
for i := range soakCycles {
|
||||
it := items[i%len(items)]
|
||||
out, _, _ := proc.acquire(context.Background(), it)
|
||||
out, _, _ := proc.acquire(ctx, it)
|
||||
|
||||
// Read-back exercises the surfaces a caller would use after acquisition.
|
||||
if out == outcomeFound {
|
||||
|
|
|
|||
|
|
@ -148,7 +148,7 @@ type panickingAlbumRepo struct {
|
|||
|
||||
func (r *panickingAlbumRepo) Get(ctx context.Context, id string) (*model.Album, error) {
|
||||
if id == r.panicID {
|
||||
panic("boom")
|
||||
panic("boom") //nolint:forbidigo
|
||||
}
|
||||
return r.MockAlbumRepo.Get(ctx, id)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -87,7 +87,7 @@ var _ = Describe("Auth", func() {
|
|||
Expect(claims.Issuer).To(Equal(consts.JWTIssuer))
|
||||
Expect(claims.Subject).To(Equal("johndoe"))
|
||||
Expect(claims.UserID).To(Equal("123"))
|
||||
Expect(claims.IsAdmin).To(Equal(true))
|
||||
Expect(claims.IsAdmin).To(BeTrue())
|
||||
Expect(claims.ExpiresAt).To(BeTemporally(">", time.Now()))
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -13,14 +13,18 @@ import (
|
|||
)
|
||||
|
||||
var _ = Describe("common.go", func() {
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
})
|
||||
|
||||
Describe("userName", func() {
|
||||
It("returns the username from context", func() {
|
||||
ctx := request.WithUser(context.Background(), model.User{UserName: "testuser"})
|
||||
Expect(userName(ctx)).To(Equal("testuser"))
|
||||
Expect(userName(request.WithUser(ctx, model.User{UserName: "testuser"}))).To(Equal("testuser"))
|
||||
})
|
||||
|
||||
It("returns 'UNKNOWN' if no user in context", func() {
|
||||
ctx := context.Background()
|
||||
Expect(userName(ctx)).To(Equal("UNKNOWN"))
|
||||
})
|
||||
})
|
||||
|
|
@ -42,13 +46,11 @@ var _ = Describe("common.go", func() {
|
|||
})
|
||||
|
||||
It("returns the absolute path when library exists", func() {
|
||||
ctx := context.Background()
|
||||
abs := AbsolutePath(ctx, ds, libId, path)
|
||||
Expect(abs).To(Equal(filepath.FromSlash("/library/root/music/file.mp3")))
|
||||
})
|
||||
|
||||
It("returns the original path if library not found", func() {
|
||||
ctx := context.Background()
|
||||
abs := AbsolutePath(ctx, ds, 999, path)
|
||||
Expect(abs).To(Equal(path))
|
||||
})
|
||||
|
|
|
|||
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/server/events"
|
||||
"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/str"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
|
@ -125,7 +125,7 @@ func (e *provider) UpdateAlbumInfo(ctx context.Context, id string) (*model.Album
|
|||
return nil, err
|
||||
}
|
||||
|
||||
updatedAt := V(album.ExternalInfoUpdatedAt)
|
||||
updatedAt := gg.V(album.ExternalInfoUpdatedAt)
|
||||
albumName := album.Name()
|
||||
if updatedAt.IsZero() {
|
||||
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
|
||||
updatedAt := V(artist.ExternalInfoUpdatedAt)
|
||||
updatedAt := gg.V(artist.ExternalInfoUpdatedAt)
|
||||
artistName := artist.Name()
|
||||
if updatedAt.IsZero() {
|
||||
log.Debug(ctx, "ArtistInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", artistName)
|
||||
|
|
|
|||
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{
|
||||
ID: "song-1", Title: "Song One", ArtistID: "artist-1",
|
||||
Participants: model.Participants{model.RoleArtist: model.ParticipantList{
|
||||
{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"}},
|
||||
{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"},
|
||||
}},
|
||||
}
|
||||
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{track}, nil)
|
||||
|
|
@ -173,7 +173,7 @@ var _ = Describe("Provider - TopSongs", func() {
|
|||
track := model.MediaFile{
|
||||
ID: "one-track", Title: "Collab Song", ArtistID: "artist-1",
|
||||
Participants: model.Participants{model.RoleArtist: model.ParticipantList{
|
||||
{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"}},
|
||||
{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"},
|
||||
}},
|
||||
}
|
||||
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{track}, nil)
|
||||
|
|
@ -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()
|
||||
|
||||
// Title track-fetch: tracks must carry RoleArtist participants so back-mapping routes them.
|
||||
participant1 := model.Participant{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}}
|
||||
participant1 := model.Participant{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}
|
||||
song1 := model.MediaFile{
|
||||
ID: "song-1", Title: "Song One", Artist: "Artist One", ArtistID: "artist-1",
|
||||
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()
|
||||
|
||||
// Title track-fetch: song2 must carry RoleArtist participants for back-mapping.
|
||||
participant1 := model.Participant{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}}
|
||||
participant1 := model.Participant{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}
|
||||
song2 := model.MediaFile{
|
||||
ID: "song-2", Title: "Song Two", Artist: "Artist One", ArtistID: "artist-1",
|
||||
Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}},
|
||||
|
|
|
|||
|
|
@ -643,6 +643,7 @@ func (p *encoderProbe) has(cmdPath, encoder string) bool {
|
|||
return true
|
||||
case encoderProbeUnavailable:
|
||||
return false
|
||||
case encoderProbeUnknown:
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ func TestFFmpeg(t *testing.T) {
|
|||
_, file, _, _ := runtime.Caller(0)
|
||||
appPath, _ := filepath.Abs(filepath.Join(filepath.Dir(file), "..", ".."))
|
||||
confPath := filepath.Join(appPath, "tests", "navidrome-test.toml")
|
||||
_ = os.Chdir(appPath)
|
||||
t.Chdir(appPath)
|
||||
conf.LoadFromFile(confPath)
|
||||
log.SetLevel(log.LevelFatal)
|
||||
RegisterFailHandler(Fail)
|
||||
|
|
|
|||
|
|
@ -157,7 +157,7 @@ func (r *libraryRepositoryWrapper) Save(ctx context.Context, lib *model.Library)
|
|||
return "", err
|
||||
}
|
||||
|
||||
err := r.LibraryRepository.Put(ctx, lib)
|
||||
err := r.Put(ctx, lib)
|
||||
if err != nil {
|
||||
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) ||
|
||||
(updatesColumn(cols, "pidTrack") && originalLib.PIDTrack != lib.PIDTrack)
|
||||
|
||||
err = r.LibraryRepository.Put(ctx, lib, cols...)
|
||||
err = r.Put(ctx, lib, cols...)
|
||||
if err != nil {
|
||||
return r.mapError(err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import (
|
|||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/deluan/rest"
|
||||
_ "github.com/navidrome/navidrome/adapters/gotaglib" // Register taglib extractor
|
||||
|
|
@ -34,7 +35,7 @@ var _ = Describe("Library Service", func() {
|
|||
var pluginManager *mockPluginUnloader
|
||||
|
||||
BeforeEach(func() {
|
||||
|
||||
ctx = GinkgoT().Context()
|
||||
ds = &tests.MockDataStore{}
|
||||
libraryRepo = &tests.MockLibraryRepo{}
|
||||
userRepo = tests.CreateMockUserRepo()
|
||||
|
|
@ -52,7 +53,6 @@ var _ = Describe("Library Service", func() {
|
|||
// Create a mock plugin unloader
|
||||
pluginManager = &mockPluginUnloader{}
|
||||
service = core.NewLibrary(ds, scanner, watcherManager, broker, pluginManager)
|
||||
ctx = context.Background()
|
||||
|
||||
// Create a temporary directory for testing valid paths
|
||||
var err error
|
||||
|
|
@ -499,7 +499,7 @@ var _ = Describe("Library Service", func() {
|
|||
err := repo.Delete(ctx, "1")
|
||||
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(libraryRepo.Data).To(HaveLen(0))
|
||||
Expect(libraryRepo.Data).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("fails when library doesn't exist", func() {
|
||||
|
|
@ -658,7 +658,7 @@ var _ = Describe("Library Service", func() {
|
|||
// Wait briefly for the goroutine to complete
|
||||
Eventually(func() int {
|
||||
return scanner.GetScanAllCallCount()
|
||||
}, "1s", "10ms").Should(Equal(1))
|
||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
||||
|
||||
// Verify scan was called with correct parameters
|
||||
calls := scanner.GetScanAllCalls()
|
||||
|
|
@ -684,7 +684,7 @@ var _ = Describe("Library Service", func() {
|
|||
// Wait briefly for the goroutine to complete
|
||||
Eventually(func() int {
|
||||
return scanner.GetScanAllCallCount()
|
||||
}, "1s", "10ms").Should(Equal(1))
|
||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
||||
|
||||
// Verify scan was called with correct parameters
|
||||
calls := scanner.GetScanAllCalls()
|
||||
|
|
@ -705,7 +705,7 @@ var _ = Describe("Library Service", func() {
|
|||
// Wait a bit to ensure no scan was triggered
|
||||
Consistently(func() int {
|
||||
return scanner.GetScanAllCallCount()
|
||||
}, "100ms", "10ms").Should(Equal(0))
|
||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
||||
})
|
||||
|
||||
It("triggers scan when updating the library PID config", func() {
|
||||
|
|
@ -716,7 +716,7 @@ var _ = Describe("Library Service", func() {
|
|||
|
||||
Eventually(func() int {
|
||||
return scanner.GetScanAllCallCount()
|
||||
}, "1s", "10ms").Should(Equal(1))
|
||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
||||
// A quick scan: the scanner itself rescans this library in full
|
||||
Expect(scanner.GetScanAllCalls()[0].FullScan).To(BeFalse())
|
||||
})
|
||||
|
|
@ -730,7 +730,7 @@ var _ = Describe("Library Service", func() {
|
|||
|
||||
Consistently(func() int {
|
||||
return scanner.GetScanAllCallCount()
|
||||
}, "100ms", "10ms").Should(Equal(0))
|
||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
||||
})
|
||||
|
||||
It("waits for a running scan before triggering a new one", func() {
|
||||
|
|
@ -742,12 +742,12 @@ var _ = Describe("Library Service", func() {
|
|||
|
||||
Consistently(func() int {
|
||||
return scanner.GetScanAllCallCount()
|
||||
}, "200ms", "20ms").Should(Equal(0))
|
||||
}, 200*time.Millisecond, 20*time.Millisecond).Should(Equal(0))
|
||||
|
||||
scanner.SetScanning(false)
|
||||
Eventually(func() int {
|
||||
return scanner.GetScanAllCallCount()
|
||||
}, "3s", "20ms").Should(Equal(1))
|
||||
}, 3*time.Second, 20*time.Millisecond).Should(Equal(1))
|
||||
})
|
||||
|
||||
It("does not trigger scan when library creation fails", func() {
|
||||
|
|
@ -760,7 +760,7 @@ var _ = Describe("Library Service", func() {
|
|||
// Ensure no scan was triggered since creation failed
|
||||
Consistently(func() int {
|
||||
return scanner.GetScanAllCallCount()
|
||||
}, "100ms", "10ms").Should(Equal(0))
|
||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
||||
})
|
||||
|
||||
It("does not trigger scan when library update fails", func() {
|
||||
|
|
@ -777,7 +777,7 @@ var _ = Describe("Library Service", func() {
|
|||
// Ensure no scan was triggered since update failed
|
||||
Consistently(func() int {
|
||||
return scanner.GetScanAllCallCount()
|
||||
}, "100ms", "10ms").Should(Equal(0))
|
||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
||||
})
|
||||
|
||||
It("triggers scan when deleting a library", func() {
|
||||
|
|
@ -793,7 +793,7 @@ var _ = Describe("Library Service", func() {
|
|||
// Wait briefly for the goroutine to complete
|
||||
Eventually(func() int {
|
||||
return scanner.GetScanAllCallCount()
|
||||
}, "1s", "10ms").Should(Equal(1))
|
||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
||||
|
||||
// Verify scan was called with correct parameters
|
||||
calls := scanner.GetScanAllCalls()
|
||||
|
|
@ -808,7 +808,7 @@ var _ = Describe("Library Service", func() {
|
|||
// Ensure no scan was triggered since deletion failed
|
||||
Consistently(func() int {
|
||||
return scanner.GetScanAllCallCount()
|
||||
}, "100ms", "10ms").Should(Equal(0))
|
||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
||||
})
|
||||
|
||||
Context("Watcher Integration", func() {
|
||||
|
|
@ -821,7 +821,7 @@ var _ = Describe("Library Service", func() {
|
|||
// Verify watcher was started
|
||||
Eventually(func() int {
|
||||
return watcherManager.lenStarted()
|
||||
}, "1s", "10ms").Should(Equal(1))
|
||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
||||
|
||||
Expect(watcherManager.StartedWatchers[0].ID).To(Equal(1))
|
||||
Expect(watcherManager.StartedWatchers[0].Name).To(Equal("New Library"))
|
||||
|
|
@ -850,7 +850,7 @@ var _ = Describe("Library Service", func() {
|
|||
// Verify watcher was restarted
|
||||
Eventually(func() int {
|
||||
return watcherManager.lenRestarted()
|
||||
}, "1s", "10ms").Should(Equal(1))
|
||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
||||
|
||||
Expect(watcherManager.RestartedWatchers[0].ID).To(Equal(1))
|
||||
Expect(watcherManager.RestartedWatchers[0].Path).To(Equal(newTempDir))
|
||||
|
|
@ -870,7 +870,7 @@ var _ = Describe("Library Service", func() {
|
|||
// Verify watcher was NOT restarted (since path didn't change)
|
||||
Consistently(func() int {
|
||||
return watcherManager.lenRestarted()
|
||||
}, "100ms", "10ms").Should(Equal(0))
|
||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
||||
})
|
||||
|
||||
It("stops watcher when library is deleted", func() {
|
||||
|
|
@ -885,7 +885,7 @@ var _ = Describe("Library Service", func() {
|
|||
// Verify watcher was stopped
|
||||
Eventually(func() int {
|
||||
return watcherManager.lenStopped()
|
||||
}, "1s", "10ms").Should(Equal(1))
|
||||
}, time.Second, 10*time.Millisecond).Should(Equal(1))
|
||||
|
||||
Expect(watcherManager.StoppedWatchers[0]).To(Equal(1))
|
||||
})
|
||||
|
|
@ -903,7 +903,7 @@ var _ = Describe("Library Service", func() {
|
|||
// Verify watcher was NOT stopped since deletion failed
|
||||
Consistently(func() int {
|
||||
return watcherManager.lenStopped()
|
||||
}, "100ms", "10ms").Should(Equal(0))
|
||||
}, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -3,12 +3,14 @@ package lyrics
|
|||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
. "github.com/Masterminds/squirrel"
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"github.com/navidrome/navidrome/persistence"
|
||||
"github.com/navidrome/navidrome/utils/cache"
|
||||
)
|
||||
|
||||
// maxLegacyLyricsCandidates bounds the duplicate window scanned by the legacy
|
||||
|
|
@ -16,6 +18,12 @@ import (
|
|||
// matches without turning it into an unbounded table scan.
|
||||
const maxLegacyLyricsCandidates = 10
|
||||
|
||||
const (
|
||||
lyricsCacheSize = 1000
|
||||
lyricsCacheTTL = 5 * time.Minute
|
||||
lyricsLoadTimeout = time.Minute
|
||||
)
|
||||
|
||||
// Provider fetches lyrics for a single media file. It is the contract
|
||||
// implemented by individual lyrics sources, such as plugins.
|
||||
type Provider interface {
|
||||
|
|
@ -37,12 +45,25 @@ type PluginLoader interface {
|
|||
type lyricsService struct {
|
||||
ds model.DataStore
|
||||
pluginLoader PluginLoader
|
||||
pluginCache cache.SimpleCache[pluginKey, model.LyricList]
|
||||
}
|
||||
|
||||
type pluginKey struct {
|
||||
plugin string
|
||||
mediaFileID string
|
||||
}
|
||||
|
||||
// NewLyrics creates a new lyrics service. pluginLoader may be nil if no plugin
|
||||
// system is available.
|
||||
func NewLyrics(ds model.DataStore, pluginLoader PluginLoader) Lyrics {
|
||||
return &lyricsService{ds: ds, pluginLoader: pluginLoader}
|
||||
return &lyricsService{
|
||||
ds: ds,
|
||||
pluginLoader: pluginLoader,
|
||||
pluginCache: cache.NewSimpleCache[pluginKey, model.LyricList](cache.Options{
|
||||
SizeLimit: lyricsCacheSize,
|
||||
DefaultTTL: lyricsCacheTTL,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// GetLyrics returns lyrics for the given media file, trying sources in the
|
||||
|
|
|
|||
|
|
@ -164,7 +164,7 @@ var _ = Describe("Lyrics", func() {
|
|||
conf.Update(func(c *conf.Options) { c.LyricsPriority = priority })
|
||||
svc := lyrics.NewLyrics(nil, nil)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(expected))
|
||||
},
|
||||
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() {
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = ".ttml,embedded" })
|
||||
embeddedJSON, err := json.Marshal(embeddedLyrics)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
repo := &tests.MockMediaFileRepo{}
|
||||
repo.SetData(model.MediaFiles{
|
||||
|
|
@ -193,7 +193,7 @@ var _ = Describe("Lyrics", func() {
|
|||
svc := lyrics.NewLyrics(&tests.MockDataStore{MockedMediaFile: repo}, nil)
|
||||
|
||||
list, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up")
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(ttmlLyrics))
|
||||
})
|
||||
|
||||
|
|
@ -221,7 +221,7 @@ var _ = Describe("Lyrics", func() {
|
|||
Path: "song.mp3",
|
||||
})
|
||||
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(HaveLen(1))
|
||||
Expect(list[0].Line).To(Equal([]model.Line{
|
||||
{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
|
||||
// doesn't match the structured format, so the .yaml hit is non-empty and
|
||||
// shadows the lower-priority .lrc entirely.
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(HaveLen(1))
|
||||
Expect(list[0].Synced).To(BeFalse())
|
||||
Expect(list[0].Line).To(Equal([]model.Line{
|
||||
|
|
@ -286,7 +286,7 @@ var _ = Describe("Lyrics", func() {
|
|||
|
||||
svc := lyrics.NewLyrics(nil, nil)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(embeddedLyrics))
|
||||
})
|
||||
|
||||
|
|
@ -295,7 +295,7 @@ var _ = Describe("Lyrics", func() {
|
|||
|
||||
svc := lyrics.NewLyrics(nil, nil)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
|
|
@ -313,7 +313,7 @@ var _ = Describe("Lyrics", func() {
|
|||
mockLoader.lyrics = unsyncedLyrics
|
||||
svc := lyrics.NewLyrics(nil, mockLoader)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(unsyncedLyrics))
|
||||
})
|
||||
|
||||
|
|
@ -323,7 +323,7 @@ var _ = Describe("Lyrics", func() {
|
|||
mockLoader.lyrics = unsyncedLyrics
|
||||
svc := lyrics.NewLyrics(nil, mockLoader)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(unsyncedLyrics))
|
||||
})
|
||||
|
||||
|
|
@ -332,7 +332,7 @@ var _ = Describe("Lyrics", func() {
|
|||
mockLoader.lyrics = unsyncedLyrics
|
||||
svc := lyrics.NewLyrics(nil, mockLoader)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(embeddedLyrics)) // embedded wins
|
||||
})
|
||||
|
||||
|
|
@ -341,7 +341,7 @@ var _ = Describe("Lyrics", func() {
|
|||
mockLoader.notFound = true
|
||||
svc := lyrics.NewLyrics(nil, mockLoader)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(embeddedLyrics)) // falls through to embedded
|
||||
})
|
||||
|
||||
|
|
@ -351,7 +351,7 @@ var _ = Describe("Lyrics", func() {
|
|||
mockLoader.lyrics = unsyncedLyrics
|
||||
svc := lyrics.NewLyrics(nil, mockLoader)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(unsyncedLyrics))
|
||||
})
|
||||
|
||||
|
|
@ -360,11 +360,82 @@ var _ = Describe("Lyrics", func() {
|
|||
mockLoader.err = fmt.Errorf("plugin error")
|
||||
svc := lyrics.NewLyrics(nil, mockLoader)
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(embeddedLyrics)) // falls through to embedded
|
||||
})
|
||||
})
|
||||
|
||||
Context("caching", func() {
|
||||
var mockLoader *mockPluginLoader
|
||||
var svc lyrics.Lyrics
|
||||
|
||||
BeforeEach(func() {
|
||||
conf.Update(func(c *conf.Options) { c.LyricsPriority = "test-lyrics-plugin" })
|
||||
mockLoader = &mockPluginLoader{}
|
||||
svc = lyrics.NewLyrics(nil, mockLoader)
|
||||
mf.ID = "mf-1"
|
||||
})
|
||||
|
||||
It("serves a repeated request for the same track from the cache", func() {
|
||||
mockLoader.lyrics = unsyncedLyrics
|
||||
_, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(unsyncedLyrics))
|
||||
Expect(mockLoader.calls).To(Equal(1))
|
||||
})
|
||||
|
||||
It("caches a miss, so a track without lyrics does not reach the plugin again", func() {
|
||||
for range 2 {
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(BeEmpty())
|
||||
}
|
||||
Expect(mockLoader.calls).To(Equal(1))
|
||||
})
|
||||
|
||||
It("caches a plugin error as a miss, since some plugins report no lyrics as an error", func() {
|
||||
mockLoader.err = fmt.Errorf("no lyrics found from any provider")
|
||||
for range 2 {
|
||||
list, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(BeEmpty())
|
||||
}
|
||||
Expect(mockLoader.calls).To(Equal(1))
|
||||
})
|
||||
|
||||
It("looks up each track separately", func() {
|
||||
other := mf
|
||||
other.ID = "mf-2"
|
||||
_, _ = svc.GetLyrics(ctx, &mf)
|
||||
_, _ = svc.GetLyrics(ctx, &other)
|
||||
Expect(mockLoader.calls).To(Equal(2))
|
||||
})
|
||||
|
||||
It("finishes and caches the lookup when the caller's request is cancelled", func() {
|
||||
mockLoader.lyrics = unsyncedLyrics
|
||||
cancelled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
|
||||
list, err := svc.GetLyrics(cancelled, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(unsyncedLyrics))
|
||||
|
||||
list, err = svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(list).To(Equal(unsyncedLyrics))
|
||||
Expect(mockLoader.calls).To(Equal(1))
|
||||
})
|
||||
|
||||
It("bounds the lookup with a deadline", func() {
|
||||
_, err := svc.GetLyrics(ctx, &mf)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(mockLoader.hadDeadline).To(BeTrue())
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("GetLyricsByArtistTitle", func() {
|
||||
var svc lyrics.Lyrics
|
||||
var repo *tests.MockMediaFileRepo
|
||||
|
|
@ -410,10 +481,12 @@ var _ = Describe("Lyrics", func() {
|
|||
})
|
||||
|
||||
type mockPluginLoader struct {
|
||||
lyrics model.LyricList
|
||||
err error
|
||||
notFound bool
|
||||
pluginName string // expected plugin name (exact match, like real manager)
|
||||
lyrics model.LyricList
|
||||
err error
|
||||
notFound bool
|
||||
pluginName string // expected plugin name (exact match, like real manager)
|
||||
calls int
|
||||
hadDeadline bool
|
||||
}
|
||||
|
||||
func (m *mockPluginLoader) PluginNames(_ string) []string {
|
||||
|
|
@ -431,14 +504,18 @@ func (m *mockPluginLoader) LoadLyricsProvider(name string) (lyrics.Provider, boo
|
|||
if m.pluginName != "" && name != m.pluginName {
|
||||
return nil, false
|
||||
}
|
||||
return &mockLyricsProvider{lyrics: m.lyrics, err: m.err}, true
|
||||
return &mockLyricsProvider{loader: m}, true
|
||||
}
|
||||
|
||||
type mockLyricsProvider struct {
|
||||
lyrics model.LyricList
|
||||
err error
|
||||
loader *mockPluginLoader
|
||||
}
|
||||
|
||||
func (m *mockLyricsProvider) GetLyrics(_ context.Context, _ *model.MediaFile) (model.LyricList, error) {
|
||||
return m.lyrics, m.err
|
||||
func (m *mockLyricsProvider) GetLyrics(ctx context.Context, _ *model.MediaFile) (model.LyricList, error) {
|
||||
m.loader.calls++
|
||||
_, m.loader.hadDeadline = ctx.Deadline()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m.loader.lyrics, m.loader.err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import (
|
|||
"io"
|
||||
"io/fs"
|
||||
"path"
|
||||
"time"
|
||||
|
||||
"github.com/navidrome/navidrome/core/storage"
|
||||
"github.com/navidrome/navidrome/log"
|
||||
|
|
@ -68,7 +69,8 @@ func fromExternalFile(ctx context.Context, mf *model.MediaFile, suffix string) (
|
|||
return list, nil
|
||||
}
|
||||
|
||||
// fromPlugin attempts to load lyrics from a plugin with the given name.
|
||||
// fromPlugin attempts to load lyrics from a plugin with the given name. Results are cached,
|
||||
// misses included: clients ask for every track in a queue, and plugin lookups are slow.
|
||||
func (l *lyricsService) fromPlugin(ctx context.Context, mf *model.MediaFile, pluginName string) (model.LyricList, error) {
|
||||
if l.pluginLoader == nil {
|
||||
log.Debug(ctx, "Invalid lyric source", "source", pluginName)
|
||||
|
|
@ -81,13 +83,20 @@ func (l *lyricsService) fromPlugin(ctx context.Context, mf *model.MediaFile, plu
|
|||
return nil, nil
|
||||
}
|
||||
|
||||
lyricsList, err := provider.GetLyrics(ctx, mf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(lyricsList) > 0 {
|
||||
log.Trace(ctx, "Retrieved lyrics from plugin", "plugin", pluginName, "count", len(lyricsList))
|
||||
}
|
||||
return lyricsList, nil
|
||||
key := pluginKey{plugin: pluginName, mediaFileID: mf.ID}
|
||||
return l.pluginCache.GetWithLoader(key, func(pluginKey) (model.LyricList, time.Duration, error) {
|
||||
// Concurrent callers share one load, so one cancelled request must not abort it for the others.
|
||||
loadCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), lyricsLoadTimeout)
|
||||
defer cancel()
|
||||
lyricsList, err := provider.GetLyrics(loadCtx, mf)
|
||||
if err != nil {
|
||||
// Cached as a miss: some plugins report "no lyrics" as an error.
|
||||
log.Error(ctx, "Error getting lyrics from plugin", "plugin", pluginName, err)
|
||||
return nil, 0, nil
|
||||
}
|
||||
if len(lyricsList) > 0 {
|
||||
log.Trace(ctx, "Retrieved lyrics from plugin", "plugin", pluginName, "count", len(lyricsList))
|
||||
}
|
||||
return lyricsList, 0, nil
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,8 +22,8 @@ var _ = Describe("sources", func() {
|
|||
mf := model.MediaFile{}
|
||||
lyrics, err := fromEmbedded(ctx, &mf)
|
||||
|
||||
Expect(err).To(BeNil())
|
||||
Expect(lyrics).To(HaveLen(0))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(lyrics).To(BeEmpty())
|
||||
})
|
||||
|
||||
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)
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(lyrics).ToNot(BeNil())
|
||||
Expect(lyrics).To(Equal(expectedList))
|
||||
})
|
||||
|
|
@ -54,8 +54,8 @@ var _ = Describe("sources", func() {
|
|||
mf := model.MediaFile{Lyrics: "["}
|
||||
lyrics, err := fromEmbedded(ctx, &mf)
|
||||
|
||||
Expect(lyrics).To(HaveLen(0))
|
||||
Expect(err).ToNot(BeNil())
|
||||
Expect(lyrics).To(BeEmpty())
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
|
|
@ -76,8 +76,8 @@ var _ = Describe("sources", func() {
|
|||
It("should return nil for lyrics that don't exist", func() {
|
||||
lyrics, err := fromExternalFile(ctx, mf("01 Invisible (RED) Edit Version.mp3"), ".lrc")
|
||||
|
||||
Expect(err).To(BeNil())
|
||||
Expect(lyrics).To(HaveLen(0))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(lyrics).To(BeEmpty())
|
||||
})
|
||||
|
||||
// fromExternalFile delegates format parsing to model.ParseLyrics; the
|
||||
|
|
@ -87,7 +87,7 @@ var _ = Describe("sources", func() {
|
|||
func(name, suffix string, expectSynced bool) {
|
||||
lyrics, err := fromExternalFile(ctx, mf(name), suffix)
|
||||
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(lyrics).ToNot(BeEmpty())
|
||||
Expect(lyrics[0].Line).ToNot(BeEmpty())
|
||||
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() {
|
||||
lyrics, err := fromExternalFile(ctx, mf("bom-test.mp3"), ".lrc")
|
||||
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(lyrics).To(HaveLen(1))
|
||||
Expect(lyrics[0].Synced).To(BeTrue(), "Lyrics with BOM marker should be recognized as synced")
|
||||
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() {
|
||||
lyrics, err := fromExternalFile(ctx, mf("bom-utf16-test.mp3"), ".lrc")
|
||||
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(lyrics).To(HaveLen(1))
|
||||
Expect(lyrics[0].Synced).To(BeTrue(), "UTF-16 encoded lyrics should be recognized as synced")
|
||||
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() {
|
||||
lyrics, err := fromExternalFile(ctx, mf("bom-test.mp3"), ".ttml")
|
||||
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(lyrics).To(HaveLen(1))
|
||||
Expect(lyrics[0].Kind).To(Equal("main"))
|
||||
Expect(lyrics[0].Synced).To(BeTrue())
|
||||
|
|
@ -139,7 +139,7 @@ var _ = Describe("sources", func() {
|
|||
It("should handle UTF-16 BE encoded TTML files", func() {
|
||||
lyrics, err := fromExternalFile(ctx, mf("bom-utf16-test.mp3"), ".ttml")
|
||||
|
||||
Expect(err).To(BeNil())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(lyrics).To(HaveLen(1))
|
||||
Expect(lyrics[0].Kind).To(Equal("main"))
|
||||
Expect(lyrics[0].Synced).To(BeTrue())
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ var _ = Describe("Maintenance", func() {
|
|||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
ctx = request.WithUser(ctx, model.User{ID: "user1", IsAdmin: true})
|
||||
|
||||
ds = createTestDataStore()
|
||||
|
|
@ -395,7 +395,7 @@ var _ = Describe("Maintenance", func() {
|
|||
|
||||
It("preserves the target's participants on the remapped track", func() {
|
||||
participant := model.Participant{
|
||||
Artist: model.Artist{ID: "a1", Name: "Artist", OrderArtistName: "artist", MbzArtistID: "mbz-artist"},
|
||||
ID: "a1", Name: "Artist", OrderArtistName: "artist", MbzArtistID: "mbz-artist",
|
||||
}
|
||||
mfRepo.SetData(model.MediaFiles{
|
||||
{ID: "m1", AlbumID: "album1", Missing: true},
|
||||
|
|
|
|||
|
|
@ -353,10 +353,10 @@ var _ = Describe("Matcher", func() {
|
|||
ID: "comp", Title: "Qmart", Artist: "Björk",
|
||||
Participants: model.Participants{
|
||||
model.RoleArtist: model.ParticipantList{
|
||||
{Artist: model.Artist{ID: "a-bjork", Name: "Björk", OrderArtistName: "bjork"}},
|
||||
{ID: "a-bjork", Name: "Björk", OrderArtistName: "bjork"},
|
||||
},
|
||||
model.RoleAlbumArtist: model.ParticipantList{
|
||||
{Artist: model.Artist{ID: "a-808", Name: "808 State", OrderArtistName: "808 state"}},
|
||||
{ID: "a-808", Name: "808 State", OrderArtistName: "808 state"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -545,7 +545,7 @@ var _ = Describe("Matcher", func() {
|
|||
// Shares only Drake (overlap 1) but starred.
|
||||
starredOne := model.MediaFile{
|
||||
ID: "starred-one", Title: "Collab Hit",
|
||||
Annotations: model.Annotations{Starred: true},
|
||||
Starred: true,
|
||||
Participants: artistParticipants(model.Artist{ID: "id-drake", Name: "Drake", OrderArtistName: "drake"}),
|
||||
}
|
||||
// Shares both (overlap 2), not starred.
|
||||
|
|
@ -958,7 +958,7 @@ var _ = Describe("Matcher", func() {
|
|||
}
|
||||
starredTrack := model.MediaFile{
|
||||
ID: "starred", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Singles",
|
||||
Annotations: model.Annotations{Starred: true},
|
||||
Starred: true,
|
||||
Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}),
|
||||
}
|
||||
allowTitlePhase(model.MediaFiles{albumMatch, starredTrack})
|
||||
|
|
@ -979,7 +979,7 @@ var _ = Describe("Matcher", func() {
|
|||
}
|
||||
ratedTrack := model.MediaFile{
|
||||
ID: "rated", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Singles",
|
||||
Annotations: model.Annotations{Rating: 4},
|
||||
Rating: 4,
|
||||
Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}),
|
||||
}
|
||||
allowTitlePhase(model.MediaFiles{albumMatch, ratedTrack})
|
||||
|
|
@ -1001,7 +1001,7 @@ var _ = Describe("Matcher", func() {
|
|||
}
|
||||
starred := model.MediaFile{
|
||||
ID: "starred", Title: "Enjoy the Silence", Artist: "Depeche Mode", Album: "Violator",
|
||||
Annotations: model.Annotations{Starred: true},
|
||||
Starred: true,
|
||||
Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}),
|
||||
}
|
||||
allowTitlePhase(model.MediaFiles{plain, starred})
|
||||
|
|
|
|||
|
|
@ -109,7 +109,7 @@ func (c *insightsCollector) sendInsights(ctx context.Context) {
|
|||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := hc.Do(req) //nolint:gosec
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
log.Trace(ctx, "Could not send Insights data", err)
|
||||
return
|
||||
|
|
|
|||
|
|
@ -24,11 +24,11 @@ func getOSVersion() (string, string) {
|
|||
version := ""
|
||||
distro := ""
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(line, "VERSION_ID=") {
|
||||
version = strings.ReplaceAll(strings.TrimPrefix(line, "VERSION_ID="), "\"", "")
|
||||
if v, ok := strings.CutPrefix(line, "VERSION_ID="); ok {
|
||||
version = strings.ReplaceAll(v, "\"", "")
|
||||
}
|
||||
if strings.HasPrefix(line, "ID=") {
|
||||
distro = strings.ReplaceAll(strings.TrimPrefix(line, "ID="), "\"", "")
|
||||
if v, ok := strings.CutPrefix(line, "ID="); ok {
|
||||
distro = strings.ReplaceAll(v, "\"", "")
|
||||
}
|
||||
}
|
||||
return version, distro
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ package mpv
|
|||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
|
@ -20,11 +19,13 @@ import (
|
|||
|
||||
var _ = Describe("MPV", func() {
|
||||
var (
|
||||
ctx context.Context
|
||||
testScript string
|
||||
tempDir string
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
|
||||
// Reset MPV cache
|
||||
mpvOnce = sync.Once{}
|
||||
|
|
@ -213,7 +214,7 @@ var _ = Describe("MPV", func() {
|
|||
|
||||
It("executes MPV command and captures arguments correctly", func() {
|
||||
tests.SkipOnWindows("mpv binary not available in CI (#TBD-mpv-windows)")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
deviceName := "auto"
|
||||
|
|
@ -241,7 +242,7 @@ var _ = Describe("MPV", func() {
|
|||
|
||||
It("handles file paths with spaces", func() {
|
||||
tests.SkipOnWindows("mpv binary not available in CI (#TBD-mpv-windows)")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
deviceName := "auto"
|
||||
|
|
@ -271,7 +272,7 @@ var _ = Describe("MPV", func() {
|
|||
|
||||
It("passes all snapcast arguments correctly", func() {
|
||||
tests.SkipOnWindows("mpv binary not available in CI (#TBD-mpv-windows)")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
deviceName := "auto"
|
||||
|
|
@ -304,7 +305,7 @@ var _ = Describe("MPV", func() {
|
|||
|
||||
Context("with nil args", func() {
|
||||
It("returns error when args is nil", func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := start(ctx, nil)
|
||||
|
|
@ -313,7 +314,7 @@ var _ = Describe("MPV", func() {
|
|||
})
|
||||
|
||||
It("returns error when args is empty", func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := start(ctx, []string{})
|
||||
|
|
@ -361,7 +362,7 @@ var _ = Describe("MPV", func() {
|
|||
})
|
||||
|
||||
It("returns error when createMPVCommand fails", func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
|
||||
ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
|
||||
defer cancel()
|
||||
|
||||
playbackDone := make(chan bool, 1)
|
||||
|
|
@ -375,6 +376,7 @@ var _ = Describe("MPV", func() {
|
|||
|
||||
// createMockMPVScript creates a mock script that outputs arguments to stdout
|
||||
func createMockMPVScript(tempDir string) string {
|
||||
GinkgoHelper()
|
||||
var scriptContent string
|
||||
var scriptExt string
|
||||
|
||||
|
|
@ -400,10 +402,7 @@ done
|
|||
}
|
||||
|
||||
scriptPath := filepath.Join(tempDir, "mock_mpv"+scriptExt)
|
||||
err := os.WriteFile(scriptPath, []byte(scriptContent), 0755) // nolint:gosec
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("Failed to create mock script: %v", err))
|
||||
}
|
||||
Expect(os.WriteFile(scriptPath, []byte(scriptContent), 0755)).To(Succeed()) //nolint:gosec
|
||||
|
||||
return scriptPath
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,12 +15,13 @@ import (
|
|||
var _ = Describe("Players", func() {
|
||||
var players Players
|
||||
var repo *mockPlayerRepository
|
||||
ctx := log.NewContext(context.TODO())
|
||||
ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "johndoe"})
|
||||
ctx = request.WithUsername(ctx, "johndoe")
|
||||
var ctx context.Context
|
||||
var beforeRegister time.Time
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = log.NewContext(GinkgoT().Context())
|
||||
ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "johndoe"})
|
||||
ctx = request.WithUsername(ctx, "johndoe")
|
||||
repo = &mockPlayerRepository{}
|
||||
ds := &tests.MockDataStore{MockedPlayer: repo, MockedTranscoding: &tests.MockTranscodingRepo{}}
|
||||
players = NewPlayers(ds)
|
||||
|
|
@ -124,9 +125,10 @@ var _ = Describe("Players", func() {
|
|||
})
|
||||
|
||||
Context("bad username casing", func() {
|
||||
ctx := log.NewContext(context.TODO())
|
||||
ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "Johndoe"})
|
||||
ctx = request.WithUsername(ctx, "Johndoe")
|
||||
BeforeEach(func() {
|
||||
ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "Johndoe"})
|
||||
ctx = request.WithUsername(ctx, "Johndoe")
|
||||
})
|
||||
|
||||
It("finds player by client and user names when not ID is provided", func() {
|
||||
plr := &model.Player{ID: "123", Name: "A Player", Client: "client", UserId: "userid", UserAgent: "chrome", LastSeen: time.Time{}}
|
||||
|
|
|
|||
|
|
@ -28,9 +28,10 @@ var _ = Describe("Playlists - Import", func() {
|
|||
var ps playlists.Playlists
|
||||
var mockPlsRepo *tests.MockPlaylistRepo
|
||||
var mockLibRepo *tests.MockLibraryRepo
|
||||
ctx := context.Background()
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
mockPlsRepo = tests.CreateMockPlaylistRepo()
|
||||
mockLibRepo = &tests.MockLibraryRepo{}
|
||||
ds = &tests.MockDataStore{
|
||||
|
|
|
|||
|
|
@ -13,9 +13,10 @@ var _ = Describe("pathResolver", func() {
|
|||
var ds *tests.MockDataStore
|
||||
var mockLibRepo *tests.MockLibraryRepo
|
||||
var resolver *pathResolver
|
||||
ctx := context.Background()
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
tests.SkipOnWindows("path separator bug (#TBD-path-sep-playlists)")
|
||||
mockLibRepo = &tests.MockLibraryRepo{}
|
||||
ds = &tests.MockDataStore{
|
||||
|
|
|
|||
|
|
@ -15,9 +15,10 @@ import (
|
|||
|
||||
var _ = Describe("parseNSP", func() {
|
||||
var s *playlists
|
||||
ctx := context.Background()
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
s = &playlists{}
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -5,9 +5,9 @@ import (
|
|||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/bmatcuk/doublestar/v4"
|
||||
"github.com/deluan/rest"
|
||||
"github.com/navidrome/navidrome/conf"
|
||||
|
|
@ -190,15 +190,22 @@ func (s *playlists) Update(ctx context.Context, playlistID string,
|
|||
|
||||
if len(idxToRemove) > 0 {
|
||||
tracksRepo := repo.Tracks(ctx, playlistID, false)
|
||||
// Convert 0-based indices to 1-based position IDs and delete them directly,
|
||||
// avoiding the need to load all tracks into memory.
|
||||
positions := make([]string, len(idxToRemove))
|
||||
for i, idx := range idxToRemove {
|
||||
positions[i] = strconv.Itoa(idx + 1)
|
||||
}
|
||||
if err := tracksRepo.Delete(ctx, positions...); err != nil {
|
||||
// Indexes refer to GetWithTracks' list, which hides missing and inaccessible-library tracks.
|
||||
visible, err := tracksRepo.GetPositionIDs(ctx, model.QueryOptions{Sort: "id", Filters: squirrel.Eq{"missing": false}})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(idsToAdd) > 0 {
|
||||
if _, err := tracksRepo.Add(ctx, idsToAdd); err != nil {
|
||||
return err
|
||||
|
|
|
|||
|
|
@ -21,9 +21,10 @@ var _ = Describe("Playlists", func() {
|
|||
var ds *tests.MockDataStore
|
||||
var ps playlists.Playlists
|
||||
var mockPlsRepo *tests.MockPlaylistRepo
|
||||
ctx := context.Background()
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
mockPlsRepo = tests.CreateMockPlaylistRepo()
|
||||
ds = &tests.MockDataStore{
|
||||
MockedPlaylist: mockPlsRepo,
|
||||
|
|
|
|||
|
|
@ -19,9 +19,10 @@ var _ = Describe("REST Adapter", func() {
|
|||
var ds *tests.MockDataStore
|
||||
var ps playlists.Playlists
|
||||
var mockPlsRepo *tests.MockPlaylistRepo
|
||||
ctx := context.Background()
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
mockPlsRepo = tests.CreateMockPlaylistRepo()
|
||||
ds = &tests.MockDataStore{
|
||||
MockedPlaylist: mockPlsRepo,
|
||||
|
|
|
|||
|
|
@ -29,6 +29,10 @@ func ImageURL(ctx context.Context, artID model.ArtworkID, size int) string {
|
|||
return PublicURL(ctx, uri, params)
|
||||
}
|
||||
|
||||
func ShareURL(ctx context.Context, id string) string {
|
||||
return PublicURL(ctx, path.Join(consts.URLPathPublic, id), nil)
|
||||
}
|
||||
|
||||
// PublicURL builds a full URL for public-facing resources.
|
||||
// It uses ShareURL from config if available, otherwise falls back to the address the
|
||||
// client used to reach the server, recorded in the context.
|
||||
|
|
|
|||
|
|
@ -28,6 +28,11 @@ func TestPublicURL(t *testing.T) {
|
|||
var _ = configtest.RestoreAfterEachSpec()
|
||||
|
||||
var _ = Describe("Public URL Utilities", func() {
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
})
|
||||
|
||||
Describe("PublicURL", func() {
|
||||
When("ShareURL is set", func() {
|
||||
|
|
@ -36,13 +41,13 @@ var _ = Describe("Public URL Utilities", func() {
|
|||
})
|
||||
|
||||
It("uses ShareURL as the base", func() {
|
||||
result := publicurl.PublicURL(context.Background(), "/path/to/resource", nil)
|
||||
result := publicurl.PublicURL(ctx, "/path/to/resource", nil)
|
||||
Expect(result).To(Equal("https://share.example.com/path/to/resource"))
|
||||
})
|
||||
|
||||
It("includes query parameters", func() {
|
||||
params := url.Values{"size": []string{"300"}, "format": []string{"png"}}
|
||||
result := publicurl.PublicURL(context.Background(), "/image/123", params)
|
||||
result := publicurl.PublicURL(ctx, "/image/123", params)
|
||||
Expect(result).To(ContainSubstring("https://share.example.com/image/123"))
|
||||
Expect(result).To(ContainSubstring("size=300"))
|
||||
Expect(result).To(ContainSubstring("format=png"))
|
||||
|
|
@ -55,19 +60,19 @@ var _ = Describe("Public URL Utilities", func() {
|
|||
})
|
||||
|
||||
It("prepends the ShareURL path to the resource", func() {
|
||||
result := publicurl.PublicURL(context.Background(), "/share/img/hash", nil)
|
||||
result := publicurl.PublicURL(ctx, "/share/img/hash", nil)
|
||||
Expect(result).To(Equal("https://example.com/navi/share/img/hash"))
|
||||
})
|
||||
|
||||
It("prepends the ShareURL path and includes query parameters", func() {
|
||||
params := url.Values{"size": []string{"600"}}
|
||||
result := publicurl.PublicURL(context.Background(), "/share/img/hash", params)
|
||||
result := publicurl.PublicURL(ctx, "/share/img/hash", params)
|
||||
Expect(result).To(Equal("https://example.com/navi/share/img/hash?size=600"))
|
||||
})
|
||||
|
||||
It("handles trailing slash in ShareURL path", func() {
|
||||
conf.Update(func(c *conf.Options) { c.ShareURL = "https://example.com/navi/" })
|
||||
result := publicurl.PublicURL(context.Background(), "/share/img/hash", nil)
|
||||
result := publicurl.PublicURL(ctx, "/share/img/hash", nil)
|
||||
Expect(result).To(Equal("https://example.com/navi/share/img/hash"))
|
||||
})
|
||||
})
|
||||
|
|
@ -78,14 +83,14 @@ var _ = Describe("Public URL Utilities", func() {
|
|||
})
|
||||
|
||||
It("falls back to AbsoluteURL with request", func() {
|
||||
ctx := request.WithServerAddress(context.Background(), "https", "myserver.com")
|
||||
ctx = request.WithServerAddress(ctx, "https", "myserver.com")
|
||||
result := publicurl.PublicURL(ctx, "/path/to/resource", nil)
|
||||
Expect(result).To(Equal("https://myserver.com/path/to/resource"))
|
||||
})
|
||||
|
||||
It("falls back to localhost on the configured port without request", func() {
|
||||
conf.Update(func(c *conf.Options) { c.Port = 4533 })
|
||||
result := publicurl.PublicURL(context.Background(), "/path/to/resource", nil)
|
||||
result := publicurl.PublicURL(ctx, "/path/to/resource", nil)
|
||||
Expect(result).To(Equal("http://localhost:4533/path/to/resource"))
|
||||
})
|
||||
})
|
||||
|
|
@ -102,13 +107,13 @@ var _ = Describe("Public URL Utilities", func() {
|
|||
})
|
||||
|
||||
It("uses BaseHost and BaseScheme", func() {
|
||||
result := publicurl.AbsoluteURL(context.Background(), "/path/to/resource", nil)
|
||||
result := publicurl.AbsoluteURL(ctx, "/path/to/resource", nil)
|
||||
Expect(result).To(Equal("https://configured.example.com/path/to/resource"))
|
||||
})
|
||||
|
||||
It("defaults to http scheme if BaseScheme is empty", func() {
|
||||
conf.Update(func(c *conf.Options) { c.BaseScheme = "" })
|
||||
result := publicurl.AbsoluteURL(context.Background(), "/path/to/resource", nil)
|
||||
result := publicurl.AbsoluteURL(ctx, "/path/to/resource", nil)
|
||||
Expect(result).To(Equal("http://configured.example.com/path/to/resource"))
|
||||
})
|
||||
})
|
||||
|
|
@ -122,14 +127,14 @@ var _ = Describe("Public URL Utilities", func() {
|
|||
})
|
||||
|
||||
It("extracts host from request", func() {
|
||||
ctx := request.WithServerAddress(context.Background(), "https", "request.example.com")
|
||||
ctx = request.WithServerAddress(ctx, "https", "request.example.com")
|
||||
result := publicurl.AbsoluteURL(ctx, "/path/to/resource", nil)
|
||||
Expect(result).To(Equal("https://request.example.com/path/to/resource"))
|
||||
})
|
||||
|
||||
It("falls back to localhost on the configured port without request", func() {
|
||||
conf.Update(func(c *conf.Options) { c.Port = 8080 })
|
||||
result := publicurl.AbsoluteURL(context.Background(), "/path/to/resource", nil)
|
||||
result := publicurl.AbsoluteURL(ctx, "/path/to/resource", nil)
|
||||
Expect(result).To(Equal("http://localhost:8080/path/to/resource"))
|
||||
})
|
||||
|
||||
|
|
@ -139,7 +144,7 @@ var _ = Describe("Public URL Utilities", func() {
|
|||
c.TLSCert = "cert.pem"
|
||||
c.TLSKey = "key.pem"
|
||||
})
|
||||
result := publicurl.AbsoluteURL(context.Background(), "/path/to/resource", nil)
|
||||
result := publicurl.AbsoluteURL(ctx, "/path/to/resource", nil)
|
||||
Expect(result).To(Equal("https://localhost:4533/path/to/resource"))
|
||||
})
|
||||
|
||||
|
|
@ -148,7 +153,7 @@ var _ = Describe("Public URL Utilities", func() {
|
|||
c.Port = 4533
|
||||
c.TLSCert = "cert.pem"
|
||||
})
|
||||
result := publicurl.AbsoluteURL(context.Background(), "/path/to/resource", nil)
|
||||
result := publicurl.AbsoluteURL(ctx, "/path/to/resource", nil)
|
||||
Expect(result).To(Equal("http://localhost:4533/path/to/resource"))
|
||||
})
|
||||
})
|
||||
|
|
@ -163,13 +168,13 @@ var _ = Describe("Public URL Utilities", func() {
|
|||
})
|
||||
|
||||
It("prepends BasePath to the URL", func() {
|
||||
result := publicurl.AbsoluteURL(context.Background(), "/path/to/resource", nil)
|
||||
result := publicurl.AbsoluteURL(ctx, "/path/to/resource", nil)
|
||||
Expect(result).To(Equal("https://example.com/navidrome/path/to/resource"))
|
||||
})
|
||||
})
|
||||
|
||||
It("passes through absolute URLs unchanged", func() {
|
||||
result := publicurl.AbsoluteURL(context.Background(), "https://other.example.com/path", nil)
|
||||
result := publicurl.AbsoluteURL(ctx, "https://other.example.com/path", nil)
|
||||
Expect(result).To(Equal("https://other.example.com/path"))
|
||||
})
|
||||
|
||||
|
|
@ -179,7 +184,7 @@ var _ = Describe("Public URL Utilities", func() {
|
|||
c.BaseScheme = "https"
|
||||
})
|
||||
params := url.Values{"key": []string{"value"}}
|
||||
result := publicurl.AbsoluteURL(context.Background(), "/path", params)
|
||||
result := publicurl.AbsoluteURL(ctx, "/path", params)
|
||||
Expect(result).To(Equal("https://example.com/path?key=value"))
|
||||
})
|
||||
})
|
||||
|
|
@ -193,23 +198,35 @@ var _ = Describe("Public URL Utilities", func() {
|
|||
|
||||
It("generates a URL with the artwork token", func() {
|
||||
artID := model.NewArtworkID(model.KindAlbumArtwork, "album-123", nil)
|
||||
result := publicurl.ImageURL(context.Background(), artID, 0)
|
||||
result := publicurl.ImageURL(ctx, artID, 0)
|
||||
Expect(result).To(HavePrefix("https://share.example.com/share/img/"))
|
||||
})
|
||||
|
||||
It("includes size parameter when provided", func() {
|
||||
artID := model.NewArtworkID(model.KindArtistArtwork, "artist-1", nil)
|
||||
result := publicurl.ImageURL(context.Background(), artID, 300)
|
||||
result := publicurl.ImageURL(ctx, artID, 300)
|
||||
Expect(result).To(ContainSubstring("size=300"))
|
||||
})
|
||||
|
||||
It("omits size parameter when zero", func() {
|
||||
artID := model.NewArtworkID(model.KindMediaFileArtwork, "track-1", nil)
|
||||
result := publicurl.ImageURL(context.Background(), artID, 0)
|
||||
result := publicurl.ImageURL(ctx, artID, 0)
|
||||
Expect(result).ToNot(ContainSubstring("size="))
|
||||
})
|
||||
})
|
||||
|
||||
Describe("ShareURL", func() {
|
||||
It("builds the share page URL under the configured ShareURL path", func() {
|
||||
conf.Update(func(c *conf.Options) { c.ShareURL = "https://example.com/navi/" })
|
||||
Expect(publicurl.ShareURL(ctx, "abc123")).To(Equal("https://example.com/navi/share/abc123"))
|
||||
})
|
||||
|
||||
It("uses the request address when ShareURL is not set", func() {
|
||||
ctx = request.WithServerAddress(ctx, "https", "music.example.com")
|
||||
Expect(publicurl.ShareURL(ctx, "abc123")).To(Equal("https://music.example.com/share/abc123"))
|
||||
})
|
||||
})
|
||||
|
||||
Describe("ImageURL address precedence", func() {
|
||||
var artID model.ArtworkID
|
||||
|
||||
|
|
@ -219,7 +236,7 @@ var _ = Describe("Public URL Utilities", func() {
|
|||
})
|
||||
|
||||
It("uses the address of the request that triggered the call", func() {
|
||||
ctx := request.WithServerAddress(context.Background(), "https", "music.example.com")
|
||||
ctx = request.WithServerAddress(ctx, "https", "music.example.com")
|
||||
|
||||
result := publicurl.ImageURL(ctx, artID, 300)
|
||||
Expect(result).To(HavePrefix("https://music.example.com/share/img/"))
|
||||
|
|
@ -228,7 +245,7 @@ var _ = Describe("Public URL Utilities", func() {
|
|||
|
||||
It("prefers ShareURL over the address in the context", func() {
|
||||
conf.Update(func(c *conf.Options) { c.ShareURL = "https://share.example.com" })
|
||||
ctx := request.WithServerAddress(context.Background(), "https", "music.example.com")
|
||||
ctx = request.WithServerAddress(ctx, "https", "music.example.com")
|
||||
|
||||
result := publicurl.ImageURL(ctx, artID, 0)
|
||||
Expect(result).To(HavePrefix("https://share.example.com/share/img/"))
|
||||
|
|
@ -236,7 +253,7 @@ var _ = Describe("Public URL Utilities", func() {
|
|||
|
||||
It("falls back to localhost on the configured port when no address is available", func() {
|
||||
conf.Update(func(c *conf.Options) { c.Port = 4533 })
|
||||
result := publicurl.ImageURL(context.Background(), artID, 0)
|
||||
result := publicurl.ImageURL(ctx, artID, 0)
|
||||
Expect(result).To(HavePrefix("http://localhost:4533/share/img/"))
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -100,7 +100,7 @@ func (qc *quickConnect) Initiate(device Device) (Request, error) {
|
|||
App: strings.Clone(device.App), AppVersion: strings.Clone(device.AppVersion)}
|
||||
now := time.Now()
|
||||
e := &entry{
|
||||
Request: Request{Device: device, Secret: newSecret(), Code: qc.newCode(), DateAdded: now},
|
||||
Device: device, Secret: newSecret(), Code: qc.newCode(), DateAdded: now,
|
||||
expiresAt: now.Add(timeout),
|
||||
}
|
||||
qc.bySecret[e.Secret] = e
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ var _ = Describe("BufferedScrobbler", func() {
|
|||
var buffer *tests.MockedScrobbleBufferRepo
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = context.Background()
|
||||
ctx = GinkgoT().Context()
|
||||
buffer = tests.CreateMockedScrobbleBufferRepo()
|
||||
userRepo := tests.CreateMockUserRepo()
|
||||
Expect(userRepo.Put(ctx, &model.User{ID: "user1", UserName: "alice"})).To(Succeed())
|
||||
|
|
@ -142,7 +142,7 @@ func TestBufferedScrobblerBackoffSchedule(t *testing.T) {
|
|||
// Let the loop settle on the empty buffer, then enqueue a scrobble.
|
||||
synctest.Wait()
|
||||
track := model.MediaFile{ID: "123", Title: "Test Track", Artist: "Test Artist"}
|
||||
g.Expect(bs.Scrobble(context.Background(), "user1", Scrobble{MediaFile: track, TimeStamp: time.Now()})).To(Succeed())
|
||||
g.Expect(bs.Scrobble(t.Context(), "user1", Scrobble{MediaFile: track, TimeStamp: time.Now()})).To(Succeed())
|
||||
|
||||
// First attempt fires immediately on the enqueue wake and is left buffered.
|
||||
synctest.Wait()
|
||||
|
|
@ -184,7 +184,7 @@ func TestBufferedScrobblerBackoffWindow(t *testing.T) {
|
|||
defer bs.Stop()
|
||||
|
||||
// First enqueue: one immediate attempt, then a 5s window opens.
|
||||
_ = bs.Scrobble(context.Background(), "user1", Scrobble{MediaFile: model.MediaFile{ID: "1"}, TimeStamp: time.Now()})
|
||||
_ = bs.Scrobble(t.Context(), "user1", Scrobble{ID: "1", TimeStamp: time.Now()})
|
||||
synctest.Wait()
|
||||
if got := scr.ScrobbleAttempts(); got != 1 {
|
||||
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.
|
||||
time.Sleep(1 * time.Second)
|
||||
_ = bs.Scrobble(context.Background(), "user1", Scrobble{MediaFile: model.MediaFile{ID: "2"}, TimeStamp: time.Now()})
|
||||
_ = bs.Scrobble(t.Context(), "user1", Scrobble{ID: "2", TimeStamp: time.Now()})
|
||||
synctest.Wait()
|
||||
if got := scr.ScrobbleAttempts(); got != 1 {
|
||||
t.Fatalf("wake during backoff drained early: %d attempts", got)
|
||||
|
|
@ -218,7 +218,7 @@ func TestBufferedScrobblerHonorsServerDelay(t *testing.T) {
|
|||
bs := newBufferedScrobbler(ds, scr, "test")
|
||||
defer bs.Stop()
|
||||
|
||||
_ = bs.Scrobble(context.Background(), "user1", Scrobble{MediaFile: model.MediaFile{ID: "1"}, TimeStamp: time.Now()})
|
||||
_ = bs.Scrobble(t.Context(), "user1", Scrobble{ID: "1", TimeStamp: time.Now()})
|
||||
synctest.Wait()
|
||||
if got := scr.ScrobbleAttempts(); got != 1 {
|
||||
t.Fatalf("expected 1 attempt, got %d", got)
|
||||
|
|
|
|||
|
|
@ -161,7 +161,7 @@ func newPlayTracker(ds model.DataStore, broker events.Broker, pluginManager Plug
|
|||
for name, constructor := range constructors {
|
||||
s := constructor(ds)
|
||||
if s == nil {
|
||||
log.Debug("Scrobbler not available. Missing configuration?", "name", name)
|
||||
log.Debug("Scrobbler not available. Disabled or missing configuration?", "name", name)
|
||||
continue
|
||||
}
|
||||
enabled = append(enabled, name)
|
||||
|
|
@ -588,6 +588,11 @@ func Register(name string, init Constructor) {
|
|||
constructors[name] = init
|
||||
}
|
||||
|
||||
// Unregister removes a builtin scrobbler registration, so tests can start from a clean registry.
|
||||
func Unregister(name string) {
|
||||
delete(constructors, name)
|
||||
}
|
||||
|
||||
// IsBuiltinScrobbler reports whether name belongs to a registered builtin
|
||||
// scrobbler (e.g. "lastfm", "listenbrainz").
|
||||
func IsBuiltinScrobbler(name string) bool {
|
||||
|
|
|
|||
|
|
@ -141,6 +141,12 @@ var _ = Describe("PlayTracker", func() {
|
|||
Expect(IsBuiltinScrobbler("fake")).To(BeTrue())
|
||||
Expect(IsBuiltinScrobbler("some-plugin")).To(BeFalse())
|
||||
})
|
||||
|
||||
It("is false after Unregister", func() {
|
||||
Register("to-remove", func(model.DataStore) Scrobbler { return nil })
|
||||
Unregister("to-remove")
|
||||
Expect(IsBuiltinScrobbler("to-remove")).To(BeFalse())
|
||||
})
|
||||
})
|
||||
|
||||
Describe("GetNowPlaying", func() {
|
||||
|
|
@ -378,7 +384,7 @@ var _ = Describe("PlayTracker", func() {
|
|||
Expect(err).ToNot(HaveOccurred())
|
||||
mockDS := ds.(*tests.MockDataStore)
|
||||
mockScrobble := mockDS.Scrobble().(*tests.MockScrobbleRepo)
|
||||
Expect(mockScrobble.RecordedScrobbles).To(HaveLen(0))
|
||||
Expect(mockScrobble.RecordedScrobbles).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
@ -1557,9 +1563,9 @@ func (f *fakeScrobbler) PlaybackReport(ctx context.Context, info PlaybackSession
|
|||
}
|
||||
|
||||
func _p(id, name string, sortName ...string) model.Participant {
|
||||
p := model.Participant{Artist: model.Artist{ID: id, Name: name}}
|
||||
p := model.Participant{ID: id, Name: name}
|
||||
if len(sortName) > 0 {
|
||||
p.Artist.SortArtistName = sortName[0]
|
||||
p.SortArtistName = sortName[0]
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import (
|
|||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/model"
|
||||
"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/slice"
|
||||
"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 {
|
||||
return nil, err
|
||||
}
|
||||
expiresAt := V(share.ExpiresAt)
|
||||
expiresAt := gg.V(share.ExpiresAt)
|
||||
if !expiresAt.IsZero() && expiresAt.Before(time.Now()) {
|
||||
return nil, model.ErrExpired
|
||||
}
|
||||
|
|
@ -91,7 +91,7 @@ func (r *shareRepositoryWrapper) Save(ctx context.Context, s *model.Share) (stri
|
|||
return "", err
|
||||
}
|
||||
s.ID = id
|
||||
if V(s.ExpiresAt).IsZero() {
|
||||
if gg.V(s.ExpiresAt).IsZero() {
|
||||
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.
|
||||
func (r *shareRepositoryWrapper) resourceType(ctx context.Context, resourceIDs string) (string, error) {
|
||||
resourceType := ""
|
||||
for _, id := range strings.Split(resourceIDs, ",") {
|
||||
for id := range strings.SplitSeq(resourceIDs, ",") {
|
||||
kind, err := model.GetEntityKindByID(ctx, r.ds, id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
|
|
@ -142,7 +142,7 @@ func (r *shareRepositoryWrapper) Update(ctx context.Context, id string, entity m
|
|||
cols := []string{"description", "downloadable"}
|
||||
|
||||
// TODO Better handling of Share expiration
|
||||
if !V(entity.ExpiresAt).IsZero() {
|
||||
if !gg.V(entity.ExpiresAt).IsZero() {
|
||||
cols = append(cols, "expires_at")
|
||||
}
|
||||
return r.ShareRepository.Update(ctx, id, entity, cols...)
|
||||
|
|
|
|||
|
|
@ -15,9 +15,10 @@ var _ = Describe("Share", func() {
|
|||
var ds model.DataStore
|
||||
var share Share
|
||||
var mockedRepo rest.Persistable[model.Share]
|
||||
ctx := context.Background()
|
||||
var ctx context.Context
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
ds = &tests.MockDataStore{}
|
||||
mockedRepo = ds.Share().(rest.Persistable[model.Share])
|
||||
share = NewShare(ds)
|
||||
|
|
@ -41,7 +42,7 @@ var _ = Describe("Share", func() {
|
|||
})
|
||||
|
||||
It("assigns the logged-in user as owner, ignoring a client-supplied UserID", func() {
|
||||
loggedInCtx := request.WithUser(context.Background(), model.User{ID: "logged-in-user"})
|
||||
loggedInCtx := request.WithUser(ctx, model.User{ID: "logged-in-user"})
|
||||
repo := share.Repository().(rest.Persistable[model.Share])
|
||||
entity := &model.Share{Description: "test", ResourceIDs: "123", UserID: "victim-user"}
|
||||
_, err := repo.Save(loggedInCtx, entity)
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ func newLocalStorage(u url.URL) storage.Storage {
|
|||
|
||||
func (s *localStorage) FS() (storage.MusicFS, error) {
|
||||
path := s.u.Path
|
||||
if _, err := os.Stat(path); err != nil { //nolint:gosec
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
return nil, fmt.Errorf("%w: %s", err, path)
|
||||
}
|
||||
return &localFS{FS: os.DirFS(path), extractor: s.extractor, root: path}, nil
|
||||
|
|
|
|||
|
|
@ -17,10 +17,12 @@ import (
|
|||
)
|
||||
|
||||
var _ = XDescribe("Watcher", func() {
|
||||
var ctx context.Context
|
||||
var lsw storage.Watcher
|
||||
var tmpFolder string
|
||||
|
||||
BeforeEach(func() {
|
||||
ctx = GinkgoT().Context()
|
||||
tmpFolder = GinkgoT().TempDir()
|
||||
|
||||
local.RegisterExtractor("noop", func(fs fs.FS, path string) local.Extractor { return noopExtractor{} })
|
||||
|
|
@ -42,19 +44,16 @@ var _ = XDescribe("Watcher", func() {
|
|||
})
|
||||
|
||||
It("should start and stop watcher", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
watchCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
w, err := lsw.Start(ctx)
|
||||
w, err := lsw.Start(watchCtx)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
cancel()
|
||||
Eventually(w).Should(BeClosed())
|
||||
})
|
||||
|
||||
It("should return error if watcher is already started", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
_, err := lsw.Start(ctx)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = lsw.Start(ctx)
|
||||
|
|
@ -62,9 +61,6 @@ var _ = XDescribe("Watcher", func() {
|
|||
})
|
||||
|
||||
It("should detect new files", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
changes, err := lsw.Start(ctx)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
|
|
@ -75,9 +71,6 @@ var _ = XDescribe("Watcher", func() {
|
|||
})
|
||||
|
||||
It("should detect new subfolders", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
changes, err := lsw.Start(ctx)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
|
|
@ -87,9 +80,6 @@ var _ = XDescribe("Watcher", func() {
|
|||
})
|
||||
|
||||
It("should detect changes in subfolders recursively", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
subfolder := filepath.Join(tmpFolder, "subfolder1/subfolder2")
|
||||
Expect(os.MkdirAll(subfolder, 0755)).To(Succeed())
|
||||
|
||||
|
|
@ -103,8 +93,6 @@ var _ = XDescribe("Watcher", func() {
|
|||
})
|
||||
|
||||
It("should detect removed in files", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
changes, err := lsw.Start(ctx)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
|
|
@ -118,9 +106,6 @@ var _ = XDescribe("Watcher", func() {
|
|||
})
|
||||
|
||||
It("should detect file moves", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
filePath := filepath.Join(tmpFolder, "test.txt")
|
||||
Expect(os.WriteFile(filePath, []byte("test"), 0600)).To(Succeed())
|
||||
|
||||
|
|
@ -146,7 +131,7 @@ var _ = Describe("Watcher.Start", func() {
|
|||
Expect(err).ToNot(HaveOccurred())
|
||||
lsw := ls.(storage.Watcher)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
ctx, cancel := context.WithTimeout(GinkgoT().Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
_, err = lsw.Start(ctx)
|
||||
Expect(err).To(HaveOccurred())
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
//nolint:unused
|
||||
package storagetest
|
||||
|
||||
import (
|
||||
|
|
@ -16,6 +15,8 @@ import (
|
|||
"github.com/navidrome/navidrome/log"
|
||||
"github.com/navidrome/navidrome/model/metadata"
|
||||
"github.com/navidrome/navidrome/utils/random"
|
||||
"github.com/onsi/ginkgo/v2"
|
||||
"github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
// FakeStorage is a fake storage that provides a FakeFS.
|
||||
|
|
@ -127,17 +128,14 @@ func (ffs *FakeFS) ClearError(filePath string) {
|
|||
}
|
||||
|
||||
func (ffs *FakeFS) UpdateTags(filePath string, newTags map[string]any, when ...time.Time) {
|
||||
ginkgo.GinkgoHelper()
|
||||
f, ok := ffs.MapFS[filePath]
|
||||
if !ok {
|
||||
panic(fmt.Errorf("file %s not found", filePath))
|
||||
}
|
||||
gomega.Expect(ok).To(gomega.BeTrue(), "file %s not found", filePath)
|
||||
var tags map[string]any
|
||||
err := json.Unmarshal(f.Data, &tags)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
gomega.Expect(json.Unmarshal(f.Data, &tags)).To(gomega.Succeed())
|
||||
maps.Copy(tags, newTags)
|
||||
data, _ := json.Marshal(tags)
|
||||
data, err := json.Marshal(tags)
|
||||
gomega.Expect(err).ToNot(gomega.HaveOccurred())
|
||||
f.Data = data
|
||||
ffs.Touch(filePath, when...)
|
||||
}
|
||||
|
|
@ -211,7 +209,8 @@ func File(tags ...map[string]any) *fstest.MapFile {
|
|||
if _, ok := ts[fakeFileInfoMode]; !ok {
|
||||
ts[fakeFileInfoMode] = fs.ModePerm
|
||||
}
|
||||
data, _ := json.Marshal(ts)
|
||||
data, err := json.Marshal(ts)
|
||||
gomega.Expect(err).ToNot(gomega.HaveOccurred())
|
||||
if _, ok := ts[fakeFileInfoSize]; !ok {
|
||||
ts[fakeFileInfoSize] = int64(len(data))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
//nolint:unused
|
||||
package storagetest_test
|
||||
|
||||
import (
|
||||
|
|
|
|||
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