Compare commits

..

47 commits

Author SHA1 Message Date
Deluan
5279c54468 ci: skip the review attestation check on draft PRs
A draft PR is not ready for review, so the personal review box is not
expected to be checked yet. The reminder comment and label on drafts were
noise for authors and gave maintainers no useful signal. The workflow now
returns early for drafts and also runs on ready_for_review, so the check
happens when the author marks the PR ready. CONTRIBUTING.md now says the
label applies to non-draft PRs.

Signed-off-by: Deluan <deluan@navidrome.org>
2026-11-21 11:06:03 -05:00
Deluan
afaabcba92 fix(jukebox): load queued tracks with the requesting user's context
jukeboxControl add and set loaded tracks with the context the playback
service started with, which has no user. Tracks from libraries the user
has no access to could then be added to the queue.

Tracks are now loaded with the request context, and set loads them
before it clears the queue, so an unknown id leaves the queue as it was.
The queue is shared by all jukebox users, so the loading user's stars,
rating, play count and bookmark are dropped from queued tracks.

Signed-off-by: Deluan <deluan@navidrome.org>
2026-11-20 13:51:57 -05:00
Deluan
a671ca1c82 ci: remind contributors to review their PRs before submitting
Add a workflow that checks whether an outside contributor confirmed
the personal review rule. When the "I personally read and reviewed
the entire diff" box is unchecked, the PR template is missing, or a
coding agent account opened the PR, it adds the
review-attestation-missing label and posts one reminder comment that
links to the rule. It removes the label once the box is checked.
Maintainers, Dependabot and github-actions are skipped. It runs on
pull_request_target and reads only PR metadata, so fork code never
runs with the write token.

The PR template now shows the review rule at the top and tells AI
agents never to check the attestation boxes for the human.
CONTRIBUTING.md says unreviewed AI output may be closed without review
and documents the label and comment.

Signed-off-by: Deluan <deluan@navidrome.org>
2026-11-20 11:06:50 -05:00
Deluan Quintão
55ffc04e2e
fix(transcoding): use a sample rate the MP3 and AAC encoders accept (#6518) 2026-11-20 10:55:29 -05:00
Deluan Quintão
a143ecb5c1
fix(server): bound JSON request bodies on queue, quick connect and admin routes (#6506) 2026-11-20 09:20:58 -05:00
Nikita Sobakin
ced5acbb3b
feat(plugins): pass requesting username to similar-songs requests (#6514) 2026-11-20 00:22:50 -05:00
Deluan Quintão
8eb2131e7b
refactor(plugins): share one userAccess and libraryAccess for plugin access checks (#6515) 2026-11-19 23:06:39 -05:00
Alanna
bc8e5df565
chore(deps): bump navidrome-music-player to 4.25.6 (#6510)
Includes navidrome/react-music-player#9, which ignores Media Session
play/pause actions that match the current playback state.


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

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

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

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

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

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

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

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

Fixes #6497

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

Components called httpClient directly for the Last.fm and ListenBrainz
links, plugin rescan, image upload and delete, playlist tracks and M3U
export. Those calls are now named wrapperDataProvider methods used through
useDataProvider(), next to the existing custom ones. The
getTranscodeDecision call moved into src/subsonic with the other Subsonic
calls, and src/transcode/fetchDecision.js is gone. URLs, methods, headers
and bodies are unchanged.

A no-restricted-imports rule now rejects httpClient imports outside
src/dataProvider and src/subsonic, and its message names where the call
should go.

* refactor(ui): share the JSON response wrapper in dataProvider custom methods

Extract a fetchData helper for the repeated httpClient(...).then(({ json }) => ({ data: json }))
in wrapperDataProvider custom methods, including the ones that predate this branch. URLs,
methods, headers and bodies are unchanged.

* fix(ui): keep moved dataProvider calls out of the optimistic queue

While an undoable mutation is pending (removing playlist tracks, saving a
playlist edit), react-admin's useDataProvider queues every call and resolves
it with no result. On a 401 it also resolves with nothing instead of
rejecting. The calls moved off httpClient in this branch went through that
proxy, so Export M3U failed, the duplicate check in Add to playlist showed an
error, and image upload could report success after a failure.

Add useDirectDataProvider, which returns the raw dataProvider from
DataProviderContext, and use it for those calls. They now behave as they did
when they called httpClient directly.
2026-11-16 00:06:25 -05:00
Deluan Quintão
a4be9224db
fix(listenbrainz): register the builtin even when it is disabled (#6479) 2026-11-15 19:52:20 -05:00
Deluan Quintão
a8872b413b
ci: fail PRs that add new //nolint directives (#6481) 2026-11-15 19:23:25 -05:00
Deluan Quintão
2e7e24a023
chore(lint): ban panic (#6478)
* chore(lint): ban panic in production code

Add a forbidigo rule that rejects panic outside tests and test helpers
(_test.go, tests/ and storagetest/). Its message says to return an error,
and to use log.Fatal only for startup failures.

The existing production panics are gone:
- model.MustParseArtworkID was only used by core/artwork tests. It is now a
  Gomega helper in those test suites, and it also panicked with the parsed
  ID instead of the error.
- isDBInitialized in db/migrations panicked on a query error and never
  closed its rows. It now uses QueryRowContext and logs the error.

The two http.ErrAbortHandler panics in the stream and API v1 handlers stay,
because net/http requires them to abort a response. They are marked with
//nolint:forbidigo. cmd/wire_injectors.go is not linted, because of its
wireinject build tag.

* chore(lint): ban panic in tests too

The panic ban excluded test files and test helpers, so agents could read it as permission to panic in tests. The rule now applies everywhere, and its message says what to use instead: return an error, or Expect(...)/Fail(...) in tests.

Test panics are replaced with Gomega assertions, and the helpers that assert call GinkgoHelper() so failures point at the calling spec. The fake HTTP clients in the deezer tests and getDirEntry use Fail(...). storagetest.FakeFS.UpdateTags now asserts with Gomega instead of panicking.

Seven test panics stay, marked //nolint:forbidigo: they exercise panic recovery or stand in for log.Fatal.

* refactor(tests): share panicking test helpers

Move mustParseArtworkID out of the two core/artwork suites into tests.MustParseArtworkID, and add conf.PanicOnLogFatal so the conf specs share one panicking logFatal stub and one //nolint. The MustPath spec now asserts the fatal message instead of capturing it. Also merge the back-to-back user and artist loops in the persistence suite setup.
2026-11-15 19:07:43 -05:00
Deluan Quintão
3679b6215d
refactor(agents): remove typed-nil workarounds from Last.fm and ListenBrainz (#6476) 2026-11-15 17:40:12 -05:00
Deluan Quintão
a6f3b91f87
chore(lint): add depguard walls between API packages and persistence (#6475)
* refactor: move ShareURL to core/publicurl

The Subsonic sharing endpoint imported the server/public router package only
to build share page URLs. ShareURL now lives in core/publicurl next to
ImageURL and PublicURL, so the two API packages no longer depend on each
other. The generated URLs are unchanged.

* chore(lint): add depguard walls between API packages and persistence

Enable depguard with two kinds of rules for production code:

- subsonic, nativeapi, jellyfin, apiv1 and public must not import each
  other. Shared code belongs in a neutral package.
- persistence must not import core, server, scanner, plugins, adapters or
  cmd.

Each rule's message names the fix. Test files are excluded because the
end-to-end suites wire several layers together on purpose. A model rule
was left out because the Go compiler already rejects those imports as
cycles.
2026-11-15 17:23:51 -05:00
Deluan Quintão
dfe90ba384
chore(lint): ban context.Background in tests, flag unused nolints (#6474)
* chore(lint): ban context.Background in tests, flag unused nolints

Add a forbidigo rule that rejects context.Background and context.TODO in
_test.go files. The lint message points to the right fix: the spec's ctx
from GinkgoT().Context(), or t.Context() and b.Context() in plain tests and
benchmarks. AGENTS.md already asks for this, but nothing enforced it, so
new tests kept adding Background calls. All 465 existing calls are
replaced, with one ctx per top-level Describe set at the top of its
BeforeEach. The migration forbidigo rules keep their old scope through an
exclusion matched on their message text.

Also enable nolintlint with require-specific and allow-unused: false.
It found 41 //nolint directives that suppressed nothing, or named no
linter, or had a leading space that made them inert. They are removed or
fixed. The sweep also fixed a middleware test that wrote a user with a nil
ctx before ctx was set.

* test: keep cleanup ROLLBACKs and the scanner singleton off the spec ctx

The ROLLBACK cleanups in the library, plugin and initial setup tests must
run even if the spec context is already cancelled, so they use
context.WithoutCancel. The same goes for the context handed to the
process-wide scanner singleton in the GetInstance test. Also document that
the forbidigo exclusions are scoped by message text.

* test: pass the caller's ctx to tests.ClearDB

ClearDB was the last context.Background call in shared test code. It now
takes a ctx, and every caller passes its spec ctx. The forbidigo rule for
tests also covers the tests/ helper package now, so new helpers there
cannot add Background calls either.
2026-11-15 17:03:17 -05:00
Jonas
69377527bc
fix(server): keep player IP when RemoteAddr has no port (#6464) 2026-11-15 15:25:17 -05:00
duongynhi000005-oss
97df50888e
fix(jellyfin): avoid stalling playback info on slow lyrics plugins (#6423) (#6435) 2026-11-15 15:05:14 -05:00
SwastikTripathi
84af2760ce
fix(ui): show 1 MB instead of 1024 KB in formatBytes (#6469)
* fix(ui): show 1 MB instead of 1024 KB in formatBytes

* refactor(ui): compute the scaled size once in formatBytes

Move the repeated scaling expression into a small helper, so the unit
bump only changes the index and the value is derived from it. The output
is unchanged for every input. The GB test case now uses 1024^3 - 1
instead of an arbitrary offset.

---------

Co-authored-by: Deluan <deluan@navidrome.org>
2026-11-15 14:10:53 -05:00
Surfoo
01e4ef3e3b
fix(ui): update french translations. (#6350)
* fix(ui): update french translations.

* Add Date Format setting for the french translation

* Apply batched suggestions from code review

Co-authored-by: Nelyah <Nelyah@users.noreply.github.com>

---------

Co-authored-by: Nelyah <Nelyah@users.noreply.github.com>
2026-11-15 12:21:46 -05:00
Deluan Quintão
690a234388
fix(lyrics): cache plugin lyrics lookups for all APIs (#6465) 2026-11-15 01:22:14 -05:00
Timo
a21d5b020a
feat(lastfm): added config for minimum scrobble duration (#5992) 2026-11-14 18:05:13 -05:00
Deluan Quintão
7bea40a25f
perf(scanner): use the title index for the cross-library move lookup (#6463) 2026-11-14 17:26:26 -05:00
Junker der Provinz
2ce7ef53ca
test(scanner): run multi-library and selective scan specs on Windows (#5381) (#6307)
* test(scanner): run multi-library and selective scan specs on Windows

Both suites put their DB in Ginkgo's TempDir, but the shared db.Db() pool stays open until TestScanner returns, so on Windows the TempDir cleanup failed with a sharing violation. Use the same os.MkdirTemp plus best-effort RemoveAll setup as scanner_test.go and drop the skips.

Signed-off-by: junkerderprovinz <jdp@braethoria.com>

* test(scanner): say why the DB may stay open in the temp dir

Signed-off-by: junkerderprovinz <jdp@braethoria.com>

---------

Signed-off-by: junkerderprovinz <jdp@braethoria.com>
Co-authored-by: junkerderprovinz <jdp@braethoria.com>
Co-authored-by: Deluan Quintão <deluan@navidrome.org>
2026-11-13 22:58:10 -05:00
Kris Anderson
88adc02f74
fix(ui): skip the login form when already signed in (#6459)
* fix(ui): skip the login form when already signed in

Opening #/login while signed in always showed the login form, so a
bookmarked or browser-autocompleted login URL asked for the password on
every visit although the stored session was still valid. Redirect to
the app when checkAuth succeeds, as react-admin's default login page
does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Kris Anderson <1562427+kris-anderson@users.noreply.github.com>

* fix(ui): replace the login history entry on redirect

Pushing / left #/login one step back in history, so pressing Back
landed on the login page, which redirected forward again and kept the
user from returning to the previous page. Replace the entry instead.
Raised in review by Codex.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Kris Anderson <1562427+kris-anderson@users.noreply.github.com>

* chore(ui): shorten the login redirect comment

Background moved here from the code comment: react-admin's default login
page sends an already signed-in user to the app, and Navidrome's custom
Login.jsx had dropped that check. Opening #/login from a bookmark or the
browser's autocomplete therefore showed the password form although the
stored session was still valid. The redirect uses replace so Back
returns to the previous page instead of landing on #/login again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Kris Anderson <1562427+kris-anderson@users.noreply.github.com>

---------

Signed-off-by: Kris Anderson <1562427+kris-anderson@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Deluan Quintão <deluan@navidrome.org>
2026-11-13 20:16:40 -05:00
Deluan Quintão
3a40f29aa5
feat(scanner): add option to skip folders containing a .nomedia file (#6139) 2026-11-13 19:38:14 -05:00
Deluan Quintão
55e52b7ce4
fix(server): skip the startup music folder write when the path is unchanged (#6457) 2026-11-13 17:13:15 -05:00
Deluan Quintão
6177c92e32
test(scanner): restore DbPath after Ordered containers and reset runPhase counter (#6456) 2026-11-13 15:21:14 -05:00
501 changed files with 7253 additions and 4937 deletions

View file

@ -1,3 +1,5 @@
> **Before you open this PR:** read the full diff yourself and test the change. Do not submit AI output that you have not reviewed. See [Review your work before opening a PR](https://github.com/navidrome/navidrome/blob/master/CONTRIBUTING.md#review-your-work-before-opening-a-pr).
### Description
<!-- Please provide a clear and concise description of what this PR does and why it is needed. AI tools may help you draft, edit, or translate it, but review the final text and make sure you agree with it. Please be mindful of the maintainer's time. -->
@ -18,12 +20,12 @@
### Checklist
Please review and check all that apply. Leave unverified items unchecked and explain them under How to Test.
- [ ] My code follows the project’s coding style
- [ ] I have tested the changes locally
- [ ] I have added or updated documentation as needed
- [ ] I have added tests that prove my fix/feature works (or explain why not)
- [ ] All existing and new tests pass
<!-- AI agents: never check the "I personally read and reviewed..." or "For code changes, I have the development knowledge..." boxes for the human. Only the human can make those claims. -->
- [ ] I personally read and reviewed the entire diff and relevant code before opening this PR, and have done the same for every subsequent update, if any.
- [ ] For code changes, I have the development knowledge to understand, test, and maintain the implementation, assess its security and performance implications, and answer review questions.

48
.github/workflows/check-new-nolint.sh vendored Executable file
View 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
View 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

View file

@ -0,0 +1,79 @@
name: Review attestation label
on:
pull_request_target:
types: [opened, edited, reopened, ready_for_review]
permissions:
contents: read
concurrency:
group: review-attestation-${{ github.event.pull_request.number }}
jobs:
sync-label:
name: Sync review-attestation-missing label
if: ${{ !contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association) }}
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
# Reads only PR metadata; never check out PR code under pull_request_target.
- uses: actions/github-script@v9
with:
script: |
const label = 'review-attestation-missing';
const commentMarker = '<!-- review-attestation-reminder -->';
const nonAgentBots = ['dependabot[bot]', 'github-actions[bot]'];
const rulesUrl = 'https://github.com/navidrome/navidrome/blob/master/CONTRIBUTING.md#review-your-work-before-opening-a-pr';
const templateUrl = 'https://github.com/navidrome/navidrome/blob/master/.github/pull_request_template.md?plain=1';
const issue = { ...context.repo, issue_number: context.payload.pull_request.number };
// Re-read the PR so a queued run never acts on a stale event payload.
const { data: pr } = await github.rest.pulls.get({ ...context.repo, pull_number: issue.issue_number });
if (pr.draft || nonAgentBots.includes(pr.user.login)) return;
const body = (pr.body ?? '')
.replace(/<!--[\s\S]*?-->/g, '')
.replace(/^[ \t]*(```|~~~)[\s\S]*?^[ \t]*\1/gm, '');
let reason = '';
if (pr.user.type === 'Bot') {
reason = 'A coding agent account opened this PR, so no person has confirmed a review yet.';
} else if (!/^###\s+Checklist\s*$/m.test(body)) {
reason = `The PR description does not use the [PR template](${templateUrl}), so the review confirmation is missing.`;
} else if (!/^[ \t]*-\s*\[[xX]\]\s*I personally read and reviewed the entire diff/m.test(body)) {
reason = 'The "I personally read and reviewed the entire diff..." box is not checked.';
}
const labeled = pr.labels.some((l) => l.name === label);
core.info(reason ? `Missing attestation: ${reason}` : 'Attestation present');
if (!reason) {
if (labeled) {
try {
await github.rest.issues.removeLabel({ ...issue, name: label });
} catch (e) {
if (e.status !== 404) throw e;
}
}
return;
}
if (!labeled) {
await github.rest.issues.addLabels({ ...issue, labels: [label] });
}
const comments = await github.paginate(github.rest.issues.listComments, { ...issue, per_page: 100 });
if (comments.some((c) => c.user?.login === 'github-actions[bot]' && c.body?.includes(commentMarker))) return;
await github.rest.issues.createComment({
...issue,
body: [
commentMarker,
'Thanks for the PR. Before it can be reviewed, please follow the [review rule](' + rulesUrl + '):',
'',
'- Read and review the entire diff and the relevant code yourself.',
'- Test the affected behavior yourself.',
'',
"An AI agent's summary or review does not count. If an agent wrote this code, review it as if someone else wrote it.",
'',
`**Why you see this:** ${reason}`,
'',
'When you are done, edit the PR description and check the "I personally read and reviewed the entire diff..." box. The `' + label + '` label then goes away. A PR that looks like unreviewed AI output may be closed without review.',
].join('\n'),
});

View file

@ -11,26 +11,142 @@ linters:
- bodyclose
- containedctx
- copyloopvar
- depguard
- dogsled
- durationcheck
- errchkjson
- errorlint
- exhaustive
- forbidigo
- ginkgolinter
- gocritic
- gocyclo
- godoclint
- goprintffuncname
- gosec
- misspell
- modernize
- nakedret
- nilerr
- nolintlint
- perfsprint
- rowserrcheck
- unconvert
- whitespace
disable:
- staticcheck
- thelper
- unconvert
- usestdlibvars
- 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
godoclint:
# a doc comment that names another symbol (left behind by a move or a paste) is a bug
default: none
enable:
- start-with-name
options:
start-with-name:
include-unexported: true
gocritic:
disable-all: true
enabled-checks:
@ -41,6 +157,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 +168,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 +200,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

View file

@ -24,7 +24,7 @@ For large or cross-cutting changes, agree on the design and a sequence of small,
## Review your work before opening a PR
Before opening any pull request, including a draft, you must personally read and review the entire diff and the relevant surrounding code, understand the implementation, and verify the affected behavior. This applies when an AI agent writes the code or creates the PR for you. An agent's summary or review does not satisfy this requirement. Personally review each subsequent update and verify its effects before pushing it or asking an agent to push it.
Before opening any pull request, including a draft, you must personally read and review the entire diff and the relevant surrounding code, understand the implementation, and verify the affected behavior. This applies when an AI agent writes the code or creates the PR for you. An agent's summary or review does not satisfy this requirement. Personally review each subsequent update and verify its effects before pushing it or asking an agent to push it. A PR that looks like unreviewed AI output may be closed without review.
Check the assumptions behind the change. Explain the implementation and important tradeoffs in your own words. For code changes, personally test the affected functionality, add regression tests where practical, and report the commands run and results actually observed. Identify failures, untested cases, and limitations. If an automated test is impractical, explain why and provide manual verification steps.
@ -38,6 +38,8 @@ AI-assisted work must meet the personal full-diff review and functional testing
Declare whether AI was used to generate or modify submitted code or tests, draft substantive PR text, or create the PR. A simple Yes or No in the PR description is enough. Tool names, prompts, and transcripts are not required.
An AI agent must never check the personal review or development knowledge boxes in the PR template for you. A non-draft PR from an outside contributor gets the `review-attestation-missing` label and a reminder comment when the personal review box is unchecked, the PR template is missing, or a coding agent account opened the PR.
AI tools may help you draft, edit, or translate PR explanations and review replies. Review the final text before you send it, make sure you agree with it, and take responsibility for it. Do not send AI-generated text that you have not reviewed to maintainers or other contributors. Please be mindful of the maintainer's time.
## Keep the result maintainable

View file

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

View file

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

View file

@ -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() {
@ -30,32 +30,32 @@ var _ = Describe("JWT Authentication", func() {
It("successfully fetches and caches a JWT token", func() {
testJWT := createTestJWT(5 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
})
token, err := client.getJWT(ctx)
Expect(err).To(BeNil())
Expect(err).ToNot(HaveOccurred())
Expect(token).To(Equal(testJWT))
})
It("returns the cached token on subsequent calls", func() {
testJWT := createTestJWT(5 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
})
// 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,17 +65,17 @@ 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,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))),
})
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
@ -90,7 +90,7 @@ var _ = Describe("JWT Authentication", func() {
// Create a token that expires in 30 seconds (less than 1-minute buffer)
testJWT := createTestJWT(30 * time.Second)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
})
@ -103,7 +103,7 @@ var _ = Describe("JWT Authentication", func() {
// Create a token that expired 1 minute ago
testJWT := createTestJWT(-1 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
})
@ -116,12 +116,12 @@ var _ = Describe("JWT Authentication", func() {
// Create a token that expires in 2 minutes (just over the 1-minute buffer)
testJWT := createTestJWT(2 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
})
token, err := client.getJWT(ctx)
Expect(err).To(BeNil())
Expect(err).ToNot(HaveOccurred())
Expect(token).ToNot(BeEmpty())
})
})
@ -129,7 +129,7 @@ var _ = Describe("JWT Authentication", func() {
Context("with invalid responses", func() {
It("handles HTTP error responses", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 500,
StatusCode: http.StatusInternalServerError,
Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)),
})
@ -140,7 +140,7 @@ var _ = Describe("JWT Authentication", func() {
It("handles malformed JSON responses", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{invalid json}`)),
})
@ -151,7 +151,7 @@ var _ = Describe("JWT Authentication", func() {
It("handles responses with empty JWT field", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"jwt":""}`)),
})
@ -162,7 +162,7 @@ var _ = Describe("JWT Authentication", func() {
It("handles invalid JWT tokens", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"jwt":"not-a-valid-jwt"}`)),
})
@ -176,17 +176,17 @@ 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,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))),
})
@ -201,12 +201,12 @@ var _ = Describe("JWT Authentication", func() {
// First token expires in 5 minutes
firstJWT := createTestJWT(5 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, firstJWT))),
})
token1, err := client.getJWT(ctx)
Expect(err).To(BeNil())
Expect(err).ToNot(HaveOccurred())
Expect(token1).To(Equal(firstJWT))
// Manually expire the cached token
@ -215,12 +215,12 @@ var _ = Describe("JWT Authentication", func() {
// Second token with different expiration (10 minutes)
secondJWT := createTestJWT(10 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, secondJWT))),
})
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)
}

View file

@ -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())
httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: 200})
Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: http.StatusOK})
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"))
@ -38,7 +38,7 @@ var _ = Describe("client", func() {
It("fails if artist was not found", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
})
@ -49,7 +49,7 @@ var _ = Describe("client", func() {
// Deezer answers 200 with no rate-limit headers when throttling, so this body is the only signal.
It("reports an exhausted quota as a retryable error, not as a missing artist", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(
`{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)),
})
@ -64,7 +64,7 @@ var _ = Describe("client", func() {
It("reports a non-quota body error as a plain error", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(
`{"error":{"type":"Exception","message":"Invalid query","code":100}}`)),
})
@ -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())
httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: 200})
Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: http.StatusOK})
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
@ -104,18 +104,18 @@ var _ = Describe("client", func() {
// Mock the JWT token endpoint with a valid JWT that expires in 5 minutes
testJWT := createTestJWT(5 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))),
})
})
It("returns artist bio from a successful request", func() {
f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json")
Expect(err).To(BeNil())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
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())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
_, 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())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
_, 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 "))
@ -163,7 +163,7 @@ var _ = Describe("client", func() {
]
}`
httpClient.mock("https://pipe.deezer.com/api", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(errorResponse)),
})
@ -185,7 +185,7 @@ var _ = Describe("client", func() {
}
}`
httpClient.mock("https://pipe.deezer.com/api", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(emptyBioResponse)),
})
@ -195,7 +195,7 @@ var _ = Describe("client", func() {
It("handles JWT token fetch failure", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 500,
StatusCode: http.StatusInternalServerError,
Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)),
})
@ -208,7 +208,7 @@ var _ = Describe("client", func() {
// Create a JWT that expires in 30 seconds (less than the 1-minute buffer)
expiredJWT := createTestJWT(30 * time.Second)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, expiredJWT))),
})
@ -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
}

View file

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

View file

@ -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]

View file

@ -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
}

View file

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

View file

@ -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.

View file

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

View file

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

View file

@ -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
}

View file

@ -57,7 +57,7 @@ var _ = Describe("auth_router", func() {
stubGetSessionOK := func(sessionKey string) {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"session":{"name":"Navidrome","key":"` + sessionKey + `","subscriber":0}}`)),
StatusCode: 200,
StatusCode: http.StatusOK,
}
}
@ -74,7 +74,7 @@ var _ = Describe("auth_router", func() {
var body map[string]any
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())

View file

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

View file

@ -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)
})
@ -28,19 +30,19 @@ var _ = Describe("client", func() {
Describe("albumGetInfo", func() {
It("returns an album on successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
album, err := client.albumGetInfo(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"))
})
It("does not double-encode plus signs", func() {
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := client.albumGetInfo(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"))
})
@ -49,19 +51,19 @@ var _ = Describe("client", func() {
Describe("artistGetInfo", func() {
It("returns an artist for a successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
artist, err := client.artistGetInfo(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"))
})
It("double-encodes plus signs in the artist name", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := client.artistGetInfo(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"))
})
@ -69,47 +71,47 @@ var _ = Describe("client", func() {
It("fails if Last.fm returns an http status != 200", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Internal Server Error`)),
StatusCode: 500,
StatusCode: http.StatusInternalServerError,
}
_, err := client.artistGetInfo(context.Background(), "U2", "pt")
_, err := client.artistGetInfo(ctx, "U2", "pt")
Expect(err).To(MatchError("last.fm http status: (500)"))
})
It("fails if Last.fm returns an http status != 200", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":3,"message":"Invalid Method - No method with that name in this package"}`)),
StatusCode: 400,
StatusCode: http.StatusBadRequest,
}
_, err := client.artistGetInfo(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"}))
})
It("fails if Last.fm returns an error", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":6,"message":"The artist you supplied could not be found"}`)),
StatusCode: 200,
StatusCode: http.StatusOK,
}
_, 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"))
})
It("fails if returned body is not a valid JSON", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`<xml>NOT_VALID_JSON</xml>`)),
StatusCode: 200,
StatusCode: http.StatusOK,
}
_, err := client.artistGetInfo(context.Background(), "U2", "pt")
_, err := client.artistGetInfo(ctx, "U2", "pt")
Expect(err).To(MatchError("invalid character '<' looking for beginning of value"))
})
@ -118,19 +120,19 @@ var _ = Describe("client", func() {
Describe("artistGetSimilar", func() {
It("returns an artist for a successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
similar, err := client.artistGetSimilar(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"))
})
It("double-encodes plus signs in the artist name", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := client.artistGetSimilar(context.Background(), "+44", 2)
_, err := client.artistGetSimilar(ctx, "+44", 2)
Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("%2B44"))
})
@ -139,19 +141,19 @@ var _ = Describe("client", func() {
Describe("artistGetTopTracks", func() {
It("returns top tracks for a successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
top, err := client.artistGetTopTracks(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"))
})
It("double-encodes plus signs in the artist name", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := client.artistGetTopTracks(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"))
})
@ -160,11 +162,11 @@ var _ = Describe("client", func() {
Describe("trackGetSimilar", func() {
It("returns similar tracks for a successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
similar, err := client.trackGetSimilar(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))
@ -173,9 +175,9 @@ var _ = Describe("client", func() {
It("double-encodes plus signs in the track and artist names", func() {
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := client.trackGetSimilar(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"))
@ -184,10 +186,10 @@ var _ = Describe("client", func() {
It("returns empty list when no similar tracks found", func() {
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
similar, err := client.trackGetSimilar(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())
})
})
@ -196,10 +198,10 @@ var _ = Describe("client", func() {
It("returns a token when the request is successful", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"token":"TOKEN"}`)),
StatusCode: 200,
StatusCode: http.StatusOK,
}
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"))
@ -212,10 +214,10 @@ var _ = Describe("client", func() {
It("returns a session key when the request is successful", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"session":{"name":"Navidrome","key":"SESSION_KEY","subscriber":0}}`)),
StatusCode: 200,
StatusCode: http.StatusOK,
}
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"))
@ -229,7 +231,7 @@ var _ = Describe("client", func() {
It("sends parameters in request body for POST", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"scrobbles":{"scrobble":{"ignoredMessage":{"code":"0"}},"@attr":{"accepted":1}}}`)),
StatusCode: 200,
StatusCode: http.StatusOK,
}
info := ScrobbleInfo{
@ -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))
@ -263,7 +265,7 @@ var _ = Describe("client", func() {
It("sends parameters in request body for POST", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"nowplaying":{"ignoredMessage":{"code":"0"}}}`)),
StatusCode: 200,
StatusCode: http.StatusOK,
}
info := ScrobbleInfo{
@ -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))

View file

@ -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"))

View file

@ -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 (

View file

@ -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"},
},
},
}
@ -80,7 +82,7 @@ var _ = Describe("listenBrainzAgent", func() {
Describe("NowPlaying", func() {
It("updates NowPlaying successfully", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: http.StatusOK}
err := agent.NowPlaying(ctx, "user-1", track, 0)
Expect(err).ToNot(HaveOccurred())
@ -100,14 +102,14 @@ var _ = Describe("listenBrainzAgent", func() {
})
It("sends a Scrobble successfully", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: http.StatusOK}
err := agent.Scrobble(ctx, "user-1", sc)
Expect(err).ToNot(HaveOccurred())
})
It("sets the Timestamp properly", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: http.StatusOK}
err := agent.Scrobble(ctx, "user-1", sc)
Expect(err).ToNot(HaveOccurred())
@ -128,7 +130,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns ErrRetryLater on error 503", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 503, "error": "Cannot submit listens to queue, please try again later."}`)),
StatusCode: 503,
StatusCode: http.StatusServiceUnavailable,
}
err := agent.Scrobble(ctx, "user-1", sc)
@ -138,7 +140,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns ErrRetryLater on error 500", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 500, "error": "Something went wrong. Please try again."}`)),
StatusCode: 500,
StatusCode: http.StatusInternalServerError,
}
err := agent.Scrobble(ctx, "user-1", sc)
@ -148,7 +150,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns ErrRetryLater on http errors", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad Gateway`)),
StatusCode: 500,
StatusCode: http.StatusInternalServerError,
}
err := agent.Scrobble(ctx, "user-1", sc)
@ -158,7 +160,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns ErrUnrecoverable on other errors", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400, "error": "BadRequest: Invalid JSON document submitted."}`)),
StatusCode: 400,
StatusCode: http.StatusBadRequest,
}
err := agent.Scrobble(ctx, "user-1", sc)
@ -167,7 +169,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("keeps a 429 scrobble for retry and carries the delay", func() {
httpClient.Res = http.Response{
StatusCode: 429,
StatusCode: http.StatusTooManyRequests,
Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}},
Body: io.NopCloser(bytes.NewBufferString(`{"code":429,"error":"rate limited"}`)),
}
@ -191,7 +193,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns artist url when MBID present", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
Expect(agent.GetArtistURL(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")).To(Equal("http://projectmili.com/"))
Expect(httpClient.RequestCount).To(Equal(1))
Expect(httpClient.SavedRequest.URL.Query().Get("artist_mbids")).To(Equal("d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56"))
@ -199,7 +201,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns error when url not present", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973")
Expect(err).To(HaveOccurred())
Expect(httpClient.RequestCount).To(Equal(1))
@ -217,7 +219,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns error when ListenBrainz returns an error", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)),
StatusCode: 400,
StatusCode: http.StatusBadRequest,
}
_, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973")
Expect(err).To(HaveOccurred())
@ -247,7 +249,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns an error on listenbrainz error", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)),
StatusCode: 400,
StatusCode: http.StatusBadRequest,
}
_, err := agent.GetArtistTopSongs(ctx, "", "", "1", 1)
Expect(err).To(HaveOccurred())
@ -257,7 +259,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns all tracks when asked", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 2)
Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]agents.Song{
@ -284,7 +286,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns only one track when prompted", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]agents.Song{
@ -310,7 +312,7 @@ var _ = Describe("listenBrainzAgent", func() {
"release_mbid": "rel-1",
"length": 200000
}]`
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: 200}
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: http.StatusOK}
data, err := agent.GetArtistTopSongs(ctx, "", "", "mbid-drake", 1)
Expect(err).ToNot(HaveOccurred())
Expect(data).To(HaveLen(1))
@ -322,7 +324,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("leaves Artists nil when the top song carries no name or MBIDs", func() {
body := `[{"recording_name": "Anon", "recording_mbid": "rec-1", "artist_name": "", "artist_mbids": []}]`
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: 200}
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: http.StatusOK}
data, err := agent.GetArtistTopSongs(ctx, "", "", "x", 1)
Expect(err).ToNot(HaveOccurred())
Expect(data).To(HaveLen(1))
@ -354,7 +356,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns an error on listenbrainz error", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
StatusCode: 400,
StatusCode: http.StatusBadRequest,
}
_, err := agent.GetSimilarArtists(ctx, "", "", "1", 1)
Expect(err).To(HaveOccurred())
@ -364,7 +366,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns all data on call", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 2)
Expect(err).ToNot(HaveOccurred())
@ -378,7 +380,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns subset of data on call", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 1)
Expect(err).ToNot(HaveOccurred())
@ -414,7 +416,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns an error on listenbrainz error", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
StatusCode: 400,
StatusCode: http.StatusBadRequest,
}
_, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", "1", 1)
Expect(err).To(HaveOccurred())
@ -424,7 +426,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns all data on call", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 2)
Expect(err).ToNot(HaveOccurred())
@ -456,7 +458,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns subset of data on call", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 1)
Expect(err).ToNot(HaveOccurred())
@ -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{}))
})
})
})

View file

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

View file

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

View file

@ -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)
})
@ -46,12 +48,12 @@ var _ = Describe("client", func() {
BeforeEach(func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token valid.", "user_name": "ListenBrainzUser", "valid": true}`)),
StatusCode: 200,
StatusCode: http.StatusOK,
}
})
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"))
})
})
@ -72,7 +74,7 @@ var _ = Describe("client", func() {
BeforeEach(func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)),
StatusCode: 200,
StatusCode: http.StatusOK,
}
li = listenInfo{
TrackMetadata: trackMetadata{
@ -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"))
@ -129,9 +131,9 @@ var _ = Describe("client", func() {
It("handles a malformed request with status code", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)),
StatusCode: 400,
StatusCode: http.StatusBadRequest,
}
_, 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"))
@ -141,9 +143,9 @@ var _ = Describe("client", func() {
It("handles a malformed request without meaningful body", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(``)),
StatusCode: 501,
StatusCode: http.StatusNotImplemented,
}
_, 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"))
@ -152,8 +154,8 @@ 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")
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, 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"))
@ -162,8 +164,8 @@ 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")
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
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))
@ -178,9 +180,9 @@ var _ = Describe("client", func() {
It("handles a malformed request with status code", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)),
StatusCode: 400,
StatusCode: http.StatusBadRequest,
}
_, 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"))
@ -190,9 +192,9 @@ var _ = Describe("client", func() {
It("handles a malformed request without standard body", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(``)),
StatusCode: 500,
StatusCode: http.StatusInternalServerError,
}
_, 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"))
@ -201,8 +203,8 @@ 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)
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 5)
Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]trackInfo{
{
@ -231,8 +233,8 @@ 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)
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]trackInfo{
{
@ -267,9 +269,9 @@ var _ = Describe("client", func() {
It("handles a malformed request with status code", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
StatusCode: 400,
StatusCode: http.StatusBadRequest,
}
_, 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")))
@ -278,8 +280,8 @@ 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)
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
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)))
@ -292,8 +294,8 @@ 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)
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
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)))
@ -308,8 +310,8 @@ var _ = Describe("client", func() {
conf.Update(func(c *conf.Options) { c.ListenBrainz.ArtistAlgorithm = algorithm })
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
resp, err := client.getSimilarArtists(context.Background(), mbid, 2)
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
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)))
@ -337,9 +339,9 @@ var _ = Describe("client", func() {
It("handles a malformed request with status code", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
StatusCode: 400,
StatusCode: http.StatusBadRequest,
}
_, 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")))
@ -348,8 +350,8 @@ 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)
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
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)))
@ -376,8 +378,8 @@ 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)
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
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)))
@ -396,9 +398,9 @@ var _ = Describe("client", func() {
It("properly sorts by score and truncates duplicates", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings-real-out-of-order.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
// There are actually 5 items. The dedup should happen FIRST
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)))
@ -444,8 +446,8 @@ var _ = Describe("client", func() {
conf.Update(func(c *conf.Options) { c.ListenBrainz.TrackAlgorithm = algorithm })
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200}
resp, err := client.getSimilarRecordings(context.Background(), mbid, 1)
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
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)))
@ -466,11 +468,11 @@ var _ = Describe("client", func() {
Describe("rate limiting", func() {
It("returns RetryLaterError with the header delay on 429", func() {
httpClient.Res = http.Response{
StatusCode: 429,
StatusCode: http.StatusTooManyRequests,
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())
@ -479,10 +481,10 @@ var _ = Describe("client", func() {
It("returns RetryLaterError with zero delay when no header is present", func() {
httpClient.Res = http.Response{
StatusCode: 429,
StatusCode: http.StatusTooManyRequests,
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())
@ -491,11 +493,11 @@ var _ = Describe("client", func() {
DescribeTable("caps absurd header values at one hour",
func(header string) {
httpClient.Res = http.Response{
StatusCode: 429,
StatusCode: http.StatusTooManyRequests,
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))
},
@ -507,11 +509,11 @@ var _ = Describe("client", func() {
It("maps a body-level 429 sent with a non-429 status", func() {
httpClient.Res = http.Response{
StatusCode: 200,
StatusCode: http.StatusOK,
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())
@ -520,11 +522,11 @@ var _ = Describe("client", func() {
It("returns RetryLaterError on a 429 from makeGenericRequest", func() {
httpClient.Res = http.Response{
StatusCode: 429,
StatusCode: http.StatusTooManyRequests,
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())

View file

@ -8,7 +8,9 @@ import (
"io"
"os"
"slices"
"strconv"
"strings"
"time"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
@ -74,7 +76,7 @@ var artworkExplainCmd = &cobra.Command{
Short: "Explain why an item's artwork resolved the way it did",
Long: "Explain why an item's artwork resolved the way it did.\n\n" +
"The item can be given as a bare id, a full artwork id (e.g. al-<id>), or a <kind> <id> pair.\n" +
"<kind> is one of: " + kindPrefixes(artwork.ExplainKinds) + ".\n" +
"<kind> is one of: " + kindPrefixes(explainKinds) + ".\n" +
"A disc artwork id is the album id and the disc number, joined by a colon: <albumID>:2",
Args: cobra.RangeArgs(1, 2),
Run: func(cmd *cobra.Command, args []string) {
@ -262,7 +264,7 @@ func configState(rep statusReport) string {
func printQueueStats(w io.Writer, stats []model.ArtworkQueueStat, total int64, countHeader, indent string) {
fmt.Fprintf(w, "%sKIND\tPRIORITY\t%s\n", indent, countHeader)
for _, s := range stats {
fmt.Fprintf(w, "%s%s\t%s\t%d\n", indent, kindName(s.ItemKind), artwork.PriorityName(s.Priority), s.Count)
fmt.Fprintf(w, "%s%s\t%s\t%d\n", indent, kindName(s.ItemKind), priorityName(s.Priority), s.Count)
}
fmt.Fprintf(w, "%sTOTAL\t\t%d\n", indent, total)
}
@ -274,14 +276,37 @@ func kindName(prefix string) string {
return prefix
}
type artworkPriority struct {
name string
value int
}
// knownPriorities is the one listing behind both the name and the parse, so they cannot drift.
var knownPriorities = []artworkPriority{
{"bump", model.ArtworkPriorityBump},
{"scan", model.ArtworkPriorityScan},
{"recheck", model.ArtworkPriorityRecheck},
{"backfill", model.ArtworkPriorityBackfill},
}
// priorityName falls back to the number: a row written by a newer version still has to print.
func priorityName(p int) string {
for _, ap := range knownPriorities {
if ap.value == p {
return ap.name
}
}
return strconv.Itoa(p)
}
func priorityNames() string {
return strings.Join(slice.Map(artwork.KnownPriorities, func(ap artwork.Priority) string { return ap.Name }), ", ")
return strings.Join(slice.Map(knownPriorities, func(ap artworkPriority) string { return ap.name }), ", ")
}
func parseArtworkPriority(s string) (int, error) {
for _, ap := range artwork.KnownPriorities {
if ap.Name == s {
return ap.Value, nil
for _, ap := range knownPriorities {
if ap.name == s {
return ap.value, nil
}
}
return 0, fmt.Errorf("invalid priority %q, expected one of: %s", s, priorityNames())
@ -317,7 +342,7 @@ func selectedKinds(kinds, sources []string, all bool) ([]model.Kind, error) {
return artwork.ReprocessKinds, nil
}
if len(kinds) == 0 {
return nil, fmt.Errorf("no selector given: pass --kind, --source or --all")
return nil, errors.New("no selector given: pass --kind, --source or --all")
}
return parseAll(kinds, func(s string) (model.Kind, error) {
return parseArtworkKind(s, artwork.ReprocessKinds)
@ -403,7 +428,7 @@ func promptConfirm(in io.Reader, verb string) confirmFunc {
return func(out io.Writer, total, external int64) bool {
var cost string
if external > 0 {
cost = fmt.Sprintf(" %s", externalLookupLine(external))
cost = " " + externalLookupLine(external)
}
fmt.Fprintf(out, "\nThis will %s %d items.%s Continue? [y/N] ", verb, total, cost)
var answer string
@ -534,7 +559,7 @@ func cancelSelection(kinds, priorities []string, all bool) ([]model.Kind, []int,
return nil, nil, nil
}
if len(kinds) == 0 && len(priorities) == 0 {
return nil, nil, fmt.Errorf("no selector given: pass --kind, --priority or --all")
return nil, nil, errors.New("no selector given: pass --kind, --priority or --all")
}
// RefreshableKinds, not ReprocessKinds: media files are queued, so --kind must reach them.
outKinds, err := parseAll(kinds, func(s string) (model.Kind, error) {
@ -653,6 +678,13 @@ func refreshItems(ctx context.Context, ds model.DataStore, targets []model.Artwo
return failed
}
// explainKinds is every kind explain accepts: it reports stored state and config too, so a kind
// with no chain to walk still has something to answer with.
var explainKinds = []model.Kind{
model.KindArtistArtwork, model.KindAlbumArtwork, model.KindDiscArtwork,
model.KindMediaFileArtwork, model.KindPlaylistArtwork, model.KindRadioArtwork,
}
func kindPrefixes(kinds []model.Kind) string {
return strings.Join(model.KindPrefixes(kinds), ", ")
}
@ -714,15 +746,106 @@ func artworkKindAndID(ctx context.Context, ds model.DataStore, arg string) (mode
return model.ArtworkID{Kind: kind, ID: arg}, nil
}
// cliUnavailableNote marks agents the CLI cannot construct; a running server loads them all.
const cliUnavailableNote = " (* not available to the CLI)"
// cliAgents words the CLI's own legend for the starred agents FormatAgents reports.
func cliAgents(rep artwork.ExplainReport) string {
if rep.AgentsIncomplete {
return rep.Agents + cliUnavailableNote
// explainAgents accounts for every configured agent: one the CLI cannot construct (a plugin, or a
// built-in missing its credentials) never reaches the Chain, so the raw list alone overstates it.
func explainAgents(configured string, available []string) string {
if strings.TrimSpace(configured) == "" {
return "(none)"
}
return rep.Agents
var unavailable bool
names := slice.Map(strings.Split(configured, ","), func(name string) string {
name = strings.TrimSpace(name)
if slices.Contains(available, name) {
return name
}
unavailable = true
return name + "*"
})
line := strings.Join(names, ", ")
if unavailable {
line += " (* not available to the CLI)"
}
return line
}
// availableImageAgents names the agents that can actually supply an image for kind.
func availableImageAgents(ds model.DataStore, mgr *plugins.Manager, kind model.Kind) []string {
ag := agents.GetAgents(ds, mgr)
if kind == model.KindArtistArtwork {
return slice.Map(ag.ArtistImageAgents(), func(a agents.ArtistImageAgent) string { return a.Name })
}
return slice.Map(ag.AlbumImageAgents(), func(a agents.AlbumImageAgent) string { return a.Name })
}
// explainResult states the verdict of the walk. A skipped or failed external tier, or a local
// candidate that would not open, leaves the outcome unknown: nothing observed that there is no artwork.
func explainResult(source string, steps []artwork.TraceStep) string {
if source != "" {
for _, s := range steps {
if s.Outcome == artwork.OutcomeHit {
break
}
// An external winner discards the earlier error, so the resolver settles it with no retry.
if s.Outcome == artwork.OutcomeError && strings.HasPrefix(s.Candidate, artwork.ExternalPrefix) &&
!strings.HasPrefix(source, artwork.ExternalPrefix) {
return "resolved from " + source +
" (indeterminate: a higher-priority external lookup failed; this may resolve differently on a retry)"
}
}
return "resolved from " + source
}
for _, s := range steps {
switch {
case s.Outcome == artwork.OutcomeError && strings.HasPrefix(s.Candidate, artwork.ExternalPrefix):
return "indeterminate (an external lookup failed; the item may resolve on a later attempt)"
// A stage error or an unreadable candidate means a source was found but not processed; the
// worker retries rather than settling absent, so neither reads as a clean miss.
case s.Outcome == artwork.OutcomeError, s.Outcome == artwork.OutcomeUnreadable:
return "indeterminate (a candidate was found but could not be processed; the worker retries rather than settling absent)"
}
}
return "not resolved"
}
// explainConfig names the setting that decides where a kind's artwork comes from, and its value.
func explainConfig(kind model.Kind) (name, value string) {
switch kind {
case model.KindArtistArtwork:
return "ArtistArtPriority", conf.Server().ArtistArtPriority
case model.KindAlbumArtwork:
return "CoverArtPriority", conf.Server().CoverArtPriority
case model.KindDiscArtwork:
return "DiscArtPriority", conf.Server().DiscArtPriority
case model.KindMediaFileArtwork:
return "EnableMediaFileCoverArt", strconv.FormatBool(conf.Server().EnableMediaFileCoverArt)
}
return "", ""
}
type explainReport struct {
kind model.Kind
id string
name string
stored *model.ItemArtwork
queued *model.ArtworkQueueItem
agents string
// steps is the chain walk: recorded when the item was resolved, or performed just now when walked.
steps []artwork.TraceStep
source string
walked bool
resolveErr error
}
// explainChainOrigin says whether the operator is reading history or a walk performed just now,
// since the two can disagree after a config change.
func explainChainOrigin(rep explainReport) string {
if rep.walked {
return "walked now"
}
if rep.stored != nil {
return "recorded " + formatTime(rep.stored.AttemptedAt)
}
return "not recorded"
}
// writeSteps prints the trace rows. An empty last cell would end tabwriter's column block and
@ -743,100 +866,107 @@ func writeStepTable(w io.Writer, title string, steps []artwork.TraceStep) {
writeSteps(w, " ", steps)
}
func formatExplain(rep artwork.ExplainReport) string {
func formatExplain(rep explainReport) string {
var sb strings.Builder
w := newTabWriter(&sb)
explainable := artwork.Explainable(rep.Kind)
stateful := artwork.KeepsState(rep.Kind)
unrecorded := !rep.Walked && rep.Stored == nil
explainable := artwork.Explainable(rep.kind)
stateful := artwork.KeepsState(rep.kind)
unrecorded := !rep.walked && rep.stored == nil
fmt.Fprintln(w, "Item")
fmt.Fprintf(w, " Kind:\t%s (%s)\n", rep.Kind, rep.Kind.Prefix())
fmt.Fprintf(w, " ID:\t%s\n", rep.ID)
fmt.Fprintf(w, " Name:\t%s\n", rep.Name)
fmt.Fprintf(w, " Kind:\t%s (%s)\n", rep.kind, rep.kind.Prefix())
fmt.Fprintf(w, " ID:\t%s\n", rep.id)
fmt.Fprintf(w, " Name:\t%s\n", rep.name)
fmt.Fprintln(w, "\nStored")
switch {
case !stateful:
fmt.Fprintf(w, " (%s artwork is resolved on every request and never recorded)\n", rep.Kind)
case rep.Stored == nil:
fmt.Fprintf(w, " (%s artwork is resolved on every request and never recorded)\n", rep.kind)
case rep.stored == nil:
fmt.Fprintln(w, " (no artwork state recorded)")
default:
fmt.Fprintf(w, " Source:\t%s\n", displaySource(rep.Stored.Source))
fmt.Fprintf(w, " Hash:\t%s\n", cmp.Or(rep.Stored.Hash, "(absent)"))
if rep.Stored.SourcePath != "" {
fmt.Fprintf(w, " Source path:\t%s\n", rep.Stored.SourcePath)
fmt.Fprintf(w, " Source:\t%s\n", displaySource(rep.stored.Source))
fmt.Fprintf(w, " Hash:\t%s\n", cmp.Or(rep.stored.Hash, "(absent)"))
if rep.stored.SourcePath != "" {
fmt.Fprintf(w, " Source path:\t%s\n", rep.stored.SourcePath)
}
fmt.Fprintf(w, " Attempted at:\t%s\n", artwork.FormatTime(rep.Stored.AttemptedAt))
fmt.Fprintf(w, " Attempted at:\t%s\n", formatTime(rep.stored.AttemptedAt))
}
fmt.Fprintln(w, "\nQueue")
switch {
case !stateful:
fmt.Fprintln(w, " (never queued)")
case rep.Queued == nil:
case rep.queued == nil:
fmt.Fprintln(w, " (not queued)")
default:
fmt.Fprintf(w, " Priority:\t%s (%d)\n", artwork.PriorityName(rep.Queued.Priority), rep.Queued.Priority)
fmt.Fprintf(w, " Attempts:\t%d\n", rep.Queued.Attempts)
fmt.Fprintf(w, " Retry at:\t%s\n", artwork.FormatTime(rep.Queued.RetryAt))
fmt.Fprintf(w, " Priority:\t%s (%d)\n", priorityName(rep.queued.Priority), rep.queued.Priority)
fmt.Fprintf(w, " Attempts:\t%d\n", rep.queued.Attempts)
fmt.Fprintf(w, " Retry at:\t%s\n", formatTime(rep.queued.RetryAt))
}
if rep.Queued != nil {
writeStepTable(w, "Last attempt failed", rep.LastAttemptFailed())
if rep.queued != nil {
writeStepTable(w, "Last attempt failed", artwork.DecodeTrace(rep.queued.Trace, ""))
}
if rep.Stored != nil {
writeStepTable(w, "Gave up after", rep.GaveUpAfter())
if rep.stored != nil {
writeStepTable(w, "Gave up after", artwork.DecodeTrace(rep.stored.LastFailure, ""))
}
fmt.Fprintln(w, "\nConfig")
if setting, value := artwork.ConfigFor(rep.Kind); setting == "" {
if setting, value := explainConfig(rep.kind); setting == "" {
fmt.Fprintln(w, " (no artwork source configuration applies)")
} else {
fmt.Fprintf(w, " %s:\t%s\n", setting, value)
if rep.Agents != "" {
fmt.Fprintf(w, " Agents:\t%s\n", cliAgents(rep))
if rep.agents != "" {
fmt.Fprintf(w, " Agents:\t%s\n", rep.agents)
}
}
fmt.Fprintf(w, "\nChain (%s)\n", rep.ChainOrigin())
fmt.Fprintf(w, "\nChain (%s)\n", explainChainOrigin(rep))
switch {
case !explainable:
fmt.Fprintf(w, " (%s artwork does not walk a priority chain)\n", rep.Kind)
fmt.Fprintf(w, " (%s artwork does not walk a priority chain)\n", rep.kind)
case unrecorded:
fmt.Fprintln(w, " (no resolution recorded yet; re-run with --live to walk the chain now)")
case !rep.Walked && len(rep.Steps) == 0 && rep.Stored.Hash != "":
case !rep.walked && len(rep.steps) == 0 && rep.stored.Hash != "":
// A stored image with no chain can only predate trace recording: a recorded resolution that
// found an image always records its winning candidate.
fmt.Fprintln(w, " (this item was resolved before traces were recorded; re-run with --live)")
case !rep.Walked && len(rep.Steps) == 0:
case !rep.walked && len(rep.steps) == 0:
// Absent with no chain: an empty priority list walked nothing, or a pre-tracing absent row.
fmt.Fprintln(w, " (no candidates were recorded; re-run with --live to walk the chain now)")
default:
fmt.Fprintln(w, " CANDIDATE\tOUTCOME\tDETAIL")
writeSteps(w, " ", rep.Steps)
writeSteps(w, " ", rep.steps)
}
fmt.Fprintln(w, "\nResult")
switch {
case rep.ResolveErr != nil:
fmt.Fprintf(w, " resolution failed: %s\n", rep.ResolveErr)
case rep.resolveErr != nil:
fmt.Fprintf(w, " resolution failed: %s\n", rep.resolveErr)
case !explainable:
fmt.Fprintln(w, " not evaluated (no chain was walked; see Stored above)")
case unrecorded:
fmt.Fprintln(w, " not evaluated (nothing recorded; re-run with --live to walk the chain now)")
default:
fmt.Fprintf(w, " %s\n", rep.Result())
fmt.Fprintf(w, " %s\n", explainResult(rep.source, rep.steps))
}
w.Flush()
return sb.String()
}
func formatTime(t time.Time) string {
if t.IsZero() {
return "-"
}
return t.Format(time.RFC3339)
}
func runExplain(ctx context.Context, args []string) {
defer db.Init(ctx)()
ds, ctx := getAdminContext(ctx)
targets, failures, err := resolveArtworkTargets(ctx, ds, args, artwork.ExplainKinds)
targets, failures, err := resolveArtworkTargets(ctx, ds, args, explainKinds)
if err != nil {
log.Fatal(ctx, err)
}
@ -848,29 +978,45 @@ func runExplain(ctx context.Context, args []string) {
}
kind, id := targets[0].Kind, targets[0].ID
var opts artwork.ExplainOptions
// Only artist and album reach an agent, and the load must precede the resolver, which reads the
// same manager. Leaving ag nil elsewhere avoids handing agents.GetAgents a not-yet-loaded manager.
var ag *agents.Agents
if kind == model.KindArtistArtwork || kind == model.KindAlbumArtwork {
mgr := loadPluginAgents(ctx, explainLive)
defer func() { _ = mgr.Stop() }()
ag = agents.GetAgents(ds, mgr)
name, err := artwork.ItemName(ctx, ds, kind, id)
if err != nil {
log.Fatal(ctx, "Item not found", "kind", kind, "id", id, err)
}
// Disc artwork keeps no row, so it has no stored trace and can only be explained by walking now.
if explainLive || !artwork.KeepsState(kind) {
opts.Walk = func(t *artwork.ChainTrace) *artwork.TracingResolver {
return CreateArtworkResolver(t, explainLive)
rep := explainReport{kind: kind, id: id, name: name}
if artwork.KeepsState(kind) {
rep.stored, err = ds.Artwork().GetItemArtwork(ctx, kind, id, model.ImageTypePrimary)
if err != nil && !errors.Is(err, model.ErrNotFound) {
log.Fatal(ctx, "Failed to read artwork state", "kind", kind, "id", id, err)
}
rep.queued, err = ds.ArtworkQueue().Get(ctx, kind, id, model.ImageTypePrimary)
if err != nil && !errors.Is(err, model.ErrNotFound) {
log.Fatal(ctx, "Failed to read the artwork queue", "kind", kind, "id", id, err)
}
}
rep, err := artwork.Explain(ctx, ds, ag, kind, id, opts)
if err != nil {
log.Fatal(ctx, "Failed to explain artwork", "kind", kind, "id", id, err)
}
// Disc artwork keeps no row, so it has no stored trace and can only be explained by walking now.
rep.walked = explainLive || !artwork.KeepsState(kind)
if artwork.Explainable(kind) {
// Only artist and album reach an agent, and the load must precede the resolver, which reads
// the same manager.
if kind == model.KindArtistArtwork || kind == model.KindAlbumArtwork {
mgr := loadPluginAgents(ctx, explainLive)
defer func() { _ = mgr.Stop() }()
rep.agents = explainAgents(conf.Server().Agents, availableImageAgents(ds, mgr, kind))
}
switch {
case rep.walked:
trace := &artwork.ChainTrace{}
rep.source, rep.resolveErr = CreateArtworkResolver(trace, explainLive).Resolve(ctx, kind, id)
rep.steps = trace.Steps()
case rep.stored != nil:
rep.steps = artwork.DecodeTrace(rep.stored.Trace, rep.stored.SourcePath)
rep.source = rep.stored.Source
}
}
fmt.Print(formatExplain(rep))
// The steps taken before a failed walk are the diagnosis, so report them before exiting.
if rep.ResolveErr != nil {
log.Fatal(ctx, "Failed to resolve artwork", "kind", kind, "id", id, rep.ResolveErr)
if rep.resolveErr != nil {
log.Fatal(ctx, "Failed to resolve artwork", "kind", kind, "id", id, rep.resolveErr)
}
}

View file

@ -40,8 +40,8 @@ var _ = Describe("parseArtworkKind", func() {
_, err := parseArtworkKind(prefix, valid)
Expect(err).ToNot(HaveOccurred())
},
Entry("explain reads disc artwork", "dc", artwork.ExplainKinds),
Entry("explain reads media file artwork", "mf", artwork.ExplainKinds),
Entry("explain reads disc artwork", "dc", explainKinds),
Entry("explain reads media file artwork", "mf", explainKinds),
// Disc artwork has no state to clear and the worker cannot resolve it, so refresh must not
// accept it: the queue row would be rejected on every drain.
Entry("refresh re-queues media files", "mf", artwork.RefreshableKinds),
@ -55,16 +55,17 @@ 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}
})
It("accepts the explicit <kind> <id> leader shared by every id", func() {
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"al", "x", "y"}, artwork.ExplainKinds)
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"al", "x", "y"}, explainKinds)
Expect(err).ToNot(HaveOccurred())
Expect(failures).To(BeEmpty())
Expect(targets).To(Equal([]model.ArtworkID{
@ -77,20 +78,20 @@ var _ = Describe("resolveArtworkTargets", func() {
})
It("resolves a bare id by looking it up across tables", func() {
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"artist1"}, artwork.ExplainKinds)
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"artist1"}, explainKinds)
Expect(err).ToNot(HaveOccurred())
Expect(failures).To(BeEmpty())
Expect(targets).To(Equal([]model.ArtworkID{{Kind: model.KindArtistArtwork, ID: "artist1"}}))
})
It("reads the kind from a full artwork id prefix without a database lookup", func() {
targets, _, err := resolveArtworkTargets(ctx, ds, []string{"al-realalbum"}, artwork.ExplainKinds)
targets, _, err := resolveArtworkTargets(ctx, ds, []string{"al-realalbum"}, explainKinds)
Expect(err).ToNot(HaveOccurred())
Expect(targets).To(Equal([]model.ArtworkID{{Kind: model.KindAlbumArtwork, ID: "realalbum"}}))
})
It("strips the hash suffix from a full artwork id", func() {
targets, _, err := resolveArtworkTargets(ctx, ds, []string{"al-realalbum_0123456789abcdef"}, artwork.ExplainKinds)
targets, _, err := resolveArtworkTargets(ctx, ds, []string{"al-realalbum_0123456789abcdef"}, explainKinds)
Expect(err).ToNot(HaveOccurred())
Expect(targets).To(Equal([]model.ArtworkID{{Kind: model.KindAlbumArtwork, ID: "realalbum"}}))
})
@ -104,7 +105,7 @@ var _ = Describe("resolveArtworkTargets", func() {
})
It("collects an id that matches nothing and has no kind prefix", func() {
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"nope"}, artwork.ExplainKinds)
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"nope"}, explainKinds)
Expect(err).ToNot(HaveOccurred())
Expect(targets).To(BeEmpty())
Expect(failures).To(HaveLen(1))
@ -112,7 +113,7 @@ var _ = Describe("resolveArtworkTargets", func() {
})
It("resolves the valid ids and collects the unresolvable ones", func() {
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"artist1", "nope", "al-realalbum"}, artwork.ExplainKinds)
targets, failures, err := resolveArtworkTargets(ctx, ds, []string{"artist1", "nope", "al-realalbum"}, explainKinds)
Expect(err).ToNot(HaveOccurred())
Expect(targets).To(Equal([]model.ArtworkID{
{Kind: model.KindArtistArtwork, ID: "artist1"}, {Kind: model.KindAlbumArtwork, ID: "realalbum"}}))
@ -121,35 +122,125 @@ var _ = Describe("resolveArtworkTargets", func() {
})
})
var _ = Describe("explainResult", func() {
It("reports the winning source", func() {
steps := []artwork.TraceStep{{Candidate: "folder", Outcome: "hit", Detail: "/music/a.jpg"}}
Expect(explainResult("folder", steps)).To(ContainSubstring("resolved from folder"))
})
It("reports not resolved when every candidate was tried and missed", func() {
steps := []artwork.TraceStep{
{Candidate: "artist.*", Outcome: "miss"},
{Candidate: "external:deezer", Outcome: "miss"},
}
Expect(explainResult("", steps)).To(Equal("not resolved"))
})
It("reports indeterminate when a local candidate exists but could not be read", func() {
steps := []artwork.TraceStep{
{Candidate: "cover.*", Outcome: "miss"},
{Candidate: "embedded", Outcome: "unreadable"},
}
Expect(explainResult("", steps)).To(ContainSubstring("indeterminate"),
"the worker retries an unreadable candidate instead of settling absent, so this is not a clean miss")
})
It("reports indeterminate when a processing stage errored after a candidate was found", func() {
steps := []artwork.TraceStep{
{Candidate: "cover.*", Outcome: "hit", Detail: "/music/cover.jpg"},
{Candidate: "store", Outcome: "error", Detail: "disk full"},
}
Expect(explainResult("", steps)).To(ContainSubstring("indeterminate"),
"a stage error is a processing failure the worker retries, not a definitive miss")
})
It("does not qualify a hit that an earlier unreadable candidate preceded", func() {
// chainState.try stamps only the external error onto a hit and drops the local one, so the
// worker settles this as found; warning about it would be a false alarm.
steps := []artwork.TraceStep{
{Candidate: "embedded", Outcome: "unreadable"},
{Candidate: "cover.*", Outcome: "hit", Detail: "/music/cover.jpg"},
}
Expect(explainResult("folder", steps)).To(Equal("resolved from folder"))
})
It("reports indeterminate when an external lookup failed transiently", func() {
steps := []artwork.TraceStep{
{Candidate: "artist.*", Outcome: "miss"},
{Candidate: "external:deezer", Outcome: "error", Detail: "context deadline exceeded"},
}
Expect(explainResult("", steps)).To(ContainSubstring("indeterminate"),
"a failed network call is not evidence that the item has no artwork")
})
It("qualifies a win a failed higher-priority external lookup could have taken", func() {
steps := []artwork.TraceStep{
{Candidate: "external:deezer", Outcome: "error", Detail: "context deadline exceeded"},
{Candidate: "artist.*", Outcome: "hit", Detail: "/music/artist.jpg"},
}
res := explainResult("artist.*", steps)
Expect(res).To(ContainSubstring("resolved from artist.*"))
Expect(res).To(ContainSubstring("indeterminate"),
"the resolver serves this hit but retries later, so the winner is provisional")
})
It("does not qualify an external win that followed a failed external lookup", func() {
steps := []artwork.TraceStep{
{Candidate: "external:deezer", Outcome: "error", Detail: "context deadline exceeded"},
{Candidate: "external:lastfm", Outcome: "hit", Detail: "http://img"},
}
Expect(explainResult("external:lastfm", steps)).To(Equal("resolved from external:lastfm"),
"a later agent supplying the image discards the earlier error, so there is no retry to warn about")
})
It("does not qualify a win that outranked the failed external lookup", func() {
steps := []artwork.TraceStep{
{Candidate: "artist.*", Outcome: "hit"},
{Candidate: "external:deezer", Outcome: "error", Detail: "context deadline exceeded"},
}
Expect(explainResult("artist.*", steps)).To(Equal("resolved from artist.*"))
})
})
var _ = Describe("explainAgents", func() {
It("accounts for every configured agent, marking the ones the CLI could not use", func() {
out := explainAgents("artist-nfo-metadata,apple-music,deezer,lastfm", []string{"deezer"})
for _, name := range []string{"artist-nfo-metadata", "apple-music", "deezer", "lastfm"} {
Expect(out).To(ContainSubstring(name),
"a configured agent missing from this line reads as if it had never been configured")
}
Expect(out).To(ContainSubstring("not available to the CLI"))
})
It("does not mark anything when every configured agent is available", func() {
out := explainAgents("deezer, lastfm", []string{"lastfm", "deezer"})
Expect(out).To(Equal("deezer, lastfm"))
})
It("reports an empty configuration as none, not as an unavailable agent", func() {
Expect(explainAgents("", nil)).To(Equal("(none)"))
})
})
var _ = Describe("formatExplain", func() {
var rep artwork.ExplainReport
var rep explainReport
BeforeEach(func() {
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external, artist.*" })
rep = artwork.ExplainReport{
Kind: model.KindArtistArtwork,
ID: "ar-1",
Name: "Radiohead",
Agents: "lastfm,spotify",
Walked: true,
Steps: []artwork.TraceStep{
rep = explainReport{
kind: model.KindArtistArtwork,
id: "ar-1",
name: "Radiohead",
agents: "lastfm,spotify",
walked: true,
steps: []artwork.TraceStep{
{Candidate: "upload", Outcome: "skipped", Detail: "no uploaded image"},
{Candidate: "external:deezer", Outcome: "error", Detail: "context deadline exceeded"},
},
Source: "",
source: "",
}
})
It("explains the star on an agent the CLI could not construct", func() {
rep.AgentsIncomplete = true
Expect(formatExplain(rep)).To(ContainSubstring("(* not available to the CLI)"))
})
It("leaves the agent line unadorned when every agent is available", func() {
Expect(formatExplain(rep)).ToNot(ContainSubstring("not available to the CLI"))
})
It("reports the item, its config and the chain it walked", func() {
out := formatExplain(rep)
Expect(out).To(ContainSubstring("Radiohead"))
@ -168,11 +259,11 @@ var _ = Describe("formatExplain", func() {
It("prints the stored state and the queue row when they exist", func() {
attempted := time.Date(2026, 8, 13, 10, 0, 0, 0, time.UTC)
rep.Stored = &model.ItemArtwork{Source: "folder", Hash: "abc123",
rep.stored = &model.ItemArtwork{Source: "folder", Hash: "abc123",
SourcePath: "/music/cover.jpg", AttemptedAt: attempted}
rep.Queued = &model.ArtworkQueueItem{Priority: model.ArtworkPriorityScan, Attempts: 2,
rep.queued = &model.ArtworkQueueItem{Priority: model.ArtworkPriorityScan, Attempts: 2,
RetryAt: attempted.Add(time.Hour)}
rep.Source = "folder"
rep.source = "folder"
out := formatExplain(rep)
Expect(out).To(ContainSubstring("abc123"))
@ -183,12 +274,12 @@ var _ = Describe("formatExplain", func() {
})
It("marks a known-absent stored state instead of printing an empty hash", func() {
rep.Stored = &model.ItemArtwork{AttemptedAt: time.Now()}
rep.stored = &model.ItemArtwork{AttemptedAt: time.Now()}
Expect(formatExplain(rep)).To(ContainSubstring("absent"))
})
It("reports a failed walk as failed, not as unresolved", func() {
rep.ResolveErr = errors.New("no such directory")
rep.resolveErr = errors.New("no such directory")
out := formatExplain(rep)
Expect(out).To(ContainSubstring("resolution failed: no such directory"))
@ -198,9 +289,9 @@ var _ = Describe("formatExplain", func() {
It("says a kind that does not walk a chain has no chain, without an empty table", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*, embedded" })
rep.Kind = model.KindPlaylistArtwork
rep.Steps = nil
rep.Agents = ""
rep.kind = model.KindPlaylistArtwork
rep.steps = nil
rep.agents = ""
out := formatExplain(rep)
Expect(out).To(ContainSubstring("does not walk a priority chain"))
@ -214,11 +305,11 @@ var _ = Describe("formatExplain", func() {
It("says disc artwork keeps no state instead of reporting it as unresolved state", func() {
conf.Update(func(c *conf.Options) { c.DiscArtPriority = "cover.jpg, embedded" })
rep = artwork.ExplainReport{
Kind: model.KindDiscArtwork, ID: "al-1:2", Name: "OK Computer (disc 2)",
Steps: []artwork.TraceStep{{Candidate: "cover.jpg", Outcome: "hit", Detail: "/music/cover.jpg"}},
Source: "folder",
Walked: true,
rep = explainReport{
kind: model.KindDiscArtwork, id: "al-1:2", name: "OK Computer (disc 2)",
steps: []artwork.TraceStep{{Candidate: "cover.jpg", Outcome: "hit", Detail: "/music/cover.jpg"}},
source: "folder",
walked: true,
}
out := formatExplain(rep)
@ -233,15 +324,15 @@ var _ = Describe("formatExplain", func() {
Context("stored traces", func() {
BeforeEach(func() {
rep.Walked = false
rep.Steps = nil
rep.walked = false
rep.steps = nil
})
It("labels a recorded chain with when it was recorded, not as a walk done now", func() {
attempted := time.Date(2026, 8, 13, 10, 0, 0, 0, time.UTC)
rep.Stored = &model.ItemArtwork{Source: "folder", Hash: "abc", AttemptedAt: attempted}
rep.Steps = []artwork.TraceStep{{Candidate: "artist.*", Outcome: "hit", Detail: "/music/artist.jpg"}}
rep.Source = "folder"
rep.stored = &model.ItemArtwork{Source: "folder", Hash: "abc", AttemptedAt: attempted}
rep.steps = []artwork.TraceStep{{Candidate: "artist.*", Outcome: "hit", Detail: "/music/artist.jpg"}}
rep.source = "folder"
out := formatExplain(rep)
Expect(out).To(ContainSubstring("Chain (recorded 2026-08-13T10:00:00Z)"))
@ -258,7 +349,7 @@ var _ = Describe("formatExplain", func() {
})
It("distinguishes a row written before traces existed from one with an empty chain", func() {
rep.Stored = &model.ItemArtwork{Source: "folder", Hash: "abc", AttemptedAt: time.Now()}
rep.stored = &model.ItemArtwork{Source: "folder", Hash: "abc", AttemptedAt: time.Now()}
Expect(formatExplain(rep)).To(ContainSubstring("resolved before traces were recorded"))
})
@ -266,7 +357,7 @@ var _ = Describe("formatExplain", func() {
It("does not call an absent row with an empty recorded chain a pre-tracing row", func() {
// An empty priority list records a real but empty chain and resolves absent; that is not a
// legacy row, so it must not be reported as resolved before tracing existed.
rep.Stored = &model.ItemArtwork{Source: "", Hash: "", AttemptedAt: time.Now()}
rep.stored = &model.ItemArtwork{Source: "", Hash: "", AttemptedAt: time.Now()}
out := formatExplain(rep)
Expect(out).ToNot(ContainSubstring("resolved before traces were recorded"))
@ -275,9 +366,9 @@ var _ = Describe("formatExplain", func() {
})
It("prints why the last attempt failed and why it gave up", func() {
rep.Queued = &model.ArtworkQueueItem{Priority: model.ArtworkPriorityScan, Attempts: 3,
rep.queued = &model.ArtworkQueueItem{Priority: model.ArtworkPriorityScan, Attempts: 3,
Trace: `[{"c":"decode","o":"error","d":"bad header"}]`}
rep.Stored = &model.ItemArtwork{Source: "folder", Hash: "abc", AttemptedAt: time.Now(),
rep.stored = &model.ItemArtwork{Source: "folder", Hash: "abc", AttemptedAt: time.Now(),
LastFailure: `[{"c":"read","o":"error","d":"i/o timeout"}]`}
out := formatExplain(rep)
@ -296,10 +387,10 @@ var _ = Describe("formatExplain", func() {
It("reports the setting that governs media file artwork", func() {
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false })
rep = artwork.ExplainReport{
Kind: model.KindMediaFileArtwork, ID: "mf-1", Name: "Airbag",
Walked: true,
Steps: []artwork.TraceStep{
rep = explainReport{
kind: model.KindMediaFileArtwork, id: "mf-1", name: "Airbag",
walked: true,
steps: []artwork.TraceStep{
{Candidate: "embedded", Outcome: "skipped", Detail: "EnableMediaFileCoverArt is off"},
},
}
@ -312,11 +403,31 @@ var _ = Describe("formatExplain", func() {
})
})
var _ = Describe("explainConfig", func() {
BeforeEach(func() {
conf.Update(func(c *conf.Options) {
c.DiscArtPriority = "cover.jpg"
c.EnableMediaFileCoverArt = true
})
})
DescribeTable("names the setting that decides where a kind's artwork comes from",
func(kind model.Kind, setting, value string) {
gotSetting, gotValue := explainConfig(kind)
Expect(gotSetting).To(Equal(setting))
Expect(gotValue).To(Equal(value))
},
Entry("disc", model.KindDiscArtwork, "DiscArtPriority", "cover.jpg"),
Entry("media file", model.KindMediaFileArtwork, "EnableMediaFileCoverArt", "true"),
Entry("playlist has none", model.KindPlaylistArtwork, "", ""),
)
})
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())
})
})
@ -364,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 {
@ -384,8 +498,8 @@ var _ = Describe("explain/reprocess source round trip", func() {
Expect(art.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: model.KindArtistArtwork.Prefix(),
ItemID: "ar-1", ImageType: model.ImageTypePrimary})).To(Succeed())
shown := storedSource(formatExplain(artwork.ExplainReport{Kind: model.KindArtistArtwork, ID: "ar-1",
Stored: &model.ItemArtwork{AttemptedAt: time.Now()}}))
shown := storedSource(formatExplain(explainReport{kind: model.KindArtistArtwork, id: "ar-1",
stored: &model.ItemArtwork{AttemptedAt: time.Now()}}))
q := ds.ArtworkQueue()
Expect(validateSources(ctx, q, repositorySources([]string{shown}))).To(Succeed(),
@ -456,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 }
@ -467,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"
@ -695,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())
})
})
@ -704,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)
@ -859,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}
@ -953,7 +1070,7 @@ var _ = Describe("parseArtworkPriority", func() {
It("accepts every name status prints", func() {
for _, p := range []int{model.ArtworkPriorityRecheck, model.ArtworkPriorityBackfill,
model.ArtworkPriorityScan, model.ArtworkPriorityBump} {
Expect(parseArtworkPriority(artwork.PriorityName(p))).To(Equal(p))
Expect(parseArtworkPriority(priorityName(p))).To(Equal(p))
}
})
@ -1033,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()

View file

@ -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

View file

@ -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
}

View file

@ -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 = ","
}

View file

@ -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)
}
}

View file

@ -4,6 +4,7 @@ import (
"context"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"os"
@ -307,7 +308,7 @@ func formatPluginList(list model.Plugins, format string) (string, error) {
_ = w.Write([]string{"id", "name", "version", "enabled", "last error"})
for _, p := range list {
name, version := manifestSummary(p)
_ = w.Write([]string{p.ID, name, version, fmt.Sprintf("%t", p.Enabled), p.LastError})
_ = w.Write([]string{p.ID, name, version, strconv.FormatBool(p.Enabled), p.LastError})
}
w.Flush()
return sb.String(), w.Error()
@ -440,7 +441,7 @@ func readConfigFile(ctx context.Context, path string) string {
func applyPluginEdit(ctx context.Context, mgr pluginManager, cur *model.Plugin, opts pluginEditOptions) error {
if opts.config == nil && opts.users == nil && opts.allUsers == nil &&
opts.libraries == nil && opts.allLibraries == nil && opts.writeAccess == nil {
return fmt.Errorf("nothing to update: provide at least one of --config/--users/--libraries/--write-access")
return errors.New("nothing to update: provide at least one of --config/--users/--libraries/--write-access")
}
id := cur.ID
if opts.config != nil {
@ -499,18 +500,18 @@ func usersToJSON(value string) (string, error) {
}
if strings.HasPrefix(strings.TrimSpace(value), "[") {
if !json.Valid([]byte(value)) {
return "", fmt.Errorf("invalid JSON in --users")
return "", errors.New("invalid JSON in --users")
}
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
@ -521,12 +522,12 @@ func librariesToJSON(value string) (string, error) {
}
if strings.HasPrefix(strings.TrimSpace(value), "[") {
if !json.Valid([]byte(value)) {
return "", fmt.Errorf("invalid JSON in --libraries")
return "", errors.New("invalid JSON in --libraries")
}
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 +536,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{

View file

@ -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))
})

View file

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

View file

@ -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"))
})

View file

@ -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)
}
}

View file

@ -82,7 +82,7 @@ func CreateNativeAPIRouter(ctx context.Context) *nativeapi.Router {
matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher, broker)
quickConnect := quickconnect.GetInstance()
router := nativeapi.New(dataStore, share, playlistsPlaylists, insights, library, user, maintenance, manager, uploader, provider, quickConnect, agentsAgents)
router := nativeapi.New(dataStore, share, playlistsPlaylists, insights, library, user, maintenance, manager, uploader, provider, quickConnect)
return router
}

View file

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

View file

@ -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()

View file

@ -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")))
})
})

View file

@ -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

View file

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

View file

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

View file

@ -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)
}
}

View file

@ -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" })

View file

@ -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}
})

View file

@ -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}

View file

@ -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")

View file

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

View file

@ -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))

View file

@ -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"))
}))

View file

@ -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()
}

View file

@ -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),

View file

@ -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 {

View file

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

View file

@ -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())
})

View file

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

View file

@ -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)

View file

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

View file

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

View file

@ -1,215 +0,0 @@
package artwork
import (
"context"
"errors"
"fmt"
"slices"
"strconv"
"strings"
"time"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils/slice"
)
// Result states the verdict of the walk. A skipped or failed external tier, or a local candidate
// that would not open, leaves the outcome unknown: nothing observed that there is no artwork.
func Result(source string, steps []TraceStep) string {
if source != "" {
for _, s := range steps {
if s.Outcome == OutcomeHit {
break
}
// An external winner discards the earlier error, so the resolver settles it with no retry.
if s.Outcome == OutcomeError && strings.HasPrefix(s.Candidate, ExternalPrefix) &&
!strings.HasPrefix(source, ExternalPrefix) {
return "resolved from " + source +
" (indeterminate: a higher-priority external lookup failed; this may resolve differently on a retry)"
}
}
return "resolved from " + source
}
for _, s := range steps {
switch {
case s.Outcome == OutcomeError && strings.HasPrefix(s.Candidate, ExternalPrefix):
return "indeterminate (an external lookup failed; the item may resolve on a later attempt)"
case s.Outcome == OutcomeError, s.Outcome == OutcomeUnreadable:
return "indeterminate (a candidate was found but could not be processed; the worker retries rather than settling absent)"
}
}
return "not resolved"
}
// ConfigFor names the setting that decides where a kind's artwork comes from, and its value.
func ConfigFor(kind model.Kind) (setting, value string) {
switch kind {
case model.KindArtistArtwork:
return "ArtistArtPriority", conf.Server().ArtistArtPriority
case model.KindAlbumArtwork:
return "CoverArtPriority", conf.Server().CoverArtPriority
case model.KindDiscArtwork:
return "DiscArtPriority", conf.Server().DiscArtPriority
case model.KindMediaFileArtwork:
return "EnableMediaFileCoverArt", strconv.FormatBool(conf.Server().EnableMediaFileCoverArt)
}
return "", ""
}
// ImageAgentNames names the agents that can actually supply an image for kind.
func ImageAgentNames(ag *agents.Agents, kind model.Kind) []string {
if kind == model.KindArtistArtwork {
return slice.Map(ag.ArtistImageAgents(), func(a agents.ArtistImageAgent) string { return a.Name })
}
return slice.Map(ag.AlbumImageAgents(), func(a agents.AlbumImageAgent) string { return a.Name })
}
// FormatAgents accounts for every configured agent: one that cannot be constructed never reaches
// the chain, so the raw list alone overstates it. Those are starred, and the bool lets each
// caller word its own legend.
func FormatAgents(configured string, available []string) (string, bool) {
if strings.TrimSpace(configured) == "" {
return "(none)", false
}
var unavailable bool
names := slice.Map(strings.Split(configured, ","), func(name string) string {
name = strings.TrimSpace(name)
if slices.Contains(available, name) {
return name
}
unavailable = true
return name + "*"
})
return strings.Join(names, ", "), unavailable
}
// ExplainOptions configures a single explain. The zero value reads history and never
// touches the network.
type ExplainOptions struct {
// Walk builds a resolver that records into the trace; nil reads the recorded trace instead.
Walk func(*ChainTrace) *TracingResolver
}
// ExplainReport is everything known about how one item's artwork resolved.
type ExplainReport struct {
Kind model.Kind
ID string
Name string
Stored *model.ItemArtwork
Queued *model.ArtworkQueueItem
Steps []TraceStep
Source string
Agents string
// AgentsIncomplete reports that some configured agent is starred in Agents.
AgentsIncomplete bool
Walked bool
ResolveErr error
}
// Explain gathers everything known about how kind/id's artwork resolved: stored state, the
// queue row, and either the recorded trace or a fresh walk, depending on opts.Walk.
func Explain(ctx context.Context, ds model.DataStore, ag *agents.Agents, kind model.Kind, id string,
opts ExplainOptions) (ExplainReport, error) {
name, err := ItemName(ctx, ds, kind, id)
if err != nil {
return ExplainReport{}, err
}
rep := ExplainReport{Kind: kind, ID: id, Name: name}
if KeepsState(kind) {
rep.Stored, err = ds.Artwork().GetItemArtwork(ctx, kind, id, model.ImageTypePrimary)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return ExplainReport{}, fmt.Errorf("reading artwork state: %w", err)
}
rep.Queued, err = ds.ArtworkQueue().Get(ctx, kind, id, model.ImageTypePrimary)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return ExplainReport{}, fmt.Errorf("reading the artwork queue: %w", err)
}
}
// Set even for a kind the chain never walks, so a caller that asked to walk (e.g. --live on a
// playlist) is reported as having tried.
rep.Walked = opts.Walk != nil
if !Explainable(kind) {
return rep, nil
}
if ag != nil && (kind == model.KindArtistArtwork || kind == model.KindAlbumArtwork) {
rep.Agents, rep.AgentsIncomplete = FormatAgents(conf.Server().Agents, ImageAgentNames(ag, kind))
}
switch {
case rep.Walked:
trace := &ChainTrace{}
rep.Source, rep.ResolveErr = opts.Walk(trace).Resolve(ctx, kind, id)
rep.Steps = trace.Steps()
case rep.Stored != nil:
rep.Steps = DecodeTrace(rep.Stored.Trace, rep.Stored.SourcePath)
rep.Source = rep.Stored.Source
}
return rep, nil
}
// Result reports this report's verdict; see the package-level Result for the rules.
func (r ExplainReport) Result() string { return Result(r.Source, r.Steps) }
// ChainOrigin says whether the report reads history or a walk performed just now, since the two
// can disagree after a config change.
func (r ExplainReport) ChainOrigin() string {
if r.Walked {
return "walked now"
}
if r.Stored != nil {
return "recorded " + FormatTime(r.Stored.AttemptedAt)
}
return "not recorded"
}
// FormatTime renders a timestamp for the report: a zero time reads as unset, not as year 1.
func FormatTime(t time.Time) string {
if t.IsZero() {
return "-"
}
return t.Format(time.RFC3339)
}
// LastAttemptFailed decodes why the queued row's last attempt failed, if there is one queued.
func (r ExplainReport) LastAttemptFailed() []TraceStep {
if r.Queued == nil {
return nil
}
return DecodeTrace(r.Queued.Trace, "")
}
// GaveUpAfter decodes the trace of the attempt that exhausted the retry budget, if the stored
// state recorded one.
func (r ExplainReport) GaveUpAfter() []TraceStep {
if r.Stored == nil {
return nil
}
return DecodeTrace(r.Stored.LastFailure, "")
}
// Priority names one of the queue's fixed priority levels.
type Priority struct {
Name string
Value int
}
// KnownPriorities is the one listing behind both the name and the parse, so they cannot drift.
var KnownPriorities = []Priority{
{"bump", model.ArtworkPriorityBump},
{"scan", model.ArtworkPriorityScan},
{"recheck", model.ArtworkPriorityRecheck},
{"backfill", model.ArtworkPriorityBackfill},
}
// PriorityName falls back to the number: a row written by a newer version still has to print.
func PriorityName(p int) string {
for _, ap := range KnownPriorities {
if ap.Value == p {
return ap.Name
}
}
return strconv.Itoa(p)
}

View file

@ -1,211 +0,0 @@
package artwork_test
import (
"context"
"time"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/artwork"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Result", func() {
It("reports the source when one was found", func() {
steps := []artwork.TraceStep{{Candidate: "cover.*", Outcome: artwork.OutcomeHit}}
Expect(artwork.Result("folder", steps)).To(Equal("resolved from folder"))
})
It("flags a local win that a failed external lookup could have outranked", func() {
steps := []artwork.TraceStep{
{Candidate: artwork.ExternalPrefix + "deezer", Outcome: artwork.OutcomeError, Detail: "timeout"},
{Candidate: "cover.*", Outcome: artwork.OutcomeHit},
}
Expect(artwork.Result("folder", steps)).To(ContainSubstring("indeterminate"))
})
It("does not flag an external winner", func() {
steps := []artwork.TraceStep{
{Candidate: artwork.ExternalPrefix + "lastfm", Outcome: artwork.OutcomeError},
{Candidate: artwork.ExternalPrefix + "deezer", Outcome: artwork.OutcomeHit},
}
Expect(artwork.Result(artwork.ExternalPrefix+"deezer", steps)).
To(Equal("resolved from external:deezer"))
})
It("is indeterminate when an external lookup failed and nothing resolved", func() {
steps := []artwork.TraceStep{{Candidate: artwork.ExternalPrefix + "deezer", Outcome: artwork.OutcomeError}}
Expect(artwork.Result("", steps)).To(ContainSubstring("an external lookup failed"))
})
It("is indeterminate when a candidate could not be processed", func() {
steps := []artwork.TraceStep{{Candidate: "cover.*", Outcome: artwork.OutcomeUnreadable}}
Expect(artwork.Result("", steps)).To(ContainSubstring("could not be processed"))
})
It("reports a clean miss", func() {
steps := []artwork.TraceStep{{Candidate: "cover.*", Outcome: artwork.OutcomeMiss}}
Expect(artwork.Result("", steps)).To(Equal("not resolved"))
})
})
var _ = Describe("ConfigFor", func() {
BeforeEach(func() {
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external" })
})
It("names the setting for a kind that has one", func() {
setting, value := artwork.ConfigFor(model.KindArtistArtwork)
Expect(setting).To(Equal("ArtistArtPriority"))
Expect(value).To(Equal("external"))
})
It("names the setting for the album kind", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*, embedded" })
setting, value := artwork.ConfigFor(model.KindAlbumArtwork)
Expect(setting).To(Equal("CoverArtPriority"))
Expect(value).To(Equal("cover.*, embedded"))
})
It("returns nothing for a kind with no source configuration", func() {
setting, _ := artwork.ConfigFor(model.KindPlaylistArtwork)
Expect(setting).To(BeEmpty())
})
})
var _ = Describe("FormatAgents", func() {
It("reports none when nothing is configured", func() {
line, incomplete := artwork.FormatAgents(" ", nil)
Expect(line).To(Equal("(none)"))
Expect(incomplete).To(BeFalse())
})
It("keeps the configured order and marks what is unavailable", func() {
got, incomplete := artwork.FormatAgents("spotify, lastfm", []string{"lastfm"})
Expect(incomplete).To(BeTrue())
Expect(got).To(Equal("spotify*, lastfm"))
})
It("reports complete when every configured agent is available", func() {
line, incomplete := artwork.FormatAgents("lastfm", []string{"lastfm"})
Expect(line).To(Equal("lastfm"))
Expect(incomplete).To(BeFalse())
})
})
var _ = Describe("PriorityName", func() {
It("names a known priority", func() {
Expect(artwork.PriorityName(model.ArtworkPriorityScan)).To(Equal("scan"))
})
It("falls back to the number for an unknown priority", func() {
Expect(artwork.PriorityName(999)).To(Equal("999"))
})
})
var _ = Describe("Explain", func() {
var ds *tests.MockDataStore
var artRepo *tests.MockArtworkRepo
var queueRepo *tests.MockArtworkQueueRepo
var ctx context.Context
BeforeEach(func() {
ctx = GinkgoT().Context()
artRepo = tests.CreateMockArtworkRepo()
queueRepo = tests.CreateMockArtworkQueueRepo()
ds = &tests.MockDataStore{MockedArtwork: artRepo, MockedArtworkQueue: queueRepo}
Expect(ds.Artist().Put(ctx, &model.Artist{ID: "ar-1", Name: "Radiohead"})).To(Succeed())
})
It("returns an error when the item does not exist", func() {
_, err := artwork.Explain(ctx, ds, nil, model.KindArtistArtwork, "nope", artwork.ExplainOptions{})
Expect(err).To(MatchError(model.ErrNotFound))
})
It("reads the recorded trace when no walker is supplied", func() {
// Storage shape mirrors storedStep in trace.go: c=candidate, o=outcome, d=detail.
trace := `[{"c":"external:deezer","o":"hit","d":"https://cdn/x.jpg"}]`
Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{
ItemKind: model.KindArtistArtwork.Prefix(), ItemID: "ar-1", ImageType: model.ImageTypePrimary,
Hash: "abc", Source: "external:deezer",
Trace: trace,
AttemptedAt: time.Date(2026, 9, 1, 10, 0, 0, 0, time.UTC),
})).To(Succeed())
rep, err := artwork.Explain(ctx, ds, nil, model.KindArtistArtwork, "ar-1", artwork.ExplainOptions{})
Expect(err).ToNot(HaveOccurred())
Expect(rep.Name).To(Equal("Radiohead"))
Expect(rep.Walked).To(BeFalse())
Expect(rep.Steps).To(Equal([]artwork.TraceStep{
{Candidate: "external:deezer", Outcome: artwork.OutcomeHit, Detail: "https://cdn/x.jpg"},
}))
Expect(rep.Source).To(Equal("external:deezer"))
Expect(rep.Result()).To(Equal("resolved from external:deezer"))
Expect(rep.ChainOrigin()).To(ContainSubstring("recorded"))
})
It("renders a zero attempted-at as unset, not as year 1", func() {
rep := artwork.ExplainReport{Stored: &model.ItemArtwork{Source: "folder"}}
Expect(rep.ChainOrigin()).To(Equal("recorded -"))
})
It("reports nothing recorded when there is no stored state", func() {
rep, err := artwork.Explain(ctx, ds, nil, model.KindArtistArtwork, "ar-1", artwork.ExplainOptions{})
Expect(err).ToNot(HaveOccurred())
Expect(rep.Stored).To(BeNil())
Expect(rep.Steps).To(BeEmpty())
Expect(rep.ChainOrigin()).To(Equal("not recorded"))
})
It("includes the queue row and its failure trace", func() {
failure := `[{"c":"external:lastfm","o":"error","d":"429"}]`
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
ItemKind: model.KindArtistArtwork.Prefix(), ItemID: "ar-1", ImageType: model.ImageTypePrimary,
Priority: model.ArtworkPriorityScan,
})).To(Succeed())
queueRepo.SetTrace(model.KindArtistArtwork, "ar-1", model.ImageTypePrimary, failure)
rep, err := artwork.Explain(ctx, ds, nil, model.KindArtistArtwork, "ar-1", artwork.ExplainOptions{})
Expect(err).ToNot(HaveOccurred())
Expect(rep.Queued).ToNot(BeNil())
Expect(rep.Queued.Priority).To(Equal(model.ArtworkPriorityScan))
Expect(rep.LastAttemptFailed()).To(Equal([]artwork.TraceStep{
{Candidate: "external:lastfm", Outcome: artwork.OutcomeError, Detail: "429"},
}))
})
It("records nothing for a kind that keeps no state and has no walker", func() {
Expect(ds.Album().Put(ctx, &model.Album{ID: "al-1", Name: "OK Computer"})).To(Succeed())
rep, err := artwork.Explain(ctx, ds, nil, model.KindDiscArtwork, "al-1:2", artwork.ExplainOptions{})
Expect(err).ToNot(HaveOccurred())
Expect(rep.Stored).To(BeNil())
Expect(rep.Steps).To(BeEmpty())
})
It("performs a fresh walk and reports its outcome, including a failed one, when a walker is supplied", func() {
// GetAll erroring mid-walk is a deterministic way to force ResolveErr without a real library.
ds.Album().(*tests.MockAlbumRepo).SetError(true)
opts := artwork.ExplainOptions{Walk: func(t *artwork.ChainTrace) *artwork.TracingResolver {
return artwork.NewTracingResolver(ds, nil, nil, t, false)
}}
rep, err := artwork.Explain(ctx, ds, nil, model.KindArtistArtwork, "ar-1", opts)
Expect(err).ToNot(HaveOccurred())
Expect(rep.Walked).To(BeTrue())
Expect(rep.ResolveErr).To(HaveOccurred())
})
It("still reports Walked for a kind with no chain to walk, when a walker is supplied", func() {
Expect(ds.Playlist().Put(ctx, &model.Playlist{ID: "pl-1", Name: "Favorites"})).To(Succeed())
opts := artwork.ExplainOptions{Walk: func(*artwork.ChainTrace) *artwork.TracingResolver {
panic("a kind that cannot walk must never be handed to the walker")
}}
rep, err := artwork.Explain(ctx, ds, nil, model.KindPlaylistArtwork, "pl-1", opts)
Expect(err).ToNot(HaveOccurred())
Expect(rep.Walked).To(BeTrue())
})
})

View file

@ -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}

View file

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

View file

@ -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{}

View file

@ -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")}}
})

View file

@ -25,13 +25,6 @@ var ReprocessKinds = []model.Kind{
// artwork is read through on every request and cached by content key, so it has neither.
func KeepsState(kind model.Kind) bool { return kind != model.KindDiscArtwork }
// ExplainKinds is every kind Explain accepts: it reports stored state and config too, so a kind
// with no chain to walk still has something to answer with.
var ExplainKinds = []model.Kind{
model.KindArtistArtwork, model.KindAlbumArtwork, model.KindDiscArtwork,
model.KindMediaFileArtwork, model.KindPlaylistArtwork, model.KindRadioArtwork,
}
// RefreshableKinds is every kind Refresh can clear and re-queue, so it holds exactly the kinds
// KeepsState admits. Media files are absent from ReprocessKinds but belong here: the worker
// resolves them, it just never enumerates them in bulk.

View file

@ -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"},

View file

@ -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")))

View file

@ -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() {

View file

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

View file

@ -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())

View file

@ -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())

View file

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

View file

@ -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())

View file

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

View file

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

View file

@ -7,6 +7,7 @@ import (
"slices"
"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)
}

View file

@ -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() {

View file

@ -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())
})
})

View file

@ -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 {

View file

@ -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)
}

View file

@ -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()))
})
})

View file

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

View file

@ -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))
})

View file

@ -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)

View file

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

View file

@ -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}},

View file

@ -293,7 +293,7 @@ func parseProbeOutput(data []byte) (*AudioProbeResult, error) {
return result, nil
}
return nil, fmt.Errorf("no audio stream found in ffprobe output")
return nil, errors.New("no audio stream found in ffprobe output")
}
func (e *ffmpeg) CmdPath() (string, error) {
@ -490,7 +490,7 @@ func buildDynamicArgs(opts TranscodeOptions) []string {
// buildTemplateArgs handles user-customized command templates, with dynamic injection
// of sample rate, channels, and bit depth when requested by the transcode decision.
// Values in opts have already been clamped to codec limits upstream (see
// core/stream/codec.go codecMax* helpers), so injecting them unconditionally is safe —
// core/stream/codec.go), so injecting them unconditionally is safe —
// ffmpeg honors the last occurrence of a duplicate flag.
func buildTemplateArgs(opts TranscodeOptions) []string {
args := createFFmpegCommand(opts.Command, opts.FilePath, opts.BitRate, opts.Offset)
@ -552,7 +552,7 @@ func bitDepthToSampleFmt(bitDepth int) string {
}
}
// Path will always be an absolute path
// createFFmpegCommand expects path to always be an absolute path
func createFFmpegCommand(cmd, path string, maxBitRate, offset int) []string {
var args []string
for _, s := range fixCmd(cmd) {
@ -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)

View file

@ -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)

View file

@ -111,7 +111,7 @@ func (s *libraryService) SetUserLibraries(ctx context.Context, userID string, li
func (s *libraryService) ValidateLibraryAccess(ctx context.Context, userID string, libraryID int) error {
user, ok := request.UserFrom(ctx)
if !ok {
return fmt.Errorf("user not found in context")
return errors.New("user not found in context")
}
// Admin users have access to all libraries
@ -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)
}
@ -350,7 +350,7 @@ func updatesColumn(cols []string, col string) bool {
func (r *libraryRepositoryWrapper) validateLibraryPath(ctx context.Context, library *model.Library) error {
// Validate path format
if !filepath.IsAbs(library.Path) {
return fmt.Errorf("library path must be absolute")
return errors.New("library path must be absolute")
}
// Clean the path to normalize it
@ -377,7 +377,7 @@ func (r *libraryRepositoryWrapper) validateLibraryPath(ctx context.Context, libr
}
if !info.IsDir() {
return fmt.Errorf("resources.library.validation.pathNotDirectory")
return errors.New("resources.library.validation.pathNotDirectory")
}
return nil

View file

@ -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))
})
})
})

View file

@ -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

View file

@ -3,7 +3,7 @@ package lyrics_test
import (
"context"
"encoding/json"
"fmt"
"errors"
"os"
"path/filepath"
@ -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,20 +351,91 @@ 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))
})
It("should handle plugin error gracefully", func() {
conf.Update(func(c *conf.Options) { c.LyricsPriority = "test-lyrics-plugin,embedded" })
mockLoader.err = fmt.Errorf("plugin error")
mockLoader.err = errors.New("plugin error")
svc := lyrics.NewLyrics(nil, mockLoader)
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 = errors.New("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
}

View file

@ -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
})
}

View file

@ -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())

View file

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

View file

@ -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},

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