Compare commits

...

53 commits

Author SHA1 Message Date
Deluan Quintão
06df4a5661
feat(jellyfin): expose internet radio stations as Live TV radio channels (#6528) 2026-11-22 20:19:16 -05:00
Deluan Quintão
b9af3241e6
fix(external): don't refresh info right after a first-time fetch (#6527) 2026-11-22 18:04:03 -05:00
Deluan Quintão
f78929da2e
test: replace shared repository fakes with a real per-suite database (#6519) 2026-11-22 15:41:43 -05:00
Deluan
71553644ed docs: explain how to add UI strings and translations
Contributors should add new UI strings in English to ui/src/i18n/en.json.
They may also translate them into a language they speak. The other
languages are left to translators, who update them through POEditor, so
contributors should not edit or machine-translate them.

Signed-off-by: Deluan <deluan@navidrome.org>
2026-11-22 15:22:49 -05:00
Deluan Quintão
1c2ed1628c
feat(ui): show each performer sub-role on its own row in Get Info (#6526) 2026-11-22 14:43:22 -05:00
Deluan Quintão
4cd7ab1c60
fix(ui): play the saved queue after reopening the browser (#6524) 2026-11-21 22:14:37 -05:00
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
565 changed files with 14276 additions and 14169 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
@ -46,6 +48,10 @@ Prefer existing patterns and the smallest clear solution. Justify new abstractio
The maintainer must be able to understand and maintain the result without depending on your future availability. An offer to provide ongoing support does not replace this requirement. A working implementation may still be declined if its benefit does not justify its complexity or maintenance cost.
## UI strings and translations
Add new or changed UI strings in English to `ui/src/i18n/en.json`. You may also add the translation for a language you speak in its file under `resources/i18n/`. Leave the other languages alone, and do not add machine translations for them. Translators update those languages through the [localization process](https://www.navidrome.org/docs/developers/translations/) on POEditor.
<a id="pull-requests"></a>
## Submitting and review

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

@ -12,7 +12,7 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/model"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
@ -21,14 +21,14 @@ 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 })
})
Describe("deezerConstructor", func() {
It("uses configured languages", func() {
conf.Update(func(c *conf.Options) { c.Deezer.Languages = []string{"pt", "en"} })
agent := deezerConstructor(&tests.MockDataStore{}).(*deezerAgent)
agent := deezerConstructor(struct{ model.DataStore }{}).(*deezerAgent)
Expect(agent.languages).To(Equal([]string{"pt", "en"}))
})
})
@ -40,15 +40,14 @@ var _ = Describe("deezerAgent", func() {
BeforeEach(func() {
httpClient = &fakeHttpClient{}
agent = &deezerAgent{
dataStore: &tests.MockDataStore{},
client: newClient(httpClient),
client: newClient(httpClient),
}
})
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 +65,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 +82,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 +96,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}`)),
@ -116,14 +115,13 @@ var _ = Describe("deezerAgent", func() {
BeforeEach(func() {
httpClient = &fakeHttpClient{}
agent = &deezerAgent{
dataStore: &tests.MockDataStore{},
client: newClient(httpClient),
client: newClient(httpClient),
}
})
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 +138,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 +164,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))),
}
})
@ -179,7 +177,6 @@ var _ = Describe("deezerAgent", func() {
setupAgent := func(languages []string) {
conf.Update(func(c *conf.Options) { c.Deezer.Languages = languages })
agent = &deezerAgent{
dataStore: &tests.MockDataStore{},
client: newClient(httpClient),
languages: languages,
}
@ -190,7 +187,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 +202,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 +221,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 +256,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 +267,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 +282,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

@ -14,7 +14,9 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/scrobbler"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -29,8 +31,8 @@ var _ = Describe("lastfmAgent", func() {
var ds model.DataStore
var ctx context.Context
BeforeEach(func() {
ds = &tests.MockDataStore{}
ctx = context.Background()
ctx = GinkgoT().Context()
ds = persistence.New(db.Db())
conf.Update(func(c *conf.Options) {
c.LastFM.Enabled = true
c.LastFM.ApiKey = "123"
@ -47,24 +49,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 +78,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 +93,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 +103,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 +126,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 +143,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 +164,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 +191,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 +213,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 +239,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 +257,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 +277,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 +295,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 +315,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 +330,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 +344,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))
@ -357,7 +356,8 @@ var _ = Describe("lastfmAgent", func() {
var httpClient *tests.FakeHttpClient
var track *model.MediaFile
BeforeEach(func() {
_ = ds.UserProps().Put(ctx, "user-1", sessionKeyProperty, "SK-1")
Expect(ds.User().Put(ctx, &model.User{ID: "user-1", UserName: "user-1"})).To(Succeed())
Expect(ds.UserProps().Put(ctx, "user-1", sessionKeyProperty, "SK-1")).To(Succeed())
httpClient = &tests.FakeHttpClient{}
client := newClient("API_KEY", "SECRET", httpClient)
agent = lastFMConstructor(ds)
@ -373,12 +373,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 +386,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 +416,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 +432,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 +459,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 +471,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 +481,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 +529,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 +539,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 +549,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 +559,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 +569,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 +590,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 +606,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 +624,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 +632,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 +658,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 +670,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 +678,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 +690,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 +701,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 +714,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 +732,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 +765,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

@ -10,8 +10,10 @@ import (
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -19,8 +21,7 @@ import (
var _ = Describe("auth_router", func() {
var (
ds *tests.MockDataStore
userProps *tests.MockedUserPropsRepo
ds model.DataStore
httpClient *tests.FakeHttpClient
router *Router
)
@ -31,10 +32,10 @@ var _ = Describe("auth_router", func() {
)
BeforeEach(func() {
userProps = &tests.MockedUserPropsRepo{}
ds = &tests.MockDataStore{
MockedProperty: &tests.MockedPropertyRepo{},
MockedUserProps: userProps,
ctx := GinkgoT().Context()
ds = persistence.New(db.Db())
for _, id := range []string{victimID, attackerID} {
Expect(ds.User().Put(ctx, &model.User{ID: id, UserName: id})).To(Succeed())
}
auth.Init(ds)
@ -50,14 +51,14 @@ var _ = Describe("auth_router", func() {
})
storedSessionKey := func(userID string) string {
key, _ := userProps.Get(GinkgoT().Context(), userID, sessionKeyProperty)
key, _ := ds.UserProps().Get(GinkgoT().Context(), userID, sessionKeyProperty)
return key
}
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 +75,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

@ -5,6 +5,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -13,8 +14,10 @@ import (
func TestLastFM(t *testing.T) {
tests.Init(t, false)
log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail)
RunSpecs(t, "LastFM Test Suite")
}
var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

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,12 +8,16 @@ 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"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -28,9 +32,10 @@ var _ = Describe("listenBrainzAgent", func() {
var track *model.MediaFile
BeforeEach(func() {
ds = &tests.MockDataStore{}
ctx = context.Background()
_ = ds.UserProps().Put(ctx, "user-1", sessionKeyProperty, "SK-1")
ctx = GinkgoT().Context()
ds = persistence.New(db.Db())
Expect(ds.User().Put(ctx, &model.User{ID: "user-1", UserName: "user-1"})).To(Succeed())
Expect(ds.UserProps().Put(ctx, "user-1", sessionKeyProperty, "SK-1")).To(Succeed())
httpClient = &tests.FakeHttpClient{}
agent = listenBrainzConstructor(ds)
agent.client = newClient("http://localhost:8080", httpClient)
@ -46,8 +51,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 +85,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 +105,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 +133,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 +143,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 +153,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 +163,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 +172,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 +196,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 +204,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 +222,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 +252,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 +262,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 +289,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 +315,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 +327,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 +359,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 +369,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 +383,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 +419,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 +429,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 +461,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 +482,43 @@ var _ = Describe("listenBrainzAgent", func() {
})
})
})
var _ = Describe("register", func() {
var ds model.DataStore
BeforeEach(func() {
ds = struct{ model.DataStore }{}
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

@ -5,6 +5,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -13,8 +14,10 @@ import (
func TestListenBrainz(t *testing.T) {
tests.Init(t, false)
log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail)
RunSpecs(t, "ListenBrainz Test Suite")
}
var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

View file

@ -342,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)
@ -428,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
@ -559,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) {

View file

@ -10,8 +10,10 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/artwork"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
@ -54,13 +56,13 @@ var _ = Describe("parseArtworkKind", func() {
})
var _ = Describe("resolveArtworkTargets", func() {
var ds *tests.MockDataStore
ctx := context.Background()
var ds model.DataStore
var ctx context.Context
BeforeEach(func() {
artists := tests.CreateMockArtistRepo()
artists.SetData(model.Artists{{ID: "artist1"}})
ds = &tests.MockDataStore{MockedArtist: artists}
ctx = GinkgoT().Context()
ds = persistence.New(db.Db())
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "artist1", Name: "artist1"})
})
It("accepts the explicit <kind> <id> leader shared by every id", func() {
@ -424,9 +426,9 @@ var _ = Describe("explainConfig", func() {
var _ = Describe("artwork refresh command", func() {
It("requires at least one argument", func() {
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{})).To(HaveOccurred())
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"id1"})).ToNot(HaveOccurred())
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"ar", "id1"})).ToNot(HaveOccurred())
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{})).ToNot(Succeed())
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"id1"})).To(Succeed())
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"ar", "id1"})).To(Succeed())
})
})
@ -474,7 +476,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 {
@ -489,8 +494,8 @@ var _ = Describe("explain/reprocess source round trip", func() {
}
It("names the absent state as reprocess --source accepts it", func() {
ds := &tests.MockDataStore{}
art := ds.Artwork().(*tests.MockArtworkRepo)
ds := persistence.New(db.Db())
art := ds.Artwork()
Expect(art.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: model.KindArtistArtwork.Prefix(),
ItemID: "ar-1", ImageType: model.ImageTypePrimary})).To(Succeed())
@ -561,12 +566,12 @@ var _ = Describe("confirmUnlessYes", func() {
})
var _ = Describe("reprocessArtwork", func() {
var ds *tests.MockDataStore
var art *tests.MockArtworkRepo
var queue *tests.MockArtworkQueueRepo
var ds model.DataStore
var art model.ArtworkRepository
var queue model.ArtworkQueueRepository
var out strings.Builder
var imageAgents artwork.ImageAgentCount
ctx := context.Background()
var ctx context.Context
kinds := []model.Kind{model.KindArtistArtwork, model.KindAlbumArtwork}
accept := func(io.Writer, int64, int64) bool { return true }
decline := func(io.Writer, int64, int64) bool { return false }
@ -577,15 +582,16 @@ var _ = Describe("reprocessArtwork", func() {
}
BeforeEach(func() {
ctx = GinkgoT().Context()
conf.Update(func(c *conf.Options) {
c.CoverArtPriority = "cover.*, external"
c.ArtistArtPriority = "artist.*, external"
c.EnableM3UExternalAlbumArt = false
})
imageAgents = artwork.ImageAgentCount{Artist: 1, Album: 1}
ds = &tests.MockDataStore{}
art = ds.Artwork().(*tests.MockArtworkRepo)
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo)
ds = persistence.New(db.Db())
art = ds.Artwork()
queue = ds.ArtworkQueue()
out.Reset()
put(model.KindArtistArtwork, "ar-1", "external:deezer")
put(model.KindArtistArtwork, "ar-2", "")
@ -805,21 +811,22 @@ 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())
})
})
var _ = Describe("collectStatus", func() {
var ds *tests.MockDataStore
var art *tests.MockArtworkRepo
var queue *tests.MockArtworkQueueRepo
ctx := context.Background()
var ds model.DataStore
var art model.ArtworkRepository
var queue model.ArtworkQueueRepository
var ctx context.Context
BeforeEach(func() {
ds = &tests.MockDataStore{}
art = ds.Artwork().(*tests.MockArtworkRepo)
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo)
ctx = GinkgoT().Context()
ds = persistence.New(db.Db())
art = ds.Artwork()
queue = ds.ArtworkQueue()
put := func(kind model.Kind, id, source, hash string, attempted time.Time) {
Expect(art.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: kind.Prefix(), ItemID: id,
ImageType: model.ImageTypePrimary, Source: source, Hash: hash, AttemptedAt: attempted})).To(Succeed())
@ -965,18 +972,20 @@ var _ = Describe("formatStatus", func() {
})
var _ = Describe("refreshItems", func() {
var ds *tests.MockDataStore
var queue *tests.MockArtworkQueueRepo
var art *tests.MockArtworkRepo
var ds model.DataStore
var queue model.ArtworkQueueRepository
var art model.ArtworkRepository
var out strings.Builder
ctx := context.Background()
var ctx context.Context
BeforeEach(func() {
albums := tests.CreateMockAlbumRepo()
albums.SetData(model.Albums{{ID: "al-1"}, {ID: "al-3"}})
ds = &tests.MockDataStore{MockedAlbum: albums}
art = ds.Artwork().(*tests.MockArtworkRepo)
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo)
ctx = GinkgoT().Context()
ds = persistence.New(db.Db())
for _, id := range []string{"al-1", "al-3"} {
Expect(ds.Album().Put(ctx, &model.Album{ID: id, Name: id, LibraryID: model.DefaultLibraryID})).To(Succeed())
}
art = ds.Artwork()
queue = ds.ArtworkQueue()
out.Reset()
})
@ -1140,16 +1149,17 @@ var _ = Describe("artwork cancel selection", func() {
})
var _ = Describe("cancelArtwork", func() {
var ds *tests.MockDataStore
var queue *tests.MockArtworkQueueRepo
var ds model.DataStore
var queue model.ArtworkQueueRepository
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() {
ds = &tests.MockDataStore{}
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo)
ctx = GinkgoT().Context()
ds = persistence.New(db.Db())
queue = ds.ArtworkQueue()
out.Reset()
Expect(queue.Enqueue(ctx,
model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar-1", ImageType: model.ImageTypePrimary,
@ -1204,7 +1214,18 @@ var _ = Describe("cancelArtwork", func() {
})
It("reports a queue read failure instead of reporting nothing to cancel", func() {
queue.Err = errors.New("read failed")
ds = persistencetest.Stub(ds, persistencetest.Repos{ArtworkQueue: func(r model.ArtworkQueueRepository) model.ArtworkQueueRepository {
return failingQueueRepo{ArtworkQueueRepository: r, err: errors.New("read failed")}
}})
Expect(cancelArtwork(ctx, ds, nil, nil, false, accept, &out)).To(MatchError(ContainSubstring("read failed")))
})
})
type failingQueueRepo struct {
model.ArtworkQueueRepository
err error
}
func (r failingQueueRepo) CountQueued(context.Context, []model.Kind, []int) ([]model.ArtworkQueueStat, error) {
return nil, r.err
}

View file

@ -5,6 +5,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -13,8 +14,10 @@ import (
func TestCmd(t *testing.T) {
tests.Init(t, false)
log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Cmd Suite")
}
var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

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,6 +1,7 @@
package cmd
import (
"context"
"errors"
"net/http"
"net/http/httptest"
@ -9,8 +10,10 @@ import (
"github.com/go-chi/chi/v5"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
@ -43,28 +46,44 @@ var _ = Describe("profilerHandler", func() {
)
})
type failingLibraryRepo struct {
model.LibraryRepository
err error
}
func (r failingLibraryRepo) GetAll(context.Context, ...model.QueryOptions) (model.Libraries, error) {
return nil, r.err
}
var _ = Describe("librariesWithChangedPID", func() {
var ds *tests.MockDataStore
var libs *tests.MockLibraryRepo
var ctx context.Context
var ds model.DataStore
BeforeEach(func() {
libs = &tests.MockLibraryRepo{}
ds = &tests.MockDataStore{MockedLibrary: libs}
ctx = GinkgoT().Context()
ds = persistence.New(db.Db())
})
It("returns only the libraries whose PID config changed", func() {
pid := model.Library{}.EffectivePID()
libs.SetData(model.Libraries{
{ID: 1, Name: "Same", ScannedPIDAlbum: pid.Album, ScannedPIDTrack: pid.Track},
{ID: 2, Name: "Changed", PIDAlbum: "folder", ScannedPIDAlbum: pid.Album, ScannedPIDTrack: pid.Track},
{ID: 3, Name: "Never scanned"},
})
Expect(librariesWithChangedPID(GinkgoT().Context(), ds)).To(ConsistOf("Changed", "Never scanned"))
persistencetest.SetLibraries(ctx, ds, "/music/same", "/music/changed", "/music/never")
same, err := ds.Library().Get(ctx, 1)
Expect(err).ToNot(HaveOccurred())
same.Name = "Same"
Expect(ds.Library().Put(ctx, same)).To(Succeed())
Expect(ds.Library().Put(ctx, &model.Library{ID: 2, Name: "Changed", Path: "/music/changed", PIDAlbum: "folder"})).To(Succeed())
Expect(ds.Library().Put(ctx, &model.Library{ID: 3, Name: "Never scanned", Path: "/music/never"})).To(Succeed())
Expect(ds.Library().SetScannedPID(ctx, 1, pid)).To(Succeed())
Expect(ds.Library().SetScannedPID(ctx, 2, pid)).To(Succeed())
Expect(librariesWithChangedPID(ctx, ds)).To(ConsistOf("Changed", "Never scanned"))
})
It("returns the error from the repository", func() {
libs.Err = errors.New("db down")
_, err := librariesWithChangedPID(GinkgoT().Context(), ds)
ds = persistencetest.Stub(ds, persistencetest.Repos{Library: func(r model.LibraryRepository) model.LibraryRepository {
return failingLibraryRepo{LibraryRepository: r, err: errors.New("db down")}
}})
_, err := librariesWithChangedPID(ctx, ds)
Expect(err).To(MatchError("db down"))
})
})

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

@ -80,7 +80,7 @@ func CreateNativeAPIRouter(ctx context.Context) *nativeapi.Router {
maintenance := core.NewMaintenance(dataStore)
agentsAgents := agents.GetAgents(dataStore, manager)
matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher, broker)
provider := external.NewProvider(ctx, dataStore, agentsAgents, matcherMatcher, broker)
quickConnect := quickconnect.GetInstance()
router := nativeapi.New(dataStore, share, playlistsPlaylists, insights, library, user, maintenance, manager, uploader, provider, quickConnect)
return router
@ -104,7 +104,7 @@ func CreateSubsonicAPIRouter(ctx context.Context) *subsonic.Router {
manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager)
matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher, broker)
provider := external.NewProvider(ctx, dataStore, agentsAgents, matcherMatcher, broker)
uploader := artwork.NewUploader(dataStore)
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader)
modelScanner := scanner.GetInstance(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics)
@ -135,7 +135,7 @@ func CreateJellyfinAPIRouter(ctx context.Context) *jellyfin.Router {
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader)
agentsAgents := agents.GetAgents(dataStore, manager)
matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher, broker)
provider := external.NewProvider(ctx, dataStore, agentsAgents, matcherMatcher, broker)
sonicSonic := sonic.New(dataStore, manager, matcherMatcher)
lyricsLyrics := lyrics.NewLyrics(dataStore, manager)
quickConnect := quickconnect.GetInstance()

View file

@ -5,12 +5,10 @@ import (
"github.com/onsi/ginkgo/v2"
)
// RestoreAfterEachSpec restores the config after every spec. Call it at the top level of a suite.
// Ordered specs are skipped so a BeforeAll can set config for its whole container.
// RestoreAfterEachSpec restores the config after every spec, and after each Ordered container as a
// whole, so its BeforeAll can set config for all its specs. Call it at the top level of a suite.
func RestoreAfterEachSpec() bool {
return ginkgo.BeforeEach(func() {
if !ginkgo.CurrentSpecReport().IsInOrderedContainer {
ginkgo.DeferCleanup(conf.SnapshotConfig())
}
return ginkgo.BeforeEach(ginkgo.OncePerOrdered, func() {
ginkgo.DeferCleanup(conf.SnapshotConfig())
})
}

View file

@ -18,9 +18,22 @@ var _ = Describe("RestoreAfterEachSpec", func() {
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "B" })
})
// Either container can run first: the second one sees the first one's change if it leaks.
for _, name := range []string{"first", "second"} {
Describe("in the "+name+" Ordered container", Ordered, func() {
It("starts with the original value", func() {
Expect(conf.Server().UIWelcomeMessage).To(BeEmpty())
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = name })
})
It("keeps the change for the rest of the container", func() {
Expect(conf.Server().UIWelcomeMessage).To(Equal(name))
})
})
}
Describe("in an Ordered container", Ordered, func() {
BeforeAll(func() {
DeferCleanup(conf.SnapshotConfig())
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "ordered" })
})

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

@ -5,6 +5,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -13,8 +14,10 @@ import (
func TestAgents(t *testing.T) {
tests.Init(t, false)
log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Agents Test Suite")
}
var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

View file

@ -7,8 +7,10 @@ import (
"time"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/conf"
. "github.com/onsi/ginkgo/v2"
@ -42,11 +44,9 @@ var _ = Describe("Agents", func() {
var ctx context.Context
var cancel context.CancelFunc
var ds model.DataStore
var mfRepo *tests.MockMediaFileRepo
BeforeEach(func() {
ctx, cancel = context.WithCancel(context.Background())
mfRepo = tests.CreateMockMediaFileRepo()
ds = &tests.MockDataStore{MockedMediaFile: mfRepo}
ctx, cancel = context.WithCancel(GinkgoT().Context())
ds = persistence.New(db.Db())
})
Describe("Local", func() {
@ -57,8 +57,20 @@ var _ = Describe("Agents", func() {
})
It("calls the placeholder GetArtistImages", func() {
mfRepo.SetData(model.MediaFiles{{ID: "1", Title: "One"}, {ID: "2", Title: "Two"}})
songs, err := ag.GetArtistTopSongs(ctx, "123", "John Doe", "mb123", 2)
user := model.User{ID: "user-1", UserName: "user-1"}
Expect(ds.User().Put(ctx, &user)).To(Succeed())
ctx = request.WithUser(ctx, user)
putSongs(ctx, ds,
model.MediaFile{ID: "1", Title: "One", ArtistID: "123"},
model.MediaFile{ID: "2", Title: "Two", ArtistID: "123"},
model.MediaFile{ID: "3", Title: "Not a favourite", ArtistID: "123"},
model.MediaFile{ID: "4", Title: "Other artist", ArtistID: "456"},
)
Expect(ds.MediaFile().SetStar(ctx, true, "1", "4")).To(Succeed())
Expect(ds.MediaFile().SetRating(ctx, 5, "2")).To(Succeed())
Expect(ds.MediaFile().SetRating(ctx, 4, "3")).To(Succeed())
songs, err := ag.GetArtistTopSongs(ctx, "123", "John Doe", "mb123", 3)
Expect(err).ToNot(HaveOccurred())
Expect(songs).To(ConsistOf([]Song{{ID: "1", Name: "One"}, {ID: "2", Name: "Two"}}))
})

View file

@ -3,64 +3,66 @@ package agents
import (
"context"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/utils/slice"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("localAgent GetSimilarSongsByTrack", func() {
var ds *tests.MockDataStore
var mfRepo *tests.MockMediaFileRepo
var ds *getRandomSpy
var agent *localAgent
var ctx context.Context
rock := model.Tags{model.TagGenre: []string{"Rock"}}
BeforeEach(func() {
ctx = context.Background()
mfRepo = &tests.MockMediaFileRepo{}
ds = &tests.MockDataStore{MockedMediaFile: mfRepo}
ctx = GinkgoT().Context()
ds = &getRandomSpy{DataStore: persistence.New(db.Db())}
agent = &localAgent{ds: ds}
})
It("excludes the seed track from its own similars", func() {
seed := model.MediaFile{ID: "seed-1", Title: "Seed", Tags: model.Tags{model.TagGenre: []string{"Rock"}}}
related := model.MediaFile{ID: "rel-1", Title: "Related", Tags: model.Tags{model.TagGenre: []string{"Rock"}}}
// SetData keys by ID; a duplicate "seed-1" entry would clobber the real seed.
mfRepo.SetData(model.MediaFiles{seed, related})
putSongs(ctx, ds,
model.MediaFile{ID: "seed-1", Title: "Seed", Tags: rock},
model.MediaFile{ID: "rel-1", Title: "Related", Tags: rock},
)
songs, err := agent.GetSimilarSongsByTrack(ctx, "seed-1", "Seed", "", "", 10)
Expect(err).ToNot(HaveOccurred())
names := slice.Map(songs, func(s Song) string { return s.Name })
Expect(names).ToNot(ContainElement("Seed"))
Expect(names).To(ConsistOf("Related"))
})
// The mock ignores QueryOptions.Filters, so assert the predicate itself: otherwise this spec
// would pass just as well with no genre filter at all.
It("queries the indexed genre join for the seed's own genres, skipping missing files", func() {
rock := model.NewTag(model.TagGenre, "Rock")
seed := model.MediaFile{ID: "seed-4", Title: "Seed", Tags: model.Tags{model.TagGenre: []string{"Rock"}}}
mfRepo.SetData(model.MediaFiles{seed})
putSongs(ctx, ds,
model.MediaFile{ID: "seed-4", Title: "Seed", Tags: rock},
model.MediaFile{ID: "rock", Title: "Rock", Tags: rock},
model.MediaFile{ID: "jazz", Title: "Jazz", Tags: model.Tags{model.TagGenre: []string{"Jazz"}}},
model.MediaFile{ID: "gone", Title: "Missing Rock", Tags: rock, Missing: true},
)
_, err := agent.GetSimilarSongsByTrack(ctx, "seed-4", "Seed", "", "", 10)
songs, err := agent.GetSimilarSongsByTrack(ctx, "seed-4", "Seed", "", "", 10)
Expect(err).ToNot(HaveOccurred())
Expect(songs).To(ConsistOf(Song{ID: "rock", Name: "Rock"}))
sql, args, sqlErr := mfRepo.Options.Filters.ToSql()
Expect(ds.options).To(HaveLen(1))
sql, _, sqlErr := ds.options[0].Filters.ToSql()
Expect(sqlErr).ToNot(HaveOccurred())
Expect(sql).To(ContainSubstring("media_file_tags"), "must use the indexed join, not a json_tree scan")
Expect(sql).To(ContainSubstring("missing"))
Expect(args).To(ContainElement(false), "must exclude missing files, not select them")
Expect(args).To(ContainElement(rock.ID), "must filter on the seed's own genre tag id")
Expect(args).ToNot(ContainElement(model.NewTag(model.TagGenre, "Jazz").ID))
})
It("returns the library id so the matcher can resolve the song", func() {
seed := model.MediaFile{ID: "seed-3", Title: "Seed", Tags: model.Tags{model.TagGenre: []string{"Rock"}}}
// Without the id the matcher falls through to its MBID/title phases and resolves nothing,
// so the local fallback silently returns an empty mix.
related := model.MediaFile{ID: "rel-3", Title: "Related", Tags: model.Tags{model.TagGenre: []string{"Rock"}}}
mfRepo.SetData(model.MediaFiles{seed, related})
putSongs(ctx, ds,
model.MediaFile{ID: "seed-3", Title: "Seed", Tags: rock},
model.MediaFile{ID: "rel-3", Title: "Related", Tags: rock},
)
songs, err := agent.GetSimilarSongsByTrack(ctx, "seed-3", "Seed", "", "", 10)
@ -69,28 +71,63 @@ var _ = Describe("localAgent GetSimilarSongsByTrack", func() {
})
It("asks for one extra candidate so dropping the seed still fills the count", func() {
// The mock returns rows sorted by id, so the seed comes first and would consume the only
// slot if the query did not over-fetch.
seed := model.MediaFile{ID: "a-seed", Title: "Seed", Tags: model.Tags{model.TagGenre: []string{"Rock"}}}
related := model.MediaFile{ID: "b-rel", Title: "Related", Tags: model.Tags{model.TagGenre: []string{"Rock"}}}
mfRepo.SetData(model.MediaFiles{seed, related})
putSongs(ctx, ds,
model.MediaFile{ID: "a-seed", Title: "Seed", Tags: rock},
model.MediaFile{ID: "b-rel", Title: "Related", Tags: rock},
)
songs, err := agent.GetSimilarSongsByTrack(ctx, "a-seed", "Seed", "", "", 1)
// Candidates come back in random order, so repeat until the seed has surely been drawn first.
for range 20 {
songs, err := agent.GetSimilarSongsByTrack(ctx, "a-seed", "Seed", "", "", 1)
Expect(err).ToNot(HaveOccurred())
Expect(songs).To(HaveLen(1))
Expect(songs[0].Name).To(Equal("Related"))
Expect(err).ToNot(HaveOccurred())
Expect(songs).To(HaveLen(1))
Expect(songs[0].Name).To(Equal("Related"))
}
})
It("returns nil when the seed track has no genres", func() {
seed := model.MediaFile{ID: "seed-2", Title: "NoGenre"}
mfRepo.SetData(model.MediaFiles{seed})
putSongs(ctx, ds,
model.MediaFile{ID: "seed-2", Title: "NoGenre"},
model.MediaFile{ID: "other", Title: "Other", Tags: rock},
)
songs, err := agent.GetSimilarSongsByTrack(ctx, "seed-2", "NoGenre", "", "", 10)
Expect(err).ToNot(HaveOccurred())
Expect(songs).To(BeEmpty())
// Without the early return an empty tag filter would scan the whole library.
Expect(mfRepo.Options).To(Equal(model.QueryOptions{}), "must not query at all")
Expect(ds.options).To(BeEmpty(), "must not query at all")
})
})
// getRandomSpy records the options of every MediaFile().GetRandom call, which still reaches the real repository.
type getRandomSpy struct {
model.DataStore
options []model.QueryOptions
}
func (s *getRandomSpy) MediaFile() model.MediaFileRepository {
return getRandomSpyRepo{MediaFileRepository: s.DataStore.MediaFile(), spy: s}
}
type getRandomSpyRepo struct {
model.MediaFileRepository
spy *getRandomSpy
}
func (r getRandomSpyRepo) GetRandom(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) {
r.spy.options = append(r.spy.options, options...)
return r.MediaFileRepository.GetRandom(ctx, options...)
}
// putSongs stores the songs in library 1, along with the tags they carry.
func putSongs(ctx context.Context, ds model.DataStore, songs ...model.MediaFile) {
GinkgoHelper()
for _, mf := range songs {
if tags := mf.Tags.FlattenAll(); len(tags) > 0 {
Expect(ds.Tag().Add(ctx, model.DefaultLibraryID, tags...)).To(Succeed())
}
}
persistencetest.PutMediaFiles(ctx, ds, songs...)
}

View file

@ -3,32 +3,53 @@ package agents
import (
"context"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/persistence"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("SessionKeys", func() {
ctx := context.Background()
user := model.User{ID: "u-1"}
ds := &tests.MockDataStore{MockedUserProps: &tests.MockedUserPropsRepo{}}
sk := SessionKeys{DataStore: ds, KeyName: "fakeSessionKey"}
var ctx context.Context
var ds model.DataStore
var sk SessionKeys
user := model.User{ID: "u-1", UserName: "u-1"}
BeforeEach(func() {
ctx = GinkgoT().Context()
ds = persistence.New(db.Db())
Expect(ds.User().Put(ctx, &user)).To(Succeed())
sk = SessionKeys{DataStore: ds, KeyName: "fakeSessionKey"}
})
It("uses the assigned key name", func() {
Expect(sk.KeyName).To(Equal("fakeSessionKey"))
other := SessionKeys{DataStore: ds, KeyName: "otherSessionKey"}
Expect(sk.Put(ctx, user.ID, "mine")).To(Succeed())
Expect(other.Put(ctx, user.ID, "theirs")).To(Succeed())
Expect(sk.Get(ctx, user.ID)).To(Equal("mine"))
})
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())
Expect(ds.UserProps().Get(ctx, user.ID, "fakeSessionKey")).To(Equal("test-stored-value"))
})
It("fetches the stored value", func() {
Expect(ds.UserProps().Put(ctx, user.ID, "fakeSessionKey", "test-stored-value")).To(Succeed())
value, err := sk.Get(ctx, user.ID)
Expect(err).ToNot(HaveOccurred())
Expect(value).To(Equal("test-stored-value"))
})
It("deletes the stored value", func() {
Expect(sk.Delete(ctx, user.ID)).To(BeNil())
Expect(ds.UserProps().Put(ctx, user.ID, "fakeSessionKey", "test-stored-value")).To(Succeed())
Expect(sk.Delete(ctx, user.ID)).To(Succeed())
_, err := ds.UserProps().Get(ctx, user.ID, "fakeSessionKey")
Expect(err).To(MatchError(model.ErrNotFound))
})
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

@ -8,14 +8,16 @@ import (
"io"
"strings"
"github.com/Masterminds/squirrel"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core"
"github.com/navidrome/navidrome/core/artwork"
"github.com/navidrome/navidrome/core/stream"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/utils/slice"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/stretchr/testify/mock"
@ -23,61 +25,80 @@ import (
var _ = Describe("Archiver", func() {
var (
ctx context.Context
arch core.Archiver
ms *mockMediaStreamer
dc *fakeDecider
ds *mockDataStore
ds model.DataStore
sh *mockShare
ca *mockCoverArt
)
putTracks := func(mfs ...model.MediaFile) []string {
GinkgoHelper()
return slice.Map(persistencetest.PutMediaFiles(ctx, ds, mfs...), func(mf model.MediaFile) string { return mf.ID })
}
byArtist := func(id string, mfs ...model.MediaFile) []model.MediaFile {
for i := range mfs {
mfs[i].Participants = model.Participants{model.RoleAlbumArtist: {{ID: id, Name: "Artist " + id}}}
}
return mfs
}
putPlaylist := func(id, name string, tracks ...model.MediaFile) {
GinkgoHelper()
ids := putTracks(tracks...)
Expect(ds.Playlist().Put(ctx, &model.Playlist{ID: id, Name: name, OwnerID: "user-1"})).To(Succeed())
_, err := ds.Playlist().Tracks(ctx, id, false).Add(ctx, ids)
Expect(err).ToNot(HaveOccurred())
}
BeforeEach(func() {
ctx = GinkgoT().Context()
ds = persistence.New(db.Db())
user := model.User{ID: "user-1", UserName: "user-1"}
Expect(ds.User().Put(ctx, &user)).To(Succeed())
ctx = request.WithUser(ctx, user)
for _, id := range []string{"1", "2"} {
Expect(ds.Artist().Put(ctx, &model.Artist{ID: id, Name: "Artist " + id})).To(Succeed())
}
ms = &mockMediaStreamer{}
dc = &fakeDecider{}
sh = &mockShare{}
ds = &mockDataStore{}
ca = &mockCoverArt{images: map[string][]byte{}}
arch = core.NewArchiver(ms, dc, ds, sh, ca)
})
Context("ZipAlbum", func() {
It("zips an album correctly", func() {
mfs := model.MediaFiles{
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1},
{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1},
}
mfRepo := &mockMediaFileRepository{}
mfRepo.On("GetAll", []model.QueryOptions{{
Filters: squirrel.Eq{"album_id": "1"},
Sort: "album",
}}).Return(mfs, nil)
ds.On("MediaFile").Return(mfRepo)
putTracks(
model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1, TrackNumber: 2},
model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1, TrackNumber: 1},
model.MediaFile{Path: "other/01 - other.mp3", Suffix: "mp3", AlbumID: "2", Album: "Other", DiscNumber: 1},
)
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"))
})
It("streams the request resolved by the transcode decider and names the entry after its format", func() {
mfRepo := &mockMediaFileRepository{}
mfRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{{Path: "test_data/01 - track1.flac", Suffix: "flac", AlbumID: "1"}}, nil)
ds.On("MediaFile").Return(mfRepo)
putTracks(model.MediaFile{Path: "test_data/01 - track1.flac", Suffix: "flac", AlbumID: "1"})
resolved := stream.Request{Format: "opus", BitRate: 128, SampleRate: 48000, Channels: 2}
dc.resolved = &resolved
ms.On("NewStream", mock.Anything, mock.Anything, resolved).Return(io.NopCloser(strings.NewReader("test")), nil).Once()
out := new(bytes.Buffer)
Expect(arch.ZipAlbum(GinkgoT().Context(), "1", "mp3", 128, out)).To(Succeed())
Expect(arch.ZipAlbum(ctx, "1", "mp3", 128, out)).To(Succeed())
ms.AssertExpectations(GinkgoT())
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
@ -88,31 +109,24 @@ var _ = Describe("Archiver", func() {
Context("ZipArtist", func() {
It("zips an artist's albums correctly", func() {
mfs := model.MediaFiles{
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumArtistID: "1", AlbumID: "1", Album: "Album 1", DiscNumber: 1},
{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumArtistID: "1", AlbumID: "1", Album: "Album 1", DiscNumber: 1},
}
mfRepo := &mockMediaFileRepository{}
mfRepo.On("GetAll", []model.QueryOptions{{
Filters: squirrel.And{
persistence.ParticipantIDFilter("media_file", "1", model.RoleAlbumArtist),
squirrel.Eq{"missing": false},
},
Sort: "album",
}}).Return(mfs, nil)
ds.On("MediaFile").Return(mfRepo)
putTracks(byArtist("1",
model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, TrackNumber: 1},
model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, TrackNumber: 2},
model.MediaFile{Path: "test_data/03 - missing.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, TrackNumber: 3, Missing: true},
)...)
putTracks(byArtist("2",
model.MediaFile{Path: "other/01 - other.mp3", Suffix: "mp3", AlbumID: "2", Album: "Other", DiscNumber: 1},
)...)
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"))
})
@ -121,15 +135,13 @@ var _ = Describe("Archiver", func() {
// zipArtistEntries zips the given tracks as artist "1" and returns the entry names in zip order.
zipArtistEntries := func(mfs model.MediaFiles) []string {
mfRepo := &mockMediaFileRepository{}
mfRepo.On("GetAll", mock.Anything).Return(mfs, nil)
ds.On("MediaFile", mock.Anything).Return(mfRepo)
putTracks(byArtist("1", mfs...)...)
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
@ -139,10 +151,10 @@ var _ = Describe("Archiver", func() {
It("keeps the albums in query order", func() {
names := zipArtistEntries(model.MediaFiles{
{Path: "a/01.mp3", Suffix: "mp3", AlbumID: "3", Album: "Album C"},
{Path: "a/01.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album A"},
{Path: "a/02.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album A"},
{Path: "a/01.mp3", Suffix: "mp3", AlbumID: "2", Album: "Album B"},
{Path: "c/01.mp3", Suffix: "mp3", AlbumID: "3", Album: "Album C", OrderAlbumName: "1"},
{Path: "a/01.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album A", OrderAlbumName: "2", TrackNumber: 1},
{Path: "a/02.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album A", OrderAlbumName: "2", TrackNumber: 2},
{Path: "b/01.mp3", Suffix: "mp3", AlbumID: "2", Album: "Album B", OrderAlbumName: "3"},
})
Expect(names).To(Equal([]string{"Album C/01.mp3", "Album A/01.mp3", "Album A/02.mp3", "Album B/01.mp3"}))
})
@ -251,23 +263,16 @@ var _ = Describe("Archiver", func() {
Context("when the transcode limiter rejects a file", func() {
It("aborts the archive instead of continuing with empty entries", func() {
mfs := model.MediaFiles{
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1},
{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1},
}
mfRepo := &mockMediaFileRepository{}
mfRepo.On("GetAll", []model.QueryOptions{{
Filters: squirrel.Eq{"album_id": "1"},
Sort: "album",
}}).Return(mfs, nil)
ds.On("MediaFile").Return(mfRepo)
putTracks(
model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1, TrackNumber: 1},
model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1, TrackNumber: 2},
)
ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).
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 +298,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"))
@ -312,17 +317,14 @@ 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"}},
}}
plRepo := &mockPlaylistRepository{}
plRepo.On("GetWithTracks", "1", true, false).Return(pls, nil)
ds.On("Playlist").Return(plRepo)
putPlaylist("1", "Test Playlist",
model.MediaFile{Path: "test_data/01 - track1.flac", Suffix: "flac", Artist: "Artist 1", Title: "track1"},
)
dc.resolved = &stream.Request{Format: "opus", BitRate: 128}
ms.On("NewStream", mock.Anything, mock.Anything, *dc.resolved).Return(io.NopCloser(strings.NewReader("test")), nil)
out := new(bytes.Buffer)
Expect(arch.ZipPlaylist(GinkgoT().Context(), "1", "mp3", 128, out)).To(Succeed())
Expect(arch.ZipPlaylist(ctx, "1", "mp3", 128, out)).To(Succeed())
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
Expect(err).ToNot(HaveOccurred())
@ -336,41 +338,31 @@ 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"}},
}
pls := &model.Playlist{
ID: "1",
Name: "Test Playlist",
Tracks: tracks,
}
plRepo := &mockPlaylistRepository{}
plRepo.On("GetWithTracks", "1", true, false).Return(pls, nil)
ds.On("Playlist").Return(plRepo)
putPlaylist("1", "Test Playlist",
model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "AC/DC", Title: "track1"},
model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "Artist 2", Title: "track2"},
)
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))
@ -382,21 +374,18 @@ var _ = Describe("Archiver", func() {
pngData = []byte("\x89PNG\x0d\x0a\x1a\x0a fake png")
)
mockAlbumTracks := func(filter squirrel.Sqlizer, mfs model.MediaFiles) {
mfRepo := &mockMediaFileRepository{}
mfRepo.On("GetAll", []model.QueryOptions{{Filters: filter, Sort: "album"}}).Return(mfs, nil)
ds.On("MediaFile", mock.Anything).Return(mfRepo)
putAlbumTracks := func(mfs ...model.MediaFile) {
GinkgoHelper()
putTracks(mfs...)
ms.On("NewStream", mock.Anything, mock.Anything, mock.Anything).Return(io.NopCloser(strings.NewReader("test")), nil)
}
It("adds the album cover to the album folder", func() {
ca.images["al-1"] = jpegData
mockAlbumTracks(squirrel.Eq{"album_id": "1"}, model.MediaFiles{
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1},
})
putAlbumTracks(model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1})
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))
@ -408,16 +397,13 @@ var _ = Describe("Archiver", func() {
ca.images["ar-1"] = pngData
ca.images["al-1"] = jpegData
ca.images["al-2"] = jpegData
mockAlbumTracks(squirrel.And{
persistence.ParticipantIDFilter("media_file", "1", model.RoleAlbumArtist),
squirrel.Eq{"missing": false},
}, model.MediaFiles{
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1},
{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "2", Album: "Album 2", DiscNumber: 1},
})
putAlbumTracks(byArtist("1",
model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1},
model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "2", Album: "Album 2", DiscNumber: 1},
)...)
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))
@ -429,16 +415,13 @@ var _ = Describe("Archiver", func() {
It("puts each same-named album's cover in that album's own folder", func() {
ca.images["al-1"] = jpegData
ca.images["al-2"] = pngData
mockAlbumTracks(squirrel.And{
persistence.ParticipantIDFilter("media_file", "1", model.RoleAlbumArtist),
squirrel.Eq{"missing": false},
}, model.MediaFiles{
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Greatest Hits", Year: 2001, DiscNumber: 1},
{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "2", Album: "Greatest Hits", Year: 2005, DiscNumber: 1},
})
putAlbumTracks(byArtist("1",
model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Greatest Hits", Year: 2001, DiscNumber: 1},
model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "2", Album: "Greatest Hits", Year: 2005, DiscNumber: 1},
)...)
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))
@ -447,19 +430,13 @@ var _ = Describe("Archiver", func() {
It("adds the playlist cover to the root", func() {
ca.images["pl-1"] = jpegData
plRepo := &mockPlaylistRepository{}
plRepo.On("GetWithTracks", "1", true, false).Return(&model.Playlist{
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"}},
},
}, nil)
ds.On("Playlist", mock.Anything).Return(plRepo)
putPlaylist("1", "Test Playlist",
model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Artist: "Artist 1", Title: "track1"},
)
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 +460,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))
@ -493,12 +470,10 @@ var _ = Describe("Archiver", func() {
It("still builds the archive when the cover cannot be read", func() {
ca.err = errors.New("boom")
mockAlbumTracks(squirrel.Eq{"album_id": "1"}, model.MediaFiles{
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1},
})
putAlbumTracks(model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1})
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))
@ -549,54 +524,6 @@ func (m *mockCoverArt) Get(ctx context.Context, artID model.ArtworkID, size int,
return &artwork.Image{ReadCloser: io.NopCloser(bytes.NewReader(data))}, nil
}
type mockDataStore struct {
mock.Mock
model.DataStore
}
func (m *mockDataStore) MediaFile() model.MediaFileRepository {
args := m.Called()
return args.Get(0).(model.MediaFileRepository)
}
func (m *mockDataStore) Playlist() model.PlaylistRepository {
args := m.Called()
return args.Get(0).(model.PlaylistRepository)
}
func (m *mockDataStore) Library() model.LibraryRepository {
return &mockLibraryRepository{}
}
type mockLibraryRepository struct {
mock.Mock
model.LibraryRepository
}
func (m *mockLibraryRepository) GetPath(_ context.Context, id int) (string, error) {
return "/music", nil
}
type mockMediaFileRepository struct {
mock.Mock
model.MediaFileRepository
}
func (m *mockMediaFileRepository) GetAll(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) {
args := m.Called(options)
return args.Get(0).(model.MediaFiles), args.Error(1)
}
type mockPlaylistRepository struct {
mock.Mock
model.PlaylistRepository
}
func (m *mockPlaylistRepository) GetWithTracks(_ context.Context, id string, refreshSmartPlaylists, includeMissing bool) (*model.Playlist, error) {
args := m.Called(id, refreshSmartPlaylists, includeMissing)
return args.Get(0).(*model.Playlist), args.Error(1)
}
type mockMediaStreamer struct {
mock.Mock
stream.MediaStreamer

View file

@ -13,8 +13,9 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/utils/str"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -65,7 +66,7 @@ func imageAgents(fakes ...*fakeImageAgent) *agents.Agents {
names = append(names, fake.name)
}
conf.Update(func(c *conf.Options) { c.Agents = strings.Join(names, ",") })
return agents.GetAgents(&tests.MockDataStore{}, nil)
return agents.GetAgents(persistence.New(db.Db()), nil)
}
var _ = Describe("agent images", func() {
@ -75,7 +76,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

@ -1,7 +1,9 @@
package artwork
import (
"cmp"
"context"
"errors"
"io/fs"
"net/netip"
"net/url"
@ -14,9 +16,13 @@ import (
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/core/storage"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/metadata"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/utils/httpclient"
. "github.com/onsi/ginkgo/v2"
@ -27,22 +33,27 @@ import (
func TestArtwork(t *testing.T) {
// Runs unconditionally: the two leaks below are pre-existing and out of this
// package's control, so they're ignored by exact top-function instead.
defer goleak.VerifyNone(t,
goleak.IgnoreTopFunction("github.com/onsi/ginkgo/v2/internal/interrupt_handler.(*InterruptHandler).registerForInterrupts.func2"),
// notify's own init() starts a singleton tree the moment it's imported (via
// core/storage/local or plugins); recursive on darwin, nonrecursive on linux.
goleak.IgnoreTopFunction("github.com/rjeczalik/notify.(*recursiveTree).dispatch"),
goleak.IgnoreTopFunction("github.com/rjeczalik/notify.(*nonrecursiveTree).dispatch"),
goleak.IgnoreTopFunction("github.com/rjeczalik/notify.(*nonrecursiveTree).internal"),
)
// A cleanup rather than a defer, so it runs after persistencetest closes the database.
t.Cleanup(func() {
goleak.VerifyNone(t,
goleak.IgnoreTopFunction("github.com/onsi/ginkgo/v2/internal/interrupt_handler.(*InterruptHandler).registerForInterrupts.func2"),
// notify's own init() starts a singleton tree the moment it's imported (via
// core/storage/local or plugins); recursive on darwin, nonrecursive on linux.
goleak.IgnoreTopFunction("github.com/rjeczalik/notify.(*recursiveTree).dispatch"),
goleak.IgnoreTopFunction("github.com/rjeczalik/notify.(*nonrecursiveTree).dispatch"),
goleak.IgnoreTopFunction("github.com/rjeczalik/notify.(*nonrecursiveTree).internal"),
)
})
tests.Init(t, false)
log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Artwork Suite")
}
var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()
// productionImageClient keeps the guarded client for the specs that assert it refuses loopback.
var productionImageClient = remoteImageClient
@ -97,36 +108,103 @@ func (s *osDirStorage) FS() (storage.MusicFS, error) {
return osDirFS{os.DirFS(s.root)}, nil
}
// fakeFolderRepo covers the three FolderRepository methods the resolvers reach for. The zero value
// answers as an unremarkable library does; the fields drive the album-root lookup and its failures.
type fakeFolderRepo struct {
model.FolderRepository
result []model.Folder
err error
parentResult *model.Folder
getErr error
getCallCount int
// hasOtherAudio is returned by HasAudioOutsideFolders (the album-root check).
// False means the parent qualifies as an album root.
hasOtherAudio bool
otherAudioErr error
// fixtureAlbumDir is relative to the repo root, which tests.Init makes the working directory.
const fixtureAlbumDir = "tests/fixtures/artist/an-album"
var testAdmin = model.User{ID: "admin-1", UserName: "admin", IsAdmin: true}
func asAdmin(ctx context.Context) context.Context {
return request.WithUser(ctx, testAdmin)
}
func (f *fakeFolderRepo) GetAll(context.Context, ...model.QueryOptions) ([]model.Folder, error) {
return f.result, f.err
// newTestDS returns a store over the suite database, with testAdmin stored.
func newTestDS(ctx context.Context) model.DataStore {
GinkgoHelper()
ds := persistence.New(db.Db())
admin := testAdmin
Expect(ds.User().Put(ctx, &admin)).To(Succeed())
return ds
}
func (f *fakeFolderRepo) HasAudioOutsideFolders(context.Context, model.Folder, []string) (bool, error) {
return f.hasOtherAudio, f.otherAudioErr
// useLibrary moves library 1 to root, read through the testfile scheme.
func useLibrary(ctx context.Context, ds model.DataStore, root string) {
GinkgoHelper()
persistencetest.SetLibraries(ctx, ds, testFileLibPath(root))
}
func (f *fakeFolderRepo) Get(context.Context, string) (*model.Folder, error) {
f.getCallCount++
if f.getErr != nil {
return nil, f.getErr
// putFolder stores library 1's folder at rel holding images, and returns its ID.
func putFolder(ctx context.Context, ds model.DataStore, rel string, images ...string) string {
GinkgoHelper()
lib, err := ds.Library().Get(ctx, model.DefaultLibraryID)
Expect(err).ToNot(HaveOccurred())
f := model.NewFolder(*lib, rel)
f.ImageFiles = images
f.ImagesUpdatedAt = time.Now().Truncate(time.Second)
Expect(ds.Folder().Put(ctx, f)).To(Succeed())
return f.ID
}
// putArtistAlbums stores the artist and makes it the sole album artist of albums.
func putArtistAlbums(ctx context.Context, ds model.DataStore, ar model.Artist, albums ...model.Album) {
GinkgoHelper()
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, ar)
for i := range albums {
albums[i].Participants = model.Participants{model.RoleAlbumArtist: {{Artist: ar}}}
}
if f.parentResult != nil {
return f.parentResult, nil
}
return nil, model.ErrNotFound
persistencetest.PutAlbums(ctx, ds, albums...)
}
// putRadio stores the radio without the artwork request its Put enqueues.
func putRadio(ctx context.Context, ds model.DataStore, rd model.Radio) {
GinkgoHelper()
Expect(ds.Radio().Put(asAdmin(ctx), &rd)).To(Succeed())
unqueue(model.KindRadioArtwork, rd.ID)
}
// putPlaylist stores a testAdmin playlist with one track per album, without the cover rebuild its
// Put enqueues.
func putPlaylist(ctx context.Context, ds model.DataStore, pls model.Playlist, albumIDs ...string) {
GinkgoHelper()
pls.OwnerID = cmp.Or(pls.OwnerID, testAdmin.ID)
for _, albumID := range albumIDs {
mf := model.MediaFile{ID: pls.ID + "-" + albumID, AlbumID: albumID, Path: pls.ID + "/" + albumID + ".mp3"}
persistencetest.PutMediaFiles(ctx, ds, mf)
pls.Tracks = append(pls.Tracks, model.PlaylistTrack{MediaFileID: mf.ID, MediaFile: mf})
}
Expect(ds.Playlist().Put(asAdmin(ctx), &pls)).To(Succeed())
unqueue(model.KindPlaylistArtwork, pls.ID)
}
func unqueue(kind model.Kind, id string) {
GinkgoHelper()
_, err := db.Db().Exec("DELETE FROM artwork_queue WHERE item_kind = ? AND item_id = ?", kind.Prefix(), id)
Expect(err).ToNot(HaveOccurred())
}
// queued returns the primary image's queue row, or nil when there is none.
func queued(ctx context.Context, ds model.DataStore, kind, id string) *model.ArtworkQueueItem {
GinkgoHelper()
k, ok := model.ParseKind(kind)
Expect(ok).To(BeTrue(), kind)
it, err := ds.ArtworkQueue().Get(ctx, k, id, model.ImageTypePrimary)
if errors.Is(err, model.ErrNotFound) {
return nil
}
Expect(err).ToNot(HaveOccurred())
return it
}
func queueCount(ctx context.Context, ds model.DataStore) int64 {
GinkgoHelper()
n, err := ds.ArtworkQueue().Count(ctx)
Expect(err).ToNot(HaveOccurred())
return n
}
// expireQueued ages a row past the retry budget, so the next drain settles it instead of retrying.
func expireQueued(kind, id string) {
GinkgoHelper()
_, err := db.Db().Exec("UPDATE artwork_queue SET enqueued_at = ? WHERE item_kind = ? AND item_id = ?",
time.Now().Add(-(giveUpAfter + time.Hour)), kind, id)
Expect(err).ToNot(HaveOccurred())
}

View file

@ -3,6 +3,7 @@ package artwork
import (
"bytes"
"context"
"errors"
"image"
"io"
"os"
@ -11,7 +12,9 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/resources"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/utils/cache"
@ -22,13 +25,8 @@ import (
var _ = Describe("Artwork", func() {
var (
ctx context.Context
ds *tests.MockDataStore
artRepo *tests.MockArtworkRepo
queueRepo *tests.MockArtworkQueueRepo
albumRepo *tests.MockAlbumRepo
mfRepo *tests.MockMediaFileRepo
folderRepo *fakeFolderRepo
libRepo *tests.MockLibraryRepo
ds model.DataStore
artRepo model.ArtworkRepository
ffm *tests.MockFFmpeg
store *ImageStore
imgCache cache.FileCache
@ -38,7 +36,18 @@ var _ = Describe("Artwork", func() {
seedEntity func(kind, id string)
)
primaryKey := func(kind, id string) string { return kind + "|" + id + "|" + model.ImageTypePrimary }
queuedPriority := func(kind, id string) int {
GinkgoHelper()
it := queued(ctx, ds, kind, id)
Expect(it).ToNot(BeNil(), "%s-%s must be queued", kind, id)
return it.Priority
}
setImagesUpdatedAt := func(folderID string, t time.Time) {
GinkgoHelper()
_, err := db.Db().Exec("UPDATE folder SET images_updated_at = ? WHERE id = ?", t, folderID)
Expect(err).ToNot(HaveOccurred())
}
seedFoundStore := func(kind, id string, imgBytes []byte) string {
hash, err := hashImage(bytes.NewReader(imgBytes))
@ -50,14 +59,19 @@ var _ = Describe("Artwork", func() {
return hash
}
// Without its owning entity, a state row is not served at all.
// Without its owning entity, a state row is not served at all. An entity a spec already
// stored is kept as is.
seedEntity = func(kind, id string) {
GinkgoHelper()
switch kind {
case "al":
Expect(albumRepo.Put(ctx, &model.Album{ID: id, Name: "Album"})).To(Succeed())
if _, err := ds.Album().Get(ctx, id); errors.Is(err, model.ErrNotFound) {
persistencetest.PutAlbums(ctx, ds, model.Album{ID: id, Name: "Album"})
}
case "mf":
Expect(mfRepo.Put(ctx, &model.MediaFile{ID: id})).To(Succeed())
if _, err := ds.MediaFile().Get(ctx, id); errors.Is(err, model.ErrNotFound) {
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: id, Path: id + ".mp3"})
}
}
}
@ -70,7 +84,7 @@ var _ = Describe("Artwork", func() {
}
BeforeEach(func() {
ctx = context.Background()
ctx = GinkgoT().Context()
var err error
repoRoot, err = os.Getwd()
Expect(err).ToNot(HaveOccurred())
@ -85,21 +99,9 @@ var _ = Describe("Artwork", func() {
c.CacheFolder = conf.NewDir(GinkgoT().TempDir())
})
artRepo = tests.CreateMockArtworkRepo()
queueRepo = tests.CreateMockArtworkQueueRepo()
albumRepo = tests.CreateMockAlbumRepo()
mfRepo = tests.CreateMockMediaFileRepo()
folderRepo = &fakeFolderRepo{}
libRepo = &tests.MockLibraryRepo{}
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}})
ds = &tests.MockDataStore{
MockedArtwork: artRepo,
MockedArtworkQueue: queueRepo,
MockedAlbum: albumRepo,
MockedMediaFile: mfRepo,
MockedFolder: folderRepo,
MockedLibrary: libRepo,
}
ds = newTestDS(ctx)
useLibrary(ctx, ds, repoRoot)
artRepo = ds.Artwork()
ffm = tests.NewMockFFmpeg("")
store = NewImageStore(GinkgoT().TempDir())
imgCache = cache.NewFileCache("ServingTest", "100MB", "images", 0,
@ -114,7 +116,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 +130,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 +139,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 +156,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,9 +172,9 @@ 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))
Expect(queuedPriority("al", "alni")).To(Equal(model.ArtworkPriorityScan))
})
It("refuses a non-image file-backed row even when a resized copy is already cached", func() {
@ -201,9 +203,9 @@ 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))
Expect(queuedPriority("al", "alnic")).To(Equal(model.ArtworkPriorityScan))
})
It("treats a full-size mtime mismatch as dangling: unavailable, re-enqueued at Scan, state untouched", func() {
@ -217,9 +219,9 @@ 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))
Expect(queuedPriority("al", "al3")).To(Equal(model.ArtworkPriorityScan))
ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al3", model.ImageTypePrimary)
Expect(err).ToNot(HaveOccurred())
Expect(ia.Hash).To(Equal("bbbbbbbbbbbbbbbb"))
@ -236,18 +238,19 @@ 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))
Expect(queuedPriority("al", "al3b")).To(Equal(model.ArtworkPriorityScan))
})
// State rows outlive a deleted entity until the next prune.
It("refuses to serve a found row whose entity is gone", func() {
hash := seedFoundStore("al", "alzz", coverBytes)
Expect(hash).ToNot(BeEmpty())
albumRepo.SetData(model.Albums{}) // the album is deleted; its artwork row survives
_, err := db.Db().Exec("DELETE FROM album WHERE id = ?", "alzz") // its artwork row survives
Expect(err).ToNot(HaveOccurred())
_, 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,33 +259,32 @@ 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())
Expect(queueCount(ctx, ds)).To(BeZero())
})
})
Describe("provisional read-through", func() {
It("serves local folder art, enqueues a Bump, and writes no state row", 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"}}})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al5", Name: "Album", FolderIDs: []string{fid}})
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))
Expect(queueRepo.Data[primaryKey("al", "al5")].Priority).To(Equal(model.ArtworkPriorityBump))
Expect(queuedPriority("al", "al5")).To(Equal(model.ArtworkPriorityBump))
_, err = artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al5", model.ImageTypePrimary)
Expect(err).To(MatchError(model.ErrNotFound))
})
It("returns ErrUnavailable and enqueues a Bump when nothing local resolves", func() {
folderRepo.result = nil
albumRepo.SetData(model.Albums{{ID: "al6", Name: "Album"}})
persistencetest.PutAlbums(ctx, ds, model.Album{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))
Expect(queuedPriority("al", "al6")).To(Equal(model.ArtworkPriorityBump))
_, err = artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al6", model.ImageTypePrimary)
Expect(err).To(MatchError(model.ErrNotFound))
})
@ -292,7 +294,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))
})
@ -301,9 +303,9 @@ var _ = Describe("Artwork", func() {
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false })
seedFoundStore("mf", "mf7", []byte("stale embedded track art"))
seedFoundStore("al", "albz", coverBytes)
mfRepo.SetData(model.MediaFiles{{ID: "mf7", AlbumID: "albz"}})
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf7", AlbumID: "albz", Path: "mf7.mp3"})
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")
})
@ -311,49 +313,46 @@ var _ = Describe("Artwork", func() {
It("delegates to the album when the track's state is absent", func() {
seedFoundStore("al", "albm", coverBytes)
Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "mf", ItemID: "mf2"})).To(Succeed())
mfRepo.SetData(model.MediaFiles{{ID: "mf2", AlbumID: "albm"}})
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf2", AlbumID: "albm", Path: "mf2.mp3"})
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")]
Expect(mfEnq).To(BeFalse())
Expect(queued(ctx, ds, "mf", "mf2")).To(BeNil())
})
It("delegates to the album (no enqueue) when the track is not embedded-eligible", func() {
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
seedFoundStore("al", "albn", coverBytes)
mfRepo.SetData(model.MediaFiles{{ID: "mf3", AlbumID: "albn", HasCoverArt: false}})
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf3", AlbumID: "albn", Path: "mf3.mp3", 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")]
Expect(mfEnq).To(BeFalse())
Expect(queued(ctx, ds, "mf", "mf3")).To(BeNil())
})
It("extracts embedded art provisionally and enqueues the track when eligible", func() {
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
mfRepo.SetData(model.MediaFiles{{
ID: "mf4", AlbumID: "albo", HasCoverArt: true,
Path: "tests/fixtures/artist/an-album/test.mp3", LibraryID: 0,
}})
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{
ID: "mf4", AlbumID: "albo", HasCoverArt: true, Path: fixtureAlbumDir + "/test.mp3",
})
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(queueRepo.Data[primaryKey("mf", "mf4")].Priority).To(Equal(model.ArtworkPriorityBump))
Expect(readAll(img)).ToNot(BeEmpty())
Expect(queuedPriority("mf", "mf4")).To(Equal(model.ArtworkPriorityBump))
_, err = artRepo.GetItemArtwork(ctx, model.KindMediaFileArtwork, "mf4", model.ImageTypePrimary)
Expect(err).To(MatchError(model.ErrNotFound))
})
It("delegates a multi-disc track to its disc art, not straight to the album", func() {
folderRepo.result = []model.Folder{{Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"}}}
albumRepo.SetData(model.Albums{{ID: "aldd", Name: "Album", FolderIDs: []string{"f1"}, Discs: model.Discs{1: "One", 2: "Two"}}})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "aldd", Name: "Album", FolderIDs: []string{fid}, Discs: model.Discs{1: "One", 2: "Two"}})
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}})
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf5", AlbumID: "aldd", DiscNumber: 1, FolderID: fid, Path: fixtureAlbumDir + "/test.mp3", 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))
@ -362,26 +361,25 @@ var _ = Describe("Artwork", func() {
It("falls back to the album when an eligible track's embedded art will not extract", func() {
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
// HasCoverArt is set, but the file is not audio, so nothing extracts.
mfRepo.SetData(model.MediaFiles{{
ID: "mfbad", AlbumID: "albad", LibraryID: 0, HasCoverArt: true,
Path: "tests/fixtures/artist/an-album/front.png",
}})
albumRepo.SetData(model.Albums{{ID: "albad", Name: "Album"}})
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{
ID: "mfbad", AlbumID: "albad", HasCoverArt: true, Path: fixtureAlbumDir + "/front.png",
})
persistencetest.PutAlbums(ctx, ds, model.Album{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")
})
It("routes a single-disc track through disc resolution too", func() {
// DiscArtPriority applies to single-disc albums too, over the album's own found art.
folderRepo.result = []model.Folder{{Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"}}}
albumRepo.SetData(model.Albums{{ID: "alsd", Name: "Album", FolderIDs: []string{"f1"}, Discs: model.Discs{1: ""}}})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alsd", Name: "Album", FolderIDs: []string{fid}, Discs: model.Discs{1: ""}})
seedFoundStore("al", "alsd", []byte("album-art-distinct"))
mfRepo.SetData(model.MediaFiles{{ID: "mf6", AlbumID: "alsd", DiscNumber: 1, HasCoverArt: false}})
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf6", AlbumID: "alsd", DiscNumber: 1, FolderID: fid, Path: fixtureAlbumDir + "/test.mp3", 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))
})
@ -389,8 +387,8 @@ var _ = Describe("Artwork", func() {
Describe("disc", func() {
It("serves a local disc-folder image", func() {
folderRepo.result = []model.Folder{{Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"}}}
albumRepo.SetData(model.Albums{{ID: "aldc", Name: "Album", FolderIDs: []string{"f1"}}})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "aldc", Name: "Album", FolderIDs: []string{fid}})
img, err := svc.Get(ctx, model.NewArtworkID(model.KindDiscArtwork, model.DiscArtworkID("aldc", 1), nil), 0, false)
Expect(err).ToNot(HaveOccurred())
@ -400,8 +398,8 @@ var _ = Describe("Artwork", func() {
// The resize cache keys on id + album mtime, not on the bytes, so dropping the source
// between the two requests is what shows a warm hit never touches the filesystem.
It("serves a sized disc image from cache without re-reading the source", func() {
folderRepo.result = []model.Folder{{Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"}}}
albumRepo.SetData(model.Albums{{ID: "aldc3", Name: "Album", FolderIDs: []string{"f1"}}})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "aldc3", Name: "Album", FolderIDs: []string{fid}})
discID := model.NewArtworkID(model.KindDiscArtwork, model.DiscArtworkID("aldc3", 1), nil)
first, err := svc.Get(ctx, discID, 64, false)
@ -409,7 +407,9 @@ var _ = Describe("Artwork", func() {
warmed := readAll(first)
Expect(warmed).ToNot(BeEmpty())
folderRepo.result = nil
// Unlisting the images leaves the cache key alone, so only a cache hit can still serve.
_, err = db.Db().Exec("UPDATE folder SET image_files = '[]' WHERE id = ?", fid)
Expect(err).ToNot(HaveOccurred())
second, err := svc.Get(ctx, discID, 64, false)
Expect(err).ToNot(HaveOccurred())
@ -418,11 +418,9 @@ var _ = Describe("Artwork", func() {
// A disc image can change without the album row changing, so the key folds in ImagesUpdatedAt.
It("invalidates the cached image when the folder's images change", func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"},
ImagesUpdatedAt: time.Now().Add(-time.Hour),
}}
albumRepo.SetData(model.Albums{{ID: "aldc4", Name: "Album", FolderIDs: []string{"f1"}}})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
setImagesUpdatedAt(fid, time.Now().Add(-time.Hour))
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "aldc4", Name: "Album", FolderIDs: []string{fid}})
discID := model.NewArtworkID(model.KindDiscArtwork, model.DiscArtworkID("aldc4", 1), nil)
first, err := svc.Get(ctx, discID, 64, false)
@ -430,7 +428,7 @@ var _ = Describe("Artwork", func() {
firstKey := first.ETag
readAll(first)
folderRepo.result[0].ImagesUpdatedAt = time.Now()
setImagesUpdatedAt(fid, time.Now().Add(time.Hour))
second, err := svc.Get(ctx, discID, 64, false)
Expect(err).ToNot(HaveOccurred())
readAll(second)
@ -439,11 +437,9 @@ var _ = Describe("Artwork", func() {
// Disc art has no content hash, so without an explicit validator every ETag would be empty.
It("gives a full-size disc image a validator that tracks the source", func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"},
ImagesUpdatedAt: time.Now().Add(-time.Hour),
}}
albumRepo.SetData(model.Albums{{ID: "aldc5", Name: "Album", FolderIDs: []string{"f1"}}})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
setImagesUpdatedAt(fid, time.Now().Add(-time.Hour))
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "aldc5", Name: "Album", FolderIDs: []string{fid}})
discID := model.NewArtworkID(model.KindDiscArtwork, model.DiscArtworkID("aldc5", 1), nil)
first, err := svc.Get(ctx, discID, 0, false)
@ -451,7 +447,7 @@ var _ = Describe("Artwork", func() {
readAll(first)
Expect(first.ETag).ToNot(BeEmpty())
folderRepo.result[0].ImagesUpdatedAt = time.Now()
setImagesUpdatedAt(fid, time.Now().Add(time.Hour))
second, err := svc.Get(ctx, discID, 0, false)
Expect(err).ToNot(HaveOccurred())
readAll(second)
@ -459,8 +455,7 @@ var _ = Describe("Artwork", func() {
})
It("falls back to album art when no disc image matches", func() {
folderRepo.result = nil
albumRepo.SetData(model.Albums{{ID: "aldc2", Name: "Album"}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "aldc2", Name: "Album"})
seedFoundStore("al", "aldc2", coverBytes)
img, err := svc.Get(ctx, model.NewArtworkID(model.KindDiscArtwork, model.DiscArtworkID("aldc2", 1), nil), 0, false)
@ -471,7 +466,7 @@ var _ = Describe("Artwork", func() {
Describe("GetOrPlaceholder", func() {
It("accepts a raw entity id and serves its cover art", func() {
albumRepo.SetData(model.Albums{{ID: "rawal", Name: "Album"}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "rawal", Name: "Album"})
seedFoundStore("al", "rawal", coverBytes)
img, err := svc.GetOrPlaceholder(ctx, "rawal", 0, false)
@ -526,22 +521,19 @@ func fileMtime(path string) int64 {
var _ = Describe("EntityExists", func() {
var ctx context.Context
var ds *tests.MockDataStore
var ds model.DataStore
BeforeEach(func() {
ctx = context.Background()
albumRepo := tests.CreateMockAlbumRepo()
albumRepo.SetData(model.Albums{{ID: "al1"}})
artistRepo := tests.CreateMockArtistRepo()
artistRepo.SetData(model.Artists{{ID: "ar1"}})
radioRepo := tests.CreateMockedRadioRepo()
Expect(radioRepo.Put(ctx, &model.Radio{ID: "ra1", Name: "R"})).To(Succeed())
ds = &tests.MockDataStore{MockedAlbum: albumRepo, MockedArtist: artistRepo, MockedRadio: radioRepo}
ctx = GinkgoT().Context()
ds = newTestDS(ctx)
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album"})
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar1", Name: "Artist"})
putRadio(ctx, ds, model.Radio{ID: "ra1", Name: "R"})
})
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

@ -13,9 +13,14 @@ import (
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/artwork"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/server/events"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/tests/harness"
"github.com/navidrome/navidrome/utils/cache"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -25,22 +30,31 @@ import (
var _ = Describe("Acquisition → serve loop", func() {
var (
ctx context.Context
ds *tests.MockDataStore
artRepo *tests.MockArtworkRepo
queueRepo *tests.MockArtworkQueueRepo
albumRepo *tests.MockAlbumRepo
artistRepo *tests.MockArtistRepo
mfRepo *tests.MockMediaFileRepo
plRepo *tests.MockPlaylistRepo
radioRepo *tests.MockedRadioRepo
folderRepo *fakeFolderRepo
libRepo *tests.MockLibraryRepo
ds model.DataStore
artRepo model.ArtworkRepository
store *artwork.ImageStore
svc artwork.Artwork
worker *artwork.Worker
coverBytes []byte
)
// Requests carry a user, the worker resolves as the first admin, and only admins may store
// radios and playlists, so every call runs as this admin.
admin := model.User{ID: "admin-1", UserName: "admin", IsAdmin: true}
putFolder := func(rel string, images ...string) string {
GinkgoHelper()
lib, err := ds.Library().Get(ctx, model.DefaultLibraryID)
Expect(err).ToNot(HaveOccurred())
f := model.NewFolder(*lib, rel)
f.ImageFiles = images
Expect(ds.Folder().Put(ctx, f)).To(Succeed())
return f.ID
}
putRadio := func(rd model.Radio) {
GinkgoHelper()
Expect(ds.Radio().Put(ctx, &rd)).To(Succeed())
}
itemFound := func(kind model.Kind, id string) func() bool {
return func() bool {
ia, err := artRepo.GetItemArtwork(ctx, kind, id, model.ImageTypePrimary)
@ -63,7 +77,7 @@ var _ = Describe("Acquisition → serve loop", func() {
}
BeforeEach(func() {
ctx = context.Background()
ctx = request.WithUser(GinkgoT().Context(), admin)
repoRoot, err := os.Getwd()
Expect(err).ToNot(HaveOccurred())
coverBytes = readFixture(coverFixture)
@ -77,28 +91,12 @@ var _ = Describe("Acquisition → serve loop", func() {
c.DevArtworkWorkerConcurrency = 1
})
folderRepo = &fakeFolderRepo{}
libRepo = &tests.MockLibraryRepo{}
libRepo.SetData(model.Libraries{{ID: 0, Path: repoRoot}})
artRepo = tests.CreateMockArtworkRepo()
queueRepo = tests.CreateMockArtworkQueueRepo()
albumRepo = tests.CreateMockAlbumRepo()
artistRepo = tests.CreateMockArtistRepo()
mfRepo = tests.CreateMockMediaFileRepo()
plRepo = tests.CreateMockPlaylistRepo()
radioRepo = tests.CreateMockedRadioRepo()
radioRepo.Data = map[string]*model.Radio{}
ds = &tests.MockDataStore{
MockedArtwork: artRepo,
MockedArtworkQueue: queueRepo,
MockedAlbum: albumRepo,
MockedArtist: artistRepo,
MockedMediaFile: mfRepo,
MockedPlaylist: plRepo,
MockedRadio: radioRepo,
MockedFolder: folderRepo,
MockedLibrary: libRepo,
}
harness.TruncateDB(userTables)
ds = persistence.New(db.Db())
artRepo = ds.Artwork()
u := admin
Expect(ds.User().Put(ctx, &u)).To(Succeed())
Expect(ds.Library().Put(ctx, &model.Library{ID: model.DefaultLibraryID, Name: "Music", Path: repoRoot})).To(Succeed())
ffm := tests.NewMockFFmpeg("")
store = artwork.NewImageStore(GinkgoT().TempDir())
// size=0 requests stream originals, so this reader is never called (serving_test covers resizing).
@ -113,8 +111,8 @@ var _ = Describe("Acquisition → serve loop", func() {
})
seedFolderAlbum := func(albumID string) {
folderRepo.result = []model.Folder{{Path: albumFolderPath, ImageFiles: []string{"cover.jpg"}}}
albumRepo.SetData(model.Albums{{ID: albumID, Name: "Album", FolderIDs: []string{"f1"}, LibraryID: 0}})
GinkgoHelper()
persistencetest.PutAlbums(ctx, ds, model.Album{ID: albumID, Name: "Album", FolderIDs: []string{putFolder(albumFolderPath, "cover.jpg")}})
}
It("acquires and serves a cover whose format has no registered decoder (#5950)", func() {
@ -123,14 +121,13 @@ var _ = Describe("Acquisition → serve loop", func() {
Expect(os.WriteFile(filepath.Join(libDir, "an-album", "cover.jxl"), jxlFixture, 0600)).To(Succeed())
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*" })
libRepo.SetData(model.Libraries{{ID: 0, Path: libDir}})
folderRepo.result = []model.Folder{{Path: "an-album", ImageFiles: []string{"cover.jxl"}}}
albumRepo.SetData(model.Albums{{ID: "al1", Name: "Album", FolderIDs: []string{"f1"}, LibraryID: 0}})
persistencetest.SetLibraries(ctx, ds, libDir)
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", FolderIDs: []string{putFolder("an-album", "cover.jxl")}})
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 +142,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())
@ -154,7 +151,7 @@ var _ = Describe("Acquisition → serve loop", func() {
It("acquires an artist's uploaded image and serves it", func() {
name := writeUpload(consts.EntityArtist, "artist-e2e.png", artistPngFixture)
artistRepo.SetData(model.Artists{{ID: "ar1", Name: "Artist", UploadedImage: name}})
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar1", Name: "Artist", UploadedImage: name})
bump("ar", "ar1")
runWorkerUntil(ctx, worker, itemFound(model.KindArtistArtwork, "ar1"))
@ -162,7 +159,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)))
@ -170,8 +167,10 @@ var _ = Describe("Acquisition → serve loop", func() {
It("generates a playlist grid from its tracks' album art and serves it from the store", func() {
seedFolderAlbum("al1")
plRepo.SetData(model.Playlists{{ID: "pl1", Name: "Playlist"}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"al1"}}
track := model.MediaFile{ID: "mfpl", AlbumID: "al1", LibraryID: model.DefaultLibraryID, Path: "pl/track.mp3"}
Expect(ds.MediaFile().Put(ctx, &track)).To(Succeed())
Expect(ds.Playlist().Put(ctx, &model.Playlist{ID: "pl1", Name: "Playlist", OwnerID: admin.ID,
Tracks: model.PlaylistTracks{{MediaFileID: track.ID, MediaFile: track}}})).To(Succeed())
bump("pl", "pl1")
runWorkerUntil(ctx, worker, itemFound(model.KindPlaylistArtwork, "pl1"))
@ -179,18 +178,18 @@ 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() {
name := writeUpload(consts.EntityRadio, "radio-e2e.jpg", coverFixture)
radioRepo.Data["ra1"] = &model.Radio{ID: "ra1", Name: "Station", UploadedImage: name}
putRadio(model.Radio{ID: "ra1", Name: "Station", UploadedImage: name})
bump("ra", "ra1")
runWorkerUntil(ctx, worker, itemFound(model.KindRadioArtwork, "ra1"))
@ -198,23 +197,23 @@ 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))
})
It("serves an unresolved track provisionally, then upgrades to the worker's state row", func() {
mfRepo.SetData(model.MediaFiles{{
ID: "mf1", AlbumID: "al1", HasCoverArt: true, LibraryID: 0, Path: mp3Fixture,
}})
Expect(ds.MediaFile().Put(ctx, &model.MediaFile{
ID: "mf1", AlbumID: "al1", HasCoverArt: true, LibraryID: model.DefaultLibraryID, Path: mp3Fixture,
})).To(Succeed())
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 +225,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))
@ -255,7 +254,7 @@ var _ = Describe("Acquisition → serve loop", func() {
It("acquires GIF artwork, whose decoder only core/artwork's blank import registers", func() {
writeUploadedImage(consts.EntityRadio, "station.gif", gifFixture)
radioRepo.Data["ra1"] = &model.Radio{ID: "ra1", Name: "Station", UploadedImage: "station.gif"}
putRadio(model.Radio{ID: "ra1", Name: "Station", UploadedImage: "station.gif"})
bump("ra", "ra1")
runWorkerUntil(ctx, worker, itemFound(model.KindRadioArtwork, "ra1"))
@ -268,11 +267,11 @@ var _ = Describe("Acquisition → serve loop", func() {
})
It("deduplicates byte-identical art across entities onto one image row", func() {
folderRepo.result = []model.Folder{{Path: albumFolderPath, ImageFiles: []string{"cover.jpg"}}}
albumRepo.SetData(model.Albums{
{ID: "al1", Name: "Album", FolderIDs: []string{"f1"}, LibraryID: 0},
{ID: "al2", Name: "Same Cover", FolderIDs: []string{"f1"}, LibraryID: 0},
})
fid := putFolder(albumFolderPath, "cover.jpg")
persistencetest.PutAlbums(ctx, ds,
model.Album{ID: "al1", Name: "Album", FolderIDs: []string{fid}},
model.Album{ID: "al2", Name: "Same Cover", FolderIDs: []string{fid}},
)
bump("al", "al1")
bump("al", "al2")
runWorkerUntil(ctx, worker, func() bool {
@ -284,12 +283,12 @@ 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() {
name := writeUpload(consts.EntityRadio, "radio-stale.jpg", coverFixture)
radioRepo.Data["ra1"] = &model.Radio{ID: "ra1", Name: "Station", UploadedImage: name}
putRadio(model.Radio{ID: "ra1", Name: "Station", UploadedImage: name})
bump("ra", "ra1")
runWorkerUntil(ctx, worker, itemFound(model.KindRadioArtwork, "ra1"))
@ -303,7 +302,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,17 +310,17 @@ 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)))
})
It("records an absent state for an entity with no art and reports it unavailable", func() {
albumRepo.SetData(model.Albums{{ID: "alx", Name: "Artless", LibraryID: 0}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alx", Name: "Artless"})
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

@ -65,23 +65,6 @@ func runWorkerUntil(ctx context.Context, worker *artwork.Worker, until func() bo
Eventually(done, 2*time.Second).Should(Receive(BeNil()))
}
type fakeFolderRepo struct {
model.FolderRepository
result []model.Folder
}
func (f *fakeFolderRepo) GetAll(context.Context, ...model.QueryOptions) ([]model.Folder, error) {
return f.result, nil
}
func (f *fakeFolderRepo) HasAudioOutsideFolders(context.Context, model.Folder, []string) (bool, error) {
return false, nil
}
func (f *fakeFolderRepo) Get(context.Context, string) (*model.Folder, error) {
return nil, model.ErrNotFound
}
func writeUpload(entityType, name, srcFixture string) string {
GinkgoHelper()
dst := model.UploadedImagePath(entityType, name)

View file

@ -3,6 +3,7 @@ package e2e
import (
"bytes"
"context"
"errors"
"fmt"
"hash/fnv"
"image"
@ -29,6 +30,7 @@ import (
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/scanner"
"github.com/navidrome/navidrome/server/events"
"github.com/navidrome/navidrome/tests"
@ -49,7 +51,7 @@ const (
var (
rctx context.Context
rds *tests.MockDataStore
rds model.DataStore
rstore *artwork.ImageStore
rsvc artwork.Artwork
rworker *artwork.Worker
@ -71,13 +73,15 @@ 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 err error
userTables, err = persistencetest.Tables()
Expect(err).ToNot(HaveOccurred())
})
var _ = AfterSuite(func() {
db.Close(context.Background())
db.Close(GinkgoT().Context())
})
func setupResolutionHarness() {
@ -98,7 +102,7 @@ func setupResolutionHarness() {
rctx = request.WithUser(GinkgoT().Context(), model.User{ID: "admin-1", UserName: "admin", IsAdmin: true})
harness.TruncateDB(userTables)
rds = &tests.MockDataStore{RealDS: persistence.New(db.Db())}
rds = persistence.New(db.Db())
adminUser := model.User{ID: "admin-1", UserName: "admin", Name: "Admin", IsAdmin: true, NewPassword: "password"}
Expect(rds.User().Put(rctx, &adminUser)).To(Succeed())
@ -117,7 +121,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 +328,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

@ -6,27 +6,59 @@ import (
"time"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/persistence/persistencetest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
// spyFolderRepo counts parent lookups and can fail them or the album-root check.
type spyFolderRepo struct {
model.FolderRepository
getCalls int
getErr error
otherAudioErr error
}
func (f *spyFolderRepo) Get(ctx context.Context, id string) (*model.Folder, error) {
f.getCalls++
if f.getErr != nil {
return nil, f.getErr
}
return f.FolderRepository.Get(ctx, id)
}
func (f *spyFolderRepo) HasAudioOutsideFolders(ctx context.Context, parent model.Folder, excludeIDs []string) (bool, error) {
if f.otherAudioErr != nil {
return false, f.otherAudioErr
}
return f.FolderRepository.HasAudioOutsideFolders(ctx, parent, excludeIDs)
}
// The e2e specs cover which image wins for a layout; these pin what a layout cannot reach: that
// the album-root parent is only fetched when it could qualify, and what happens when that fails.
var _ = Describe("loadAlbumFoldersPaths", func() {
var (
ctx context.Context
ds *tests.MockDataStore
repo *fakeFolderRepo
ds model.DataStore
repo *spyFolderRepo
album model.Album
now time.Time
)
putFolders := func(folders ...model.Folder) {
GinkgoHelper()
for _, f := range folders {
f.LibraryID = model.DefaultLibraryID
Expect(ds.Folder().Put(ctx, &f)).To(Succeed())
}
}
BeforeEach(func() {
ctx = context.Background()
ctx = GinkgoT().Context()
now = time.Now().Truncate(time.Second)
repo = &fakeFolderRepo{}
ds = &tests.MockDataStore{MockedFolder: repo}
real := newTestDS(ctx)
repo = &spyFolderRepo{FolderRepository: real.Folder()}
ds = persistencetest.Stub(real, persistencetest.Repos{Folder: func(model.FolderRepository) model.FolderRepository { return repo }})
album = model.Album{
ID: "album1",
Name: "Album",
@ -35,73 +67,72 @@ var _ = Describe("loadAlbumFoldersPaths", func() {
})
It("does not query the parent when it is already one of the album's folders", func() {
repo.result = []model.Folder{
{ID: "folder1", Path: "Artist", Name: "Album", ParentID: "folder2",
putFolders(
model.Folder{ID: "folder1", Path: "Artist", Name: "Album", ParentID: "folder2",
ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}},
{ID: "folder2", Path: "", Name: "Artist", ImagesUpdatedAt: now},
}
model.Folder{ID: "folder2", Path: "", Name: "Artist", ImagesUpdatedAt: now},
)
_, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album)
Expect(err).ToNot(HaveOccurred())
Expect(imgFiles).To(ConsistOf("Artist/Album/cover.jpg"))
Expect(repo.getCallCount).To(BeZero())
Expect(repo.getCalls).To(BeZero())
})
It("does not query the parent when the album's folders have different parents", func() {
repo.result = []model.Folder{
{ID: "folder1", Path: "Artist1/Album", Name: "part1", ParentID: "parentA",
putFolders(
model.Folder{ID: "folder1", Path: "Artist1/Album", Name: "part1", ParentID: "parentA",
ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}},
{ID: "folder2", Path: "Artist2/Album", Name: "part2", ParentID: "parentB",
model.Folder{ID: "folder2", Path: "Artist2/Album", Name: "part2", ParentID: "parentB",
ImagesUpdatedAt: now},
}
)
_, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album)
Expect(err).ToNot(HaveOccurred())
Expect(imgFiles).To(ConsistOf("Artist1/Album/part1/cover.jpg"))
Expect(repo.getCallCount).To(BeZero())
Expect(repo.getCalls).To(BeZero())
})
It("does not query the parent for a single-folder album that has images of its own", func() {
repo.result = []model.Folder{
{ID: "folder1", Path: "Artist", Name: "Album", ParentID: "artistFolder",
ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}},
}
putFolders(model.Folder{ID: "folder1", Path: "Artist", Name: "Album", ParentID: "artistFolder",
ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}})
_, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album)
Expect(err).ToNot(HaveOccurred())
Expect(imgFiles).To(ConsistOf("Artist/Album/cover.jpg"))
Expect(repo.getCallCount).To(BeZero())
Expect(repo.getCalls).To(BeZero())
})
It("does not promote the library root, so its images never become album art", func() {
repo.result = []model.Folder{
{ID: "folder1", Path: ".", Name: "AlbumPart1", ParentID: "rootFolder",
putFolders(
model.Folder{ID: "folder1", Path: ".", Name: "AlbumPart1", ParentID: "rootFolder",
ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}},
{ID: "folder2", Path: ".", Name: "AlbumPart2", ParentID: "rootFolder",
model.Folder{ID: "folder2", Path: ".", Name: "AlbumPart2", ParentID: "rootFolder",
ImagesUpdatedAt: now},
}
repo.parentResult = &model.Folder{ID: "rootFolder", Name: ".", ImageFiles: []string{"unrelated.jpg"}}
model.Folder{ID: "rootFolder", Name: ".", ImageFiles: []string{"unrelated.jpg"}},
)
_, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album)
Expect(err).ToNot(HaveOccurred())
Expect(imgFiles).To(ConsistOf("AlbumPart1/cover.jpg"))
Expect(repo.getCallCount).To(Equal(1))
Expect(repo.getCalls).To(Equal(1))
})
It("does not promote a parent that holds another album's audio", func() {
repo.result = []model.Folder{
{ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "albumFolder",
putFolders(
model.Folder{ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "albumFolder",
ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}},
{ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "albumFolder",
model.Folder{ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "albumFolder",
ImagesUpdatedAt: now},
}
repo.parentResult = &model.Folder{ID: "albumFolder", Path: "Artist", Name: "Album",
ParentID: "artistFolder", ImageFiles: []string{"artist.jpg"}}
repo.hasOtherAudio = true
model.Folder{ID: "albumFolder", Path: "Artist", Name: "Album",
ParentID: "artistFolder", ImageFiles: []string{"artist.jpg"}},
model.Folder{ID: "otherAlbum", Path: "Artist/Album", Name: "Bonus", ParentID: "albumFolder",
NumAudioFiles: 3},
)
_, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album)
@ -110,14 +141,14 @@ var _ = Describe("loadAlbumFoldersPaths", func() {
})
It("promotes the album root parent into the returned paths", func() {
repo.result = []model.Folder{
{ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "albumFolder",
ImagesUpdatedAt: now},
{ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "albumFolder",
ImagesUpdatedAt: now},
}
repo.parentResult = &model.Folder{ID: "albumFolder", Path: "Artist", Name: "Album",
ParentID: "artistFolder", ImageFiles: []string{"cover.jpg"}}
putFolders(
model.Folder{ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "albumFolder",
ImagesUpdatedAt: now, NumAudioFiles: 5},
model.Folder{ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "albumFolder",
ImagesUpdatedAt: now, NumAudioFiles: 5},
model.Folder{ID: "albumFolder", Path: "Artist", Name: "Album",
ParentID: "artistFolder", ImageFiles: []string{"cover.jpg"}},
)
paths, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album)
@ -127,12 +158,12 @@ var _ = Describe("loadAlbumFoldersPaths", func() {
})
It("propagates errors from the album-root check", func() {
repo.result = []model.Folder{
{ID: "folder1", Path: "Artist/Album", Name: "disc1", ParentID: "albumFolder",
putFolders(
model.Folder{ID: "folder1", Path: "Artist/Album", Name: "disc1", ParentID: "albumFolder",
ImagesUpdatedAt: now},
}
repo.parentResult = &model.Folder{ID: "albumFolder", Path: "Artist", Name: "Album",
ParentID: "artistFolder", ImageFiles: []string{"cover.jpg"}}
model.Folder{ID: "albumFolder", Path: "Artist", Name: "Album",
ParentID: "artistFolder", ImageFiles: []string{"cover.jpg"}},
)
repo.otherAudioErr = errors.New("db connection failed")
_, _, _, err := loadAlbumFoldersPaths(ctx, ds, album)
@ -141,33 +172,33 @@ var _ = Describe("loadAlbumFoldersPaths", func() {
})
It("propagates non-ErrNotFound errors from the parent folder lookup", func() {
repo.result = []model.Folder{
{ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "parentFolder",
putFolders(
model.Folder{ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "parentFolder",
ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}},
{ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "parentFolder",
model.Folder{ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "parentFolder",
ImagesUpdatedAt: now},
}
)
repo.getErr = errors.New("db connection failed")
_, _, _, err := loadAlbumFoldersPaths(ctx, ds, album)
Expect(err).To(MatchError("db connection failed"))
Expect(repo.getCallCount).To(Equal(1))
Expect(repo.getCalls).To(Equal(1))
})
It("continues when the parent folder has been deleted", func() {
repo.result = []model.Folder{
{ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "missingParent",
putFolders(
model.Folder{ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "missingParent",
ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}},
{ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "missingParent",
model.Folder{ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "missingParent",
ImagesUpdatedAt: now},
}
)
_, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album)
Expect(err).ToNot(HaveOccurred())
Expect(imgFiles).To(ConsistOf("Artist/Album/CD1/cover.jpg"))
Expect(repo.getCallCount).To(Equal(1))
Expect(repo.getCalls).To(Equal(1))
})
})

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

@ -7,7 +7,7 @@ import (
"time"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/persistence/persistencetest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
@ -38,19 +38,21 @@ var _ = Describe("commonDir", func() {
var _ = Describe("loadArtistFolder", func() {
var (
ctx context.Context
ds *tests.MockDataStore
repo *fakeFolderRepo
ds model.DataStore
albums model.Albums
updatedAt time.Time
)
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{}
libRepo.SetData(model.Libraries{{ID: 1, Path: filepath.FromSlash("/music")}})
ds = &tests.MockDataStore{MockedFolder: repo, MockedLibrary: libRepo}
ds = newTestDS(ctx)
persistencetest.SetLibraries(ctx, ds, filepath.FromSlash("/music"))
lib, err := ds.Library().Get(ctx, model.DefaultLibraryID)
Expect(err).ToNot(HaveOccurred())
artistFolder := model.NewFolder(*lib, "artist")
artistFolder.ImagesUpdatedAt = updatedAt
Expect(ds.Folder().Put(ctx, artistFolder)).To(Succeed())
albums = model.Albums{{LibraryID: 1, ID: "album1", Name: "Album 1"}}
})
@ -68,7 +70,7 @@ var _ = Describe("loadArtistFolder", func() {
Expect(err).ToNot(HaveOccurred())
Expect(folder).To(Equal(filepath.FromSlash("/music/artist")))
Expect(upd).To(Equal(updatedAt))
Expect(upd).To(BeTemporally("==", updatedAt))
})
It("climbs above the shared folder when two albums live in the same one", func() {
@ -79,7 +81,7 @@ var _ = Describe("loadArtistFolder", func() {
Expect(err).ToNot(HaveOccurred())
Expect(folder).To(Equal(filepath.FromSlash("/music/artist")))
Expect(upd).To(Equal(updatedAt))
Expect(upd).To(BeTemporally("==", updatedAt))
})
It("stops at the folder where distinct album roots already meet", func() {
@ -90,11 +92,13 @@ var _ = Describe("loadArtistFolder", func() {
Expect(err).ToNot(HaveOccurred())
Expect(folder).To(Equal(filepath.FromSlash("/music/artist")))
Expect(upd).To(Equal(updatedAt))
Expect(upd).To(BeTemporally("==", updatedAt))
})
It("returns the error when the folder lookup fails", func() {
repo.err = errors.New("fake error")
ds = persistencetest.Stub(ds, persistencetest.Repos{Folder: func(r model.FolderRepository) model.FolderRepository {
return &failingFolderRepo{FolderRepository: r, err: errors.New("fake error")}
}})
folder, upd, err := loadArtistFolder(ctx, ds, albums, []string{
filepath.FromSlash("/music/artist/album1"),
@ -106,3 +110,12 @@ var _ = Describe("loadArtistFolder", func() {
Expect(upd).To(BeZero())
})
})
type failingFolderRepo struct {
model.FolderRepository
err error
}
func (f *failingFolderRepo) GetAll(context.Context, ...model.QueryOptions) ([]model.Folder, error) {
return nil, f.err
}

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

@ -7,7 +7,7 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/persistence/persistencetest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
@ -27,14 +27,12 @@ var _ = Describe("RefreshableKinds", func() {
var _ = Describe("Housekeeping", func() {
var (
ctx context.Context
ds *tests.MockDataStore
queueRepo *tests.MockArtworkQueueRepo
propRepo *tests.MockedPropertyRepo
ctx context.Context
ds model.DataStore
)
BeforeEach(func() {
ctx = context.Background()
ctx = GinkgoT().Context()
conf.Update(func(c *conf.Options) {
c.CoverArtPriority = "embedded, folder"
c.ArtistArtPriority = "artist.jpg"
@ -42,9 +40,7 @@ var _ = Describe("Housekeeping", func() {
c.EnableExternalServices = true
})
queueRepo = tests.CreateMockArtworkQueueRepo()
propRepo = &tests.MockedPropertyRepo{}
ds = &tests.MockDataStore{MockedArtworkQueue: queueRepo, MockedProperty: propRepo}
ds = newTestDS(ctx)
})
Describe("Fingerprint", func() {
@ -99,65 +95,60 @@ var _ = Describe("Housekeeping", func() {
It("records the current fingerprint when none was ever stored", func() {
Expect(ReconcileConfigFingerprint(ctx, ds)).To(Succeed())
Expect(propRepo.Get(ctx, consts.ArtConfFingerprintPropertyKey)).To(Equal(ConfigFingerprint()))
Expect(ds.Property().Get(ctx, consts.ArtConfFingerprintPropertyKey)).To(Equal(ConfigFingerprint()))
})
It("leaves a stale fingerprint stored, so the warning survives a restart", func() {
Expect(propRepo.Put(ctx, consts.ArtConfFingerprintPropertyKey, "stale-fingerprint")).To(Succeed())
Expect(ds.Property().Put(ctx, consts.ArtConfFingerprintPropertyKey, "stale-fingerprint")).To(Succeed())
Expect(ReconcileConfigFingerprint(ctx, ds)).To(Succeed())
Expect(propRepo.Get(ctx, consts.ArtConfFingerprintPropertyKey)).To(Equal("stale-fingerprint"))
Expect(ds.Property().Get(ctx, consts.ArtConfFingerprintPropertyKey)).To(Equal("stale-fingerprint"))
})
})
Describe("EnqueueMissingAll", func() {
var artRepo *tests.MockArtworkRepo
BeforeEach(func() {
artRepo = tests.CreateMockArtworkRepo()
ds.MockedArtwork = artRepo
queueRepo.ItemArtworkSource = artRepo
queueRepo.ExistingIDs = map[string]map[string]bool{
"al": {"al1": true, "al2": true},
"ar": {"ar1": true},
"pl": {"pl1": true},
"ra": {"ra1": true},
}
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album 1"}, model.Album{ID: "al2", Name: "Album 2"})
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar1", Name: "Artist"})
putPlaylist(ctx, ds, model.Playlist{ID: "pl1", Name: "Playlist"})
putRadio(ctx, ds, model.Radio{ID: "ra1", Name: "Radio"})
})
It("enqueues only entities that have no item_artwork row, across all kinds", func() {
artRepo.ItemData["al-resolved"] = model.ItemArtwork{ItemKind: "al", ItemID: "al1", ImageType: model.ImageTypePrimary, Hash: "somehash"}
artRepo.ItemData["ar-absent"] = model.ItemArtwork{ItemKind: "ar", ItemID: "ar1", ImageType: model.ImageTypePrimary, Hash: ""}
Expect(ds.Artwork().PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "al", ItemID: "al1", ImageType: model.ImageTypePrimary, Hash: "somehash"})).To(Succeed())
Expect(ds.Artwork().PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "ar", ItemID: "ar1", ImageType: model.ImageTypePrimary, Hash: ""})).To(Succeed())
err := enqueueMissingAll(ctx, ds)
Expect(err).ToNot(HaveOccurred())
for _, it := range queueRepo.Data {
Expect(it.Priority).To(Equal(model.ArtworkPriorityRecheck))
stats, err := ds.ArtworkQueue().CountQueued(ctx, nil, nil)
Expect(err).ToNot(HaveOccurred())
Expect(stats).ToNot(BeEmpty())
for _, st := range stats {
Expect(st.Priority).To(Equal(model.ArtworkPriorityRecheck))
}
Expect(findQueued(queueRepo, "al", "al2")).ToNot(BeNil())
Expect(findQueued(queueRepo, "pl", "pl1")).ToNot(BeNil())
Expect(findQueued(queueRepo, "ra", "ra1")).ToNot(BeNil())
Expect(findQueued(queueRepo, "al", "al1")).To(BeNil())
Expect(findQueued(queueRepo, "ar", "ar1")).To(BeNil())
Expect(queued(ctx, ds, "al", "al2")).ToNot(BeNil())
Expect(queued(ctx, ds, "pl", "pl1")).ToNot(BeNil())
Expect(queued(ctx, ds, "ra", "ra1")).ToNot(BeNil())
Expect(queued(ctx, ds, "al", "al1")).To(BeNil())
Expect(queued(ctx, ds, "ar", "ar1")).To(BeNil())
})
})
})
var _ = Describe("ItemName", func() {
var ds *tests.MockDataStore
var ds model.DataStore
var ctx context.Context
BeforeEach(func() {
ctx = context.Background()
albumRepo := tests.CreateMockAlbumRepo()
albumRepo.SetData(model.Albums{
{ID: "al-1", Name: "Kid A"},
{ID: "al-2", Name: "Sandinista!", Discs: model.Discs{2: "Side Three"}},
})
ds = &tests.MockDataStore{MockedAlbum: albumRepo}
Expect(ds.Artist().(*tests.MockArtistRepo).Put(ctx, &model.Artist{ID: "ar-1", Name: "Radiohead"})).To(Succeed())
ctx = GinkgoT().Context()
ds = newTestDS(ctx)
persistencetest.PutAlbums(ctx, ds,
model.Album{ID: "al-1", Name: "Kid A"},
model.Album{ID: "al-2", Name: "Sandinista!", Discs: model.Discs{2: "Side Three"}},
)
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar-1", Name: "Radiohead"})
})
It("returns the album name", func() {

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

@ -3,28 +3,30 @@ package artwork
import (
"context"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/storage/storagetest"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/persistence/persistencetest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("loadLibraryView", Ordered, func() {
var ctx context.Context
var ds *tests.MockDataStore
var ds model.DataStore
BeforeAll(func() {
DeferCleanup(conf.SnapshotConfig())
storagetest.Register("fake", &storagetest.FakeFS{})
})
BeforeEach(func() {
ctx = GinkgoT().Context()
ds = &tests.MockDataStore{MockedLibrary: &tests.MockLibraryRepo{}}
ds = newTestDS(ctx)
})
It("returns a view for a library backed by registered storage", func() {
Expect(ds.Library().Put(ctx, &model.Library{ID: 1, Path: "fake:///music"})).To(Succeed())
persistencetest.SetLibraries(ctx, ds, "fake:///music")
lib, err := loadLibraryView(ctx, ds, 1)
Expect(err).ToNot(HaveOccurred())
@ -45,7 +47,7 @@ var _ = Describe("loadLibraryView", Ordered, func() {
})
It("returns an error when the library path uses an unregistered scheme", func() {
Expect(ds.Library().Put(ctx, &model.Library{ID: 2, Path: "unsupported:///music"})).To(Succeed())
Expect(ds.Library().Put(ctx, &model.Library{ID: 2, Name: "Unsupported", Path: "unsupported:///music"})).To(Succeed())
_, err := loadLibraryView(ctx, ds, 2)
Expect(err).To(HaveOccurred())
})

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

@ -18,7 +18,9 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -43,36 +45,34 @@ func pngHeaderWithDims(w, h uint32) []byte {
var _ = Describe("processor.acquire", func() {
var (
ctx context.Context
ds *tests.MockDataStore
folderRepo *fakeFolderRepo
libRepo *tests.MockLibraryRepo
ffm *tests.MockFFmpeg
ag *agents.Agents
store *ImageStore
artRepo *tests.MockArtworkRepo
repoRoot string
proc *processor
ctx context.Context
ds model.DataStore
ffm *tests.MockFFmpeg
ag *agents.Agents
store *ImageStore
artRepo model.ArtworkRepository
repoRoot string
proc *processor
)
// poisonBlurHash overwrites a stored image's blurhash, so a later re-decode would show.
poisonBlurHash := func(hash string) {
GinkgoHelper()
_, err := db.Db().Exec("UPDATE artwork SET blur_hash = 'SENTINEL' WHERE hash = ?", hash)
Expect(err).ToNot(HaveOccurred())
}
BeforeEach(func() {
ctx = context.Background()
ctx = GinkgoT().Context()
var err error
repoRoot, err = os.Getwd()
Expect(err).ToNot(HaveOccurred())
folderRepo = &fakeFolderRepo{}
libRepo = &tests.MockLibraryRepo{}
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}})
ds = newTestDS(ctx)
useLibrary(ctx, ds, repoRoot)
ffm = tests.NewMockFFmpeg("")
ag = agents.GetAgents(&tests.MockDataStore{}, nil)
artRepo = tests.CreateMockArtworkRepo()
ds = &tests.MockDataStore{
MockedFolder: folderRepo,
MockedLibrary: libRepo,
MockedArtwork: artRepo,
}
ds.MockedAlbum = tests.CreateMockAlbumRepo()
ag = agents.GetAgents(ds, nil)
artRepo = ds.Artwork()
store = NewImageStore(GinkgoT().TempDir())
proc = &processor{ds: ds, store: store, resolver: newResolver(ds, ag, ffm, nil)}
@ -80,13 +80,8 @@ var _ = Describe("processor.acquire", func() {
})
It("found-folder: persists state from a folder image, writes no store file, keeps sourcePath/refMtime", func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al1", Name: "Album", FolderIDs: []string{"f1"}},
})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", FolderIDs: []string{fid}})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al1"})
Expect(out).To(Equal(outcomeFound))
@ -117,13 +112,8 @@ var _ = Describe("processor.acquire", func() {
})
It("holds it once across the write window", func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "alL1", Name: "Album", FolderIDs: []string{"f1"}},
})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alL1", Name: "Album", FolderIDs: []string{fid}})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alL1"})
Expect(out).To(Equal(outcomeFound))
@ -134,10 +124,7 @@ var _ = Describe("processor.acquire", func() {
// Resolution can reach the network, so holding the lock across it would let one slow
// provider block prune, and every drain queued behind prune's writer.
It("never takes it while only resolving", func() {
folderRepo.result = nil
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "alL2", Name: "Album", FolderIDs: []string{"f1"}},
})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alL2", Name: "Album", FolderIDs: []string{"f1"}})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alL2"})
Expect(out).To(Equal(outcomeAbsent))
@ -146,10 +133,7 @@ var _ = Describe("processor.acquire", func() {
})
It("found-embedded: writes a store file and computes a non-empty blurhash from a real fixture", func() {
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al2", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}},
})
folderRepo.result = nil
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al2", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3", FolderIDs: []string{"f1"}})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al2"})
Expect(out).To(Equal(outcomeFound))
@ -169,10 +153,7 @@ var _ = Describe("processor.acquire", func() {
})
It("absent: no local source and no external error persists a known-absent state", func() {
folderRepo.result = nil
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al3", Name: "Album"},
})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al3", Name: "Album"})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al3"})
Expect(out).To(Equal(outcomeAbsent))
@ -189,11 +170,9 @@ var _ = Describe("processor.acquire", func() {
// A folder listing that names a cover the FS will not hand over: a stale mount.
libRoot := GinkgoT().TempDir()
Expect(os.MkdirAll(filepath.Join(libRoot, "an-album"), 0o755)).To(Succeed())
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(libRoot)}})
folderRepo.result = []model.Folder{{Path: "an-album", ImageFiles: []string{"cover.jpg"}}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al-io", Name: "Album", FolderIDs: []string{"f1"}},
})
useLibrary(ctx, ds, libRoot)
fid := putFolder(ctx, ds, "an-album", "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al-io", Name: "Album", FolderIDs: []string{fid}})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al-io"})
Expect(out).To(Equal(outcomeFailed))
@ -208,9 +187,6 @@ var _ = Describe("processor.acquire", func() {
// The file would still open, so the spec would pass on the decode error instead.
Skip("chmod does not restrict read access on Windows")
}
radioRepo := tests.CreateMockedRadioRepo()
radioRepo.Data = map[string]*model.Radio{}
ds.MockedRadio = radioRepo
dir := GinkgoT().TempDir()
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(dir) })
upload := model.UploadedImagePath(consts.EntityRadio, "ra-io.jpg")
@ -218,7 +194,7 @@ var _ = Describe("processor.acquire", func() {
Expect(os.WriteFile(upload, []byte("x"), 0o600)).To(Succeed())
Expect(os.Chmod(upload, 0o000)).To(Succeed()) // present, but unreadable
DeferCleanup(func() { _ = os.Chmod(upload, 0o600) })
radioRepo.Data["ra-io"] = &model.Radio{ID: "ra-io", Name: "Station", UploadedImage: "ra-io.jpg"}
putRadio(ctx, ds, model.Radio{ID: "ra-io", Name: "Station", UploadedImage: "ra-io.jpg"})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "ra", ItemID: "ra-io"})
Expect(out).To(Equal(outcomeFailed))
@ -234,9 +210,6 @@ var _ = Describe("processor.acquire", func() {
// os.Open under a non-directory maps to a not-exist error on Windows, so no localError.
Skip("cannot provoke an open fault via a non-directory parent on Windows")
}
radioRepo := tests.CreateMockedRadioRepo()
radioRepo.Data = map[string]*model.Radio{}
ds.MockedRadio = radioRepo
dir := GinkgoT().TempDir()
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(dir) })
upload := model.UploadedImagePath(consts.EntityRadio, "ra-tr.jpg")
@ -244,7 +217,7 @@ var _ = Describe("processor.acquire", func() {
// deterministically and regardless of the test user's privileges.
Expect(os.MkdirAll(filepath.Dir(filepath.Dir(upload)), 0o755)).To(Succeed())
Expect(os.WriteFile(filepath.Dir(upload), []byte("x"), 0o600)).To(Succeed())
radioRepo.Data["ra-tr"] = &model.Radio{ID: "ra-tr", Name: "Station", UploadedImage: "ra-tr.jpg"}
putRadio(ctx, ds, model.Radio{ID: "ra-tr", Name: "Station", UploadedImage: "ra-tr.jpg"})
trace := &ChainTrace{}
out, _, _ := proc.acquire(withTrace(ctx, trace), model.ArtworkQueueItem{ItemKind: "ra", ItemID: "ra-tr"})
@ -258,9 +231,7 @@ var _ = Describe("processor.acquire", func() {
It("failed-on-extError: leaves the item's state untouched", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al4", Name: "Album"},
})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al4", Name: "Album"})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
out, _, retryIn := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al4"})
@ -273,9 +244,7 @@ var _ = Describe("processor.acquire", func() {
It("failed-on-extError: reports the delay a throttled provider asked for", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al4r", Name: "Album"},
})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al4r", Name: "Album"})
imageAgents(&fakeImageAgent{name: "throttled", err: &agents.RetryLaterError{RetryIn: 42 * time.Second}})
out, _, retryIn := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al4r"})
@ -285,13 +254,8 @@ var _ = Describe("processor.acquire", func() {
It("found-stale: a fallback hit after a transient external failure persists state and returns outcomeFoundStale", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external, cover.jpg" })
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "alstale", Name: "Album", FolderIDs: []string{"f1"}},
})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alstale", Name: "Album", FolderIDs: []string{fid}})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alstale"})
@ -307,9 +271,9 @@ var _ = Describe("processor.acquire", func() {
libRoot := GinkgoT().TempDir()
Expect(os.MkdirAll(filepath.Join(libRoot, "album"), 0755)).To(Succeed())
Expect(os.WriteFile(filepath.Join(libRoot, "album", "cover.jpg"), jxlCodestream, 0600)).To(Succeed())
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(libRoot)}})
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alU", Name: "Album", FolderIDs: []string{"f1"}}})
folderRepo.result = []model.Folder{{Path: "album", ImageFiles: []string{"cover.jpg"}}}
useLibrary(ctx, ds, libRoot)
fid := putFolder(ctx, ds, "album", "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alU", Name: "Album", FolderIDs: []string{fid}})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alU"})
Expect(out).To(Equal(outcomeFound))
@ -327,9 +291,9 @@ var _ = Describe("processor.acquire", func() {
libRoot := GinkgoT().TempDir()
Expect(os.MkdirAll(filepath.Join(libRoot, "album"), 0755)).To(Succeed())
Expect(os.WriteFile(filepath.Join(libRoot, "album", "cover.jpg"), nil, 0600)).To(Succeed())
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(libRoot)}})
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alE", Name: "Album", FolderIDs: []string{"f1"}}})
folderRepo.result = []model.Folder{{Path: "album", ImageFiles: []string{"cover.jpg"}}}
useLibrary(ctx, ds, libRoot)
fid := putFolder(ctx, ds, "album", "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alE", Name: "Album", FolderIDs: []string{fid}})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alE"})
Expect(out).To(Equal(outcomeFailed))
@ -346,7 +310,7 @@ var _ = Describe("processor.acquire", func() {
}))
DeferCleanup(srv.Close)
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alX", Name: "Album"}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alX", Name: "Album"})
imageAgents(&fakeImageAgent{name: "deezerFake", imgs: []agents.ExternalImage{{URL: srv.URL, Size: 500}}})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alX"})
@ -365,7 +329,7 @@ var _ = Describe("processor.acquire", func() {
}))
DeferCleanup(srv.Close)
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alext", Name: "Album"}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alext", Name: "Album"})
imageAgents(&fakeImageAgent{name: "deezerFake", imgs: []agents.ExternalImage{{URL: srv.URL, Size: 500}}})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alext"})
@ -384,14 +348,8 @@ var _ = Describe("processor.acquire", func() {
})
It("dedup: a second item with identical bytes skips decode and reuses the artwork row", func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al5", Name: "Album A", FolderIDs: []string{"f1"}},
{ID: "al6", Name: "Album B", FolderIDs: []string{"f1"}},
})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al5", Name: "Album A", FolderIDs: []string{fid}}, model.Album{ID: "al6", Name: "Album B", FolderIDs: []string{fid}})
out1, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al5"})
Expect(out1).To(Equal(outcomeFound))
@ -399,9 +357,7 @@ var _ = Describe("processor.acquire", func() {
Expect(err).ToNot(HaveOccurred())
// A re-decode instead of a hash dedup would overwrite this sentinel.
poisoned := artRepo.Data[ia1.Hash]
poisoned.BlurHash = "SENTINEL"
artRepo.Data[ia1.Hash] = poisoned
poisonBlurHash(ia1.Hash)
out2, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al6"})
Expect(out2).To(Equal(outcomeFound))
@ -426,13 +382,12 @@ var _ = Describe("processor.acquire", func() {
Expect(os.WriteFile(img, imgBytes, 0600)).To(Succeed())
Expect(os.Chtimes(img, time.Unix(mtime, 0), time.Unix(mtime, 0))).To(Succeed())
}
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(libRoot)}})
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "alA", Name: "Album A", FolderIDs: []string{"fa"}},
{ID: "alB", Name: "Album B", FolderIDs: []string{"fb"}},
})
useLibrary(ctx, ds, libRoot)
persistencetest.PutAlbums(ctx, ds,
model.Album{ID: "alA", Name: "Album A", FolderIDs: []string{putFolder(ctx, ds, "album-a", "cover.jpg")}},
model.Album{ID: "alB", Name: "Album B", FolderIDs: []string{putFolder(ctx, ds, "album-b", "cover.jpg")}},
)
folderRepo.result = []model.Folder{{Path: "album-a", ImageFiles: []string{"cover.jpg"}}}
outN, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alA"})
Expect(outN).To(Equal(outcomeFound))
iaA, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "alA", model.ImageTypePrimary)
@ -442,11 +397,8 @@ var _ = Describe("processor.acquire", func() {
Expect(iaA.RefMtime).To(Equal(time.Unix(1000, 0).UnixNano()))
// A re-decode instead of a hash dedup would overwrite this sentinel.
poisoned := artRepo.Data[iaA.Hash]
poisoned.BlurHash = "SENTINEL"
artRepo.Data[iaA.Hash] = poisoned
poisonBlurHash(iaA.Hash)
folderRepo.result = []model.Folder{{Path: "album-b", ImageFiles: []string{"cover.jpg"}}}
outN, _, _ = proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alB"})
Expect(outN).To(Equal(outcomeFound))
iaB, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "alB", model.ImageTypePrimary)
@ -460,7 +412,7 @@ var _ = Describe("processor.acquire", func() {
Expect(filepath.ToSlash(iaAafter.SourcePath)).To(HaveSuffix("album-a/cover.jpg"))
Expect(iaAafter.RefMtime).To(Equal(time.Unix(1000, 0).UnixNano()))
Expect(artRepo.Data).To(HaveLen(1))
Expect(artRepo.GetMimeByHash(ctx)).To(HaveLen(1))
reused, err := artRepo.GetImage(ctx, iaA.Hash)
Expect(err).ToNot(HaveOccurred())
Expect(reused.BlurHash).To(Equal("SENTINEL"))
@ -474,9 +426,7 @@ var _ = Describe("processor.acquire", func() {
// Truncated PNG: a known format, so this is a real decode failure, not a missing decoder.
Expect(os.WriteFile(imgPath, pngHeaderWithDims(100, 100), 0600)).To(Succeed())
radioRepo := tests.CreateMockedRadioRepo()
radioRepo.Data = map[string]*model.Radio{"ra1": {ID: "ra1", Name: "Radio", UploadedImage: "ra1_test.jpg"}}
ds.MockedRadio = radioRepo
putRadio(ctx, ds, model.Radio{ID: "ra1", Name: "Radio", UploadedImage: "ra1_test.jpg"})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "ra", ItemID: "ra1"})
Expect(out).To(Equal(outcomeFailed))
@ -495,9 +445,7 @@ var _ = Describe("processor.acquire", func() {
Expect(f.Truncate(maxImageBytes() + 1)).To(Succeed())
Expect(f.Close()).To(Succeed())
radioRepo := tests.CreateMockedRadioRepo()
radioRepo.Data = map[string]*model.Radio{"big": {ID: "big", Name: "Radio", UploadedImage: "big_test.jpg"}}
ds.MockedRadio = radioRepo
putRadio(ctx, ds, model.Radio{ID: "big", Name: "Radio", UploadedImage: "big_test.jpg"})
out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "ra", ItemID: "big"})
Expect(out).To(Equal(outcomeFailed))
@ -557,9 +505,9 @@ var _ = Describe("processor.acquire", func() {
Expect(err).ToNot(HaveOccurred())
Expect(os.MkdirAll(filepath.Join(libRoot, "album"), 0755)).To(Succeed())
Expect(os.WriteFile(filepath.Join(libRoot, "album", "cover.jpg"), imgBytes, 0600)).To(Succeed())
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(libRoot)}})
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alM", Name: "Album", FolderIDs: []string{"f1"}}})
folderRepo.result = []model.Folder{{Path: "album", ImageFiles: []string{"cover.jpg"}}}
useLibrary(ctx, ds, libRoot)
fid := putFolder(ctx, ds, "album", "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alM", Name: "Album", FolderIDs: []string{fid}})
hash, err := hashImage(bytes.NewReader(imgBytes))
Expect(err).ToNot(HaveOccurred())
@ -575,10 +523,7 @@ var _ = Describe("processor.acquire", func() {
})
It("store write failure: fails without writing state", func() {
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al7", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}},
})
folderRepo.result = nil
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al7", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3", FolderIDs: []string{"f1"}})
// A store root that is a plain file makes every MkdirAll under it fail.
blockedRoot := filepath.Join(GinkgoT().TempDir(), "not-a-dir")

View file

@ -8,14 +8,16 @@ import (
"path/filepath"
"time"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
type flakyGetArtworkRepo struct {
*tests.MockArtworkRepo
model.ArtworkRepository
}
func (f *flakyGetArtworkRepo) GetMimeByHash(context.Context) (map[string]string, error) {
@ -24,34 +26,31 @@ func (f *flakyGetArtworkRepo) GetMimeByHash(context.Context) (map[string]string,
var _ = Describe("Prune", func() {
var ctx context.Context
var ds *tests.MockDataStore
var ds model.DataStore
var store *ImageStore
var awRepo *tests.MockArtworkRepo
var awRepo model.ArtworkRepository
BeforeEach(func() {
ctx = GinkgoT().Context()
ds = &tests.MockDataStore{}
awRepo = ds.Artwork().(*tests.MockArtworkRepo)
ds = newTestDS(ctx)
awRepo = ds.Artwork()
store = NewImageStore(GinkgoT().TempDir())
})
// PutImage refreshes created_at like the SQL repo, so fixtures are aged directly.
// PutImage refreshes created_at, so fixtures are aged directly.
ageArtwork := func(h string, t time.Time) {
a := awRepo.Data[h]
a.CreatedAt = t
awRepo.Data[h] = a
GinkgoHelper()
_, err := db.Db().Exec("UPDATE artwork SET created_at = ? WHERE hash = ?", t, h)
Expect(err).ToNot(HaveOccurred())
}
It("purges dangling item_artwork state for gone entities, summed across kinds", func() {
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "live-artist", Name: "Live"})
Expect(awRepo.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "al", ItemID: "gone-album", ImageType: model.ImageTypePrimary})).To(Succeed())
Expect(awRepo.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "ar", ItemID: "gone-artist", ImageType: model.ImageTypePrimary})).To(Succeed())
Expect(awRepo.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "ar", ItemID: "live-artist", ImageType: model.ImageTypePrimary})).To(Succeed())
awRepo.ExistingIDs = map[string]map[string]bool{
"al": {},
"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))
@ -62,18 +61,16 @@ var _ = Describe("Prune", func() {
})
It("purges dangling artwork_queue rows for gone entities", func() {
queueRepo := tests.CreateMockArtworkQueueRepo()
Expect(queueRepo.Enqueue(ctx,
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "live-album", Name: "Live"})
Expect(ds.ArtworkQueue().Enqueue(ctx,
model.ArtworkQueueItem{ItemKind: "al", ItemID: "gone-album", ImageType: model.ImageTypePrimary},
model.ArtworkQueueItem{ItemKind: "al", ItemID: "live-album", ImageType: model.ImageTypePrimary},
)).To(Succeed())
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())
Expect(queued(ctx, ds, "al", "gone-album")).To(BeNil())
Expect(queued(ctx, ds, "al", "live-album")).ToNot(BeNil())
})
It("deletes orphan rows and their store files, keeps referenced ones", func() {
@ -90,7 +87,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))
@ -107,10 +104,11 @@ var _ = Describe("Prune", func() {
Expect(store.Write(h, "image/jpeg", bytes.NewReader(data))).To(Succeed())
Expect(awRepo.PutImage(ctx, &model.Artwork{Hash: h, Mime: "image/jpeg"})).To(Succeed())
ageArtwork(h, time.Now().Add(-2*time.Hour))
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "a1", Name: "Album"})
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 +124,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 +141,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 +155,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 +172,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 +208,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))
@ -226,13 +224,15 @@ var _ = Describe("Prune", func() {
})
It("never sweeps files on a transient DB error", func() {
ds.MockedArtwork = &flakyGetArtworkRepo{MockArtworkRepo: tests.CreateMockArtworkRepo()}
ds = persistencetest.Stub(ds, persistencetest.Repos{Artwork: func(r model.ArtworkRepository) model.ArtworkRepository {
return &flakyGetArtworkRepo{ArtworkRepository: r}
}})
data := []byte("live-bytes")
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

@ -15,6 +15,7 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -44,30 +45,24 @@ var _ = Describe("IsArtistImageFile", func() {
var _ = Describe("resolveItem", func() {
var (
ctx context.Context
ds *tests.MockDataStore
folderRepo *fakeFolderRepo
libRepo *tests.MockLibraryRepo
ffm *tests.MockFFmpeg
ag *agents.Agents
repoRoot string
ctx context.Context
ds model.DataStore
ffm *tests.MockFFmpeg
ag *agents.Agents
repoRoot string
)
BeforeEach(func() {
ctx = context.Background()
// The worker resolves as an admin, which is what lets it see private playlists.
ctx = asAdmin(GinkgoT().Context())
var err error
repoRoot, err = os.Getwd()
Expect(err).ToNot(HaveOccurred())
folderRepo = &fakeFolderRepo{}
libRepo = &tests.MockLibraryRepo{}
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}})
ds = newTestDS(ctx)
useLibrary(ctx, ds, repoRoot)
ffm = tests.NewMockFFmpeg("")
ag = agents.GetAgents(&tests.MockDataStore{}, nil)
ds = &tests.MockDataStore{
MockedFolder: folderRepo,
MockedLibrary: libRepo,
}
ag = agents.GetAgents(ds, nil)
})
Describe("kind dispatch", func() {
@ -80,13 +75,10 @@ var _ = Describe("resolveItem", func() {
Describe("media file", func() {
BeforeEach(func() {
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
ds.MockedMediaFile = tests.CreateMockMediaFileRepo()
})
It("resolves embedded art from the track file", func() {
ds.MockedMediaFile.(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: "mf1", LibraryID: 0, Path: "tests/fixtures/artist/an-album/test.mp3", HasCoverArt: true},
})
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", Path: fixtureAlbumDir + "/test.mp3", HasCoverArt: true})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "mf", ItemID: "mf1"})
Expect(err).ToNot(HaveOccurred())
@ -99,9 +91,7 @@ var _ = Describe("resolveItem", func() {
})
It("resolves absent when the track has no cover art", func() {
ds.MockedMediaFile.(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: "mf2", LibraryID: 0, Path: "tests/fixtures/artist/an-album/test.mp3", HasCoverArt: false},
})
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf2", Path: fixtureAlbumDir + "/test.mp3", HasCoverArt: false})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "mf", ItemID: "mf2"})
Expect(err).ToNot(HaveOccurred())
@ -111,9 +101,7 @@ var _ = Describe("resolveItem", func() {
It("resolves absent when media file cover art is disabled", func() {
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false })
ds.MockedMediaFile.(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: "mf3", LibraryID: 0, Path: "tests/fixtures/artist/an-album/test.mp3", HasCoverArt: true},
})
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf3", Path: fixtureAlbumDir + "/test.mp3", HasCoverArt: true})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "mf", ItemID: "mf3"})
Expect(err).ToNot(HaveOccurred())
@ -130,17 +118,11 @@ var _ = Describe("resolveItem", func() {
Describe("album", func() {
BeforeEach(func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg, embedded" })
ds.MockedAlbum = tests.CreateMockAlbumRepo()
})
It("resolves folder art from the library FS", func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al1", Name: "Album", FolderIDs: []string{"f1"}},
})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", FolderIDs: []string{fid}})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al1"})
Expect(err).ToNot(HaveOccurred())
@ -153,10 +135,7 @@ var _ = Describe("resolveItem", func() {
})
It("falls back to embedded art when no folder image matches", func() {
folderRepo.result = nil
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al2", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}},
})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al2", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3", FolderIDs: []string{"f1"}})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al2"})
Expect(err).ToNot(HaveOccurred())
@ -169,9 +148,7 @@ var _ = Describe("resolveItem", func() {
It("sets extErr when the external source errors without being not-found", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al3", Name: "Album"},
})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al3", Name: "Album"})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al3"})
@ -182,9 +159,7 @@ var _ = Describe("resolveItem", func() {
It("does not set extErr when the external source reports not-found", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al4", Name: "Album"},
})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al4", Name: "Album"})
// no image agents enabled -> the external step is a definitive not-found
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al4"})
@ -195,13 +170,8 @@ var _ = Describe("resolveItem", func() {
It("carries extErr onto a fallback folder hit after a transient external failure", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external, cover.jpg" })
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al6", Name: "Album", FolderIDs: []string{"f1"}},
})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al6", Name: "Album", FolderIDs: []string{fid}})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al6"})
@ -214,13 +184,8 @@ var _ = Describe("resolveItem", func() {
It("does not carry extErr onto a fallback folder hit after a definitive external not-found", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external, cover.jpg" })
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al7", Name: "Album", FolderIDs: []string{"f1"}},
})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al7", Name: "Album", FolderIDs: []string{fid}})
// no image agents enabled -> the external step is a definitive not-found
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al7"})
@ -233,9 +198,7 @@ var _ = Describe("resolveItem", func() {
It("routes the external step through the injected gate, keyed by agent name", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al5", Name: "Album"},
})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al5", Name: "Album"})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("boom")})
var gatedNames []string
gate := func(name string, f func() (io.ReadCloser, string, error)) (io.ReadCloser, string, error) {
@ -258,9 +221,7 @@ var _ = Describe("resolveItem", func() {
imgPath := filepath.Join(tmpDir, "artwork", "artist", "ar1_test.jpg")
Expect(os.WriteFile(imgPath, []byte("uploaded artist image"), 0600)).To(Succeed())
artistRepo := tests.CreateMockArtistRepo()
artistRepo.SetData(model.Artists{{ID: "ar1", Name: "Artist", UploadedImage: "ar1_test.jpg"}})
ds.MockedArtist = artistRepo
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar1", Name: "Artist", UploadedImage: "ar1_test.jpg"})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar1"})
Expect(err).ToNot(HaveOccurred())
@ -272,18 +233,9 @@ var _ = Describe("resolveItem", func() {
It("falls through to the ArtistArtPriority chain when there is no upload", func() {
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "album/artist.*" })
folderRepo.result = []model.Folder{{
LibraryPath: testFileLibPath(repoRoot),
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"artist.png"},
}}
artistRepo := tests.CreateMockArtistRepo()
artistRepo.SetData(model.Artists{{ID: "ar2", Name: "Artist"}})
ds.MockedArtist = artistRepo
ds.MockedAlbum = tests.CreateMockAlbumRepo()
ds.MockedAlbum.(*tests.MockAlbumRepo).All = model.Albums{
{ID: "al9", Name: "Album", LibraryID: 0, FolderIDs: []string{"f1"}},
}
fid := putFolder(ctx, ds, fixtureAlbumDir, "artist.png")
putArtistAlbums(ctx, ds, model.Artist{ID: "ar2", Name: "Artist"},
model.Album{ID: "al9", Name: "Album", FolderIDs: []string{fid}})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar2"})
Expect(err).ToNot(HaveOccurred())
@ -295,9 +247,7 @@ var _ = Describe("resolveItem", func() {
It("sets extErr when the external source errors without being not-found", func() {
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external" })
artistRepo := tests.CreateMockArtistRepo()
artistRepo.SetData(model.Artists{{ID: "ar3", Name: "Artist"}})
ds.MockedArtist = artistRepo
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar3", Name: "Artist"})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar3"})
@ -308,9 +258,7 @@ var _ = Describe("resolveItem", func() {
It("does not set extErr when the external source reports not-found", func() {
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external" })
artistRepo := tests.CreateMockArtistRepo()
artistRepo.SetData(model.Artists{{ID: "ar4", Name: "Artist"}})
ds.MockedArtist = artistRepo
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar4", Name: "Artist"})
// no image agents enabled -> the external step is a definitive not-found
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar4"})
@ -321,9 +269,7 @@ var _ = Describe("resolveItem", func() {
It("routes the external step through the injected gate, keyed by agent name", func() {
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external" })
artistRepo := tests.CreateMockArtistRepo()
artistRepo.SetData(model.Artists{{ID: "ar5", Name: "Artist"}})
ds.MockedArtist = artistRepo
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar5", Name: "Artist"})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("boom")})
var gatedNames []string
gate := func(name string, f func() (io.ReadCloser, string, error)) (io.ReadCloser, string, error) {
@ -343,9 +289,7 @@ var _ = Describe("resolveItem", func() {
tmpDir := GinkgoT().TempDir()
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) })
radioRepo := tests.CreateMockedRadioRepo()
radioRepo.Data = map[string]*model.Radio{"ra1": {ID: "ra1", Name: "Radio"}}
ds.MockedRadio = radioRepo
putRadio(ctx, ds, model.Radio{ID: "ra1", Name: "Radio"})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ra", ItemID: "ra1"})
Expect(err).ToNot(HaveOccurred())
@ -359,9 +303,7 @@ var _ = Describe("resolveItem", func() {
imgPath := filepath.Join(tmpDir, "artwork", "radio", "ra2_test.jpg")
Expect(os.WriteFile(imgPath, []byte("uploaded radio image"), 0600)).To(Succeed())
radioRepo := tests.CreateMockedRadioRepo()
radioRepo.Data = map[string]*model.Radio{"ra2": {ID: "ra2", Name: "Radio", UploadedImage: "ra2_test.jpg"}}
ds.MockedRadio = radioRepo
putRadio(ctx, ds, model.Radio{ID: "ra2", Name: "Radio", UploadedImage: "ra2_test.jpg"})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ra", ItemID: "ra2"})
Expect(err).ToNot(HaveOccurred())
@ -373,27 +315,28 @@ var _ = Describe("resolveItem", func() {
})
Describe("playlist", func() {
// artless re-stores the albums with no folder, so they yield no grid tile.
artless := func(ids ...string) {
GinkgoHelper()
for _, id := range ids {
persistencetest.PutAlbums(ctx, ds, model.Album{ID: id, Name: id})
}
}
BeforeEach(func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg" })
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum = tests.CreateMockAlbumRepo()
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "t1", Name: "T1", FolderIDs: []string{"f1"}},
{ID: "t2", Name: "T2", FolderIDs: []string{"f1"}},
{ID: "t3", Name: "T3", FolderIDs: []string{"f1"}},
{ID: "t4", Name: "T4", FolderIDs: []string{"f1"}},
})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds,
model.Album{ID: "t1", Name: "T1", FolderIDs: []string{fid}},
model.Album{ID: "t2", Name: "T2", FolderIDs: []string{fid}},
model.Album{ID: "t3", Name: "T3", FolderIDs: []string{fid}},
model.Album{ID: "t4", Name: "T4", FolderIDs: []string{fid}},
)
})
DescribeTable("yields a generated grid from up to 4 album tiles",
func(albumIDs []string, expectedSize int) {
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "pl1", Name: "Playlist"}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: albumIDs}
ds.MockedPlaylist = plRepo
putPlaylist(ctx, ds, model.Playlist{ID: "pl1", Name: "Playlist"}, albumIDs...)
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl1"})
Expect(err).ToNot(HaveOccurred())
@ -421,11 +364,8 @@ var _ = Describe("resolveItem", func() {
c.EnableM3UExternalAlbumArt = false
c.CoverArtPriority = "external"
})
folderRepo.result = nil
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "plgrid", Name: "Playlist"}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1", "t2"}}
ds.MockedPlaylist = plRepo
artless("t1", "t2")
putPlaylist(ctx, ds, model.Playlist{ID: "plgrid", Name: "Playlist"}, "t1", "t2")
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("boom")})
var gatedNames []string
gate := func(name string, f func() (io.ReadCloser, string, error)) (io.ReadCloser, string, error) {
@ -445,10 +385,7 @@ var _ = Describe("resolveItem", func() {
imgPath := filepath.Join(tmpDir, "artwork", "playlist", "plu_test.jpg")
Expect(os.WriteFile(imgPath, []byte("uploaded playlist image"), 0600)).To(Succeed())
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "plu", Name: "Playlist", UploadedImage: "plu_test.jpg"}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1", "t2"}}
ds.MockedPlaylist = plRepo
putPlaylist(ctx, ds, model.Playlist{ID: "plu", Name: "Playlist", UploadedImage: "plu_test.jpg"}, "t1", "t2")
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "plu"})
Expect(err).ToNot(HaveOccurred())
@ -463,10 +400,7 @@ var _ = Describe("resolveItem", func() {
Expect(os.WriteFile(filepath.Join(plDir, "list.m3u"), []byte("#EXTM3U"), 0600)).To(Succeed())
Expect(os.WriteFile(filepath.Join(plDir, "list.jpg"), []byte("sidecar image"), 0600)).To(Succeed())
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "pls", Name: "Playlist", Path: filepath.Join(plDir, "list.m3u")}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1", "t2"}}
ds.MockedPlaylist = plRepo
putPlaylist(ctx, ds, model.Playlist{ID: "pls", Name: "Playlist", Path: filepath.Join(plDir, "list.m3u")}, "t1", "t2")
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pls"})
Expect(err).ToNot(HaveOccurred())
@ -481,10 +415,7 @@ var _ = Describe("resolveItem", func() {
imgPath := filepath.Join(dir, "cover.png")
Expect(os.WriteFile(imgPath, []byte("local external image"), 0600)).To(Succeed())
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "pll", Name: "Playlist", ExternalImageURL: imgPath}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}}
ds.MockedPlaylist = plRepo
putPlaylist(ctx, ds, model.Playlist{ID: "pll", Name: "Playlist", ExternalImageURL: imgPath}, "t1")
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pll"})
Expect(err).ToNot(HaveOccurred())
@ -496,15 +427,12 @@ var _ = Describe("resolveItem", func() {
})
It("never opens a local ExternalImageURL that is not an image file", func() {
folderRepo.result = nil // no grid tiles, so only the local file could produce a reader
artless("t1") // no grid tiles, so only the local file could produce a reader
dir := GinkgoT().TempDir()
secretPath := filepath.Join(dir, "config.ini")
Expect(os.WriteFile(secretPath, []byte("password=secret"), 0600)).To(Succeed())
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "plni", Name: "Playlist", ExternalImageURL: secretPath}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}}
ds.MockedPlaylist = plRepo
putPlaylist(ctx, ds, model.Playlist{ID: "plni", Name: "Playlist", ExternalImageURL: secretPath}, "t1")
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "plni"})
Expect(err).ToNot(HaveOccurred())
@ -514,12 +442,9 @@ var _ = Describe("resolveItem", func() {
It("routes ExternalImageURL through extGate and sets extError on transient failure", func() {
conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true })
folderRepo.result = nil // no grid tiles, so the external failure is what surfaces
artless("t1") // no grid tiles, so the external failure is what surfaces
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "ple", Name: "Playlist", ExternalImageURL: "http://example.com/cover.jpg"}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}}
ds.MockedPlaylist = plRepo
putPlaylist(ctx, ds, model.Playlist{ID: "ple", Name: "Playlist", ExternalImageURL: "http://example.com/cover.jpg"}, "t1")
var gatedNames []string
gate := func(name string, _ func() (io.ReadCloser, string, error)) (io.ReadCloser, string, error) {
@ -536,12 +461,9 @@ var _ = Describe("resolveItem", func() {
It("records the m3u failure in the trace even when album sampling adds its own steps", func() {
conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true })
folderRepo.result = nil // the sampled album yields no tile, so the m3u failure is what forced the retry
artless("t1") // the sampled album yields no tile, so the m3u failure is what forced the retry
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "plm3u", Name: "Playlist", ExternalImageURL: "http://example.com/cover.jpg"}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}}
ds.MockedPlaylist = plRepo
putPlaylist(ctx, ds, model.Playlist{ID: "plm3u", Name: "Playlist", ExternalImageURL: "http://example.com/cover.jpg"}, "t1")
gate := func(string, func() (io.ReadCloser, string, error)) (io.ReadCloser, string, error) {
return nil, "", errors.New("network down")
@ -566,12 +488,9 @@ var _ = Describe("resolveItem", func() {
})
It("treats a missing local ExternalImageURL as a definitive miss, not extError", func() {
folderRepo.result = nil // no grid tiles, so the local-file miss is what surfaces
artless("t1") // no grid tiles, so the local-file miss is what surfaces
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "plm", Name: "Playlist", ExternalImageURL: "/nonexistent/path/cover.jpg"}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}}
ds.MockedPlaylist = plRepo
putPlaylist(ctx, ds, model.Playlist{ID: "plm", Name: "Playlist", ExternalImageURL: "/nonexistent/path/cover.jpg"}, "t1")
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "plm"})
Expect(err).ToNot(HaveOccurred())
@ -586,10 +505,7 @@ var _ = Describe("resolveItem", func() {
}))
defer srv.Close()
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "pl404", Name: "Playlist", ExternalImageURL: srv.URL}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}}
ds.MockedPlaylist = plRepo
putPlaylist(ctx, ds, model.Playlist{ID: "pl404", Name: "Playlist", ExternalImageURL: srv.URL}, "t1")
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl404"})
Expect(err).ToNot(HaveOccurred())
@ -602,8 +518,7 @@ var _ = Describe("resolveItem", func() {
// A local resolver holds no agents: reaching the external branch would panic, not degrade.
It("skips the external step instead of dereferencing absent agents", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum = tests.CreateMockAlbumRepo()
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alx", Name: "Album"}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alx", Name: "Album"})
res, err := newLocalResolver(ds, ffm).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alx"})
Expect(err).ToNot(HaveOccurred())
@ -621,10 +536,7 @@ var _ = Describe("resolveItem", func() {
}))
defer srv.Close()
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "pllocal", Name: "Playlist", ExternalImageURL: srv.URL}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}}
ds.MockedPlaylist = plRepo
putPlaylist(ctx, ds, model.Playlist{ID: "pllocal", Name: "Playlist", ExternalImageURL: srv.URL}, "t1")
item := model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pllocal"}
res, err := newLocalResolver(ds, ffm).resolve(ctx, item)
@ -642,16 +554,13 @@ var _ = Describe("resolveItem", func() {
It("treats an ExternalImageURL 500 as a transient failure and sets extError", func() {
conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true })
folderRepo.result = nil // no grid tiles, so the external failure is what surfaces
artless("t1") // no grid tiles, so the external failure is what surfaces
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer srv.Close()
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "pl500", Name: "Playlist", ExternalImageURL: srv.URL}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}}
ds.MockedPlaylist = plRepo
putPlaylist(ctx, ds, model.Playlist{ID: "pl500", Name: "Playlist", ExternalImageURL: srv.URL}, "t1")
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl500"})
Expect(err).ToNot(HaveOccurred())
@ -660,14 +569,8 @@ var _ = Describe("resolveItem", func() {
})
It("yields an empty resolution when no album has art", func() {
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "empty1", Name: "Empty"},
})
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "pl2", Name: "Playlist"}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"empty1"}}
ds.MockedPlaylist = plRepo
folderRepo.result = nil
artless("empty1")
putPlaylist(ctx, ds, model.Playlist{ID: "pl2", Name: "Playlist"}, "empty1")
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl2"})
Expect(err).ToNot(HaveOccurred())
@ -679,13 +582,10 @@ var _ = Describe("resolveItem", func() {
libRoot := GinkgoT().TempDir()
Expect(os.MkdirAll(filepath.Join(libRoot, "bomb"), 0755)).To(Succeed())
Expect(os.WriteFile(filepath.Join(libRoot, "bomb", "cover.jpg"), pngHeaderWithDims(50000, 50000), 0600)).To(Succeed())
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(libRoot)}})
folderRepo.result = []model.Folder{{Path: "bomb", ImageFiles: []string{"cover.jpg"}}}
useLibrary(ctx, ds, libRoot)
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "t1", Name: "T1", FolderIDs: []string{putFolder(ctx, ds, "bomb", "cover.jpg")}})
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "plbomb", Name: "Playlist"}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}}
ds.MockedPlaylist = plRepo
putPlaylist(ctx, ds, model.Playlist{ID: "plbomb", Name: "Playlist"}, "t1")
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "plbomb"})
Expect(err).ToNot(HaveOccurred())
@ -694,11 +594,8 @@ var _ = Describe("resolveItem", func() {
})
It("does not resolve as absent when every sampled album fails to resolve", func() {
// The album ids are absent from MockAlbumRepo, so every tile fails non-externally.
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "pl3", Name: "Playlist"}})
plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"missing1", "missing2"}}
ds.MockedPlaylist = plRepo
// The tracks point at albums that are not stored, so every tile fails non-externally.
putPlaylist(ctx, ds, model.Playlist{ID: "pl3", Name: "Playlist"}, "missing1", "missing2")
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl3"})
Expect(err).To(HaveOccurred())
@ -706,17 +603,25 @@ var _ = Describe("resolveItem", func() {
})
It("returns an error when the playlist tracks cannot be loaded", func() {
plRepo := tests.CreateMockPlaylistRepo()
plRepo.SetData(model.Playlists{{ID: "pl4", Name: "Playlist"}})
ds.MockedPlaylist = plRepo
putPlaylist(ctx, ds, model.Playlist{ID: "pl4", Name: "Playlist"})
noTracks := persistencetest.Stub(ds, persistencetest.Repos{Playlist: func(r model.PlaylistRepository) model.PlaylistRepository {
return &noTracksPlaylistRepo{PlaylistRepository: r}
}})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl4"})
res, err := newResolver(noTracks, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl4"})
Expect(err).To(HaveOccurred())
Expect(res).To(Equal(resolution{}))
})
})
})
// noTracksPlaylistRepo stands in for a playlist whose track repository cannot be built.
type noTracksPlaylistRepo struct{ model.PlaylistRepository }
func (noTracksPlaylistRepo) Tracks(context.Context, string, bool) model.PlaylistTrackRepository {
return nil
}
// decodeTile runs before the processor's own guards, so it must enforce the caps itself.
var _ = Describe("decodeTile", func() {
It("rejects a decompression bomb before the full decode", func() {

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

@ -12,7 +12,9 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -81,13 +83,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 +178,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"))
})
@ -201,38 +209,28 @@ var _ = Describe("external agent tracing", func() {
var _ = Describe("resolveAlbum tracing", func() {
var (
ctx context.Context
ds *tests.MockDataStore
albumRepo *tests.MockAlbumRepo
folderRepo *fakeFolderRepo
ffm *tests.MockFFmpeg
ag *agents.Agents
t *ChainTrace
ctx context.Context
ds model.DataStore
ffm *tests.MockFFmpeg
ag *agents.Agents
t *ChainTrace
)
BeforeEach(func() {
t = &ChainTrace{}
ctx = withTrace(GinkgoT().Context(), t)
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg, embedded" })
repoRoot, err := os.Getwd()
Expect(err).ToNot(HaveOccurred())
libRepo := &tests.MockLibraryRepo{}
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}})
albumRepo = tests.CreateMockAlbumRepo()
folderRepo = &fakeFolderRepo{}
ds = &tests.MockDataStore{
MockedAlbum: albumRepo,
MockedFolder: folderRepo,
MockedLibrary: libRepo,
}
ds = newTestDS(ctx)
useLibrary(ctx, ds, repoRoot)
ffm = tests.NewMockFFmpeg("")
ag = agents.GetAgents(&tests.MockDataStore{}, nil)
t = &ChainTrace{}
ctx = withTrace(context.Background(), t)
ag = agents.GetAgents(ds, nil)
})
It("records a pattern skipped because the album folder holds no images", func() {
albumRepo.SetData(model.Albums{
{ID: "al1", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}},
})
fid := putFolder(ctx, ds, fixtureAlbumDir)
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3", FolderIDs: []string{fid}})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al1"})
Expect(err).ToNot(HaveOccurred())
@ -247,13 +245,8 @@ var _ = Describe("resolveAlbum tracing", func() {
})
It("records an evaluated pattern that matched nothing as a miss, not a skip", func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"artist.png"},
}}
albumRepo.SetData(model.Albums{
{ID: "al3", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}},
})
fid := putFolder(ctx, ds, fixtureAlbumDir, "artist.png")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al3", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3", FolderIDs: []string{fid}})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al3"})
Expect(err).ToNot(HaveOccurred())
@ -265,7 +258,7 @@ var _ = Describe("resolveAlbum tracing", func() {
It("ignores an empty priority token", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg," })
albumRepo.SetData(model.Albums{{ID: "al2", Name: "Album", FolderIDs: []string{"f1"}}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al2", Name: "Album", FolderIDs: []string{putFolder(ctx, ds, fixtureAlbumDir)}})
_, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al2"})
Expect(err).ToNot(HaveOccurred())
@ -277,15 +270,11 @@ var _ = Describe("resolveAlbum tracing", func() {
var _ = Describe("resolveArtist tracing", func() {
var (
ctx context.Context
ds *tests.MockDataStore
artistRepo *tests.MockArtistRepo
albumRepo *tests.MockAlbumRepo
folderRepo *fakeFolderRepo
ffm *tests.MockFFmpeg
ag *agents.Agents
t *ChainTrace
repoRoot string
ctx context.Context
ds model.DataStore
ffm *tests.MockFFmpeg
ag *agents.Agents
t *ChainTrace
)
uploadPath := func(file string) string {
@ -296,33 +285,23 @@ var _ = Describe("resolveArtist tracing", func() {
}
BeforeEach(func() {
t = &ChainTrace{}
ctx = withTrace(GinkgoT().Context(), t)
conf.Update(func(c *conf.Options) {
c.DataFolder = conf.NewDir(GinkgoT().TempDir())
c.ArtistArtPriority = "album/artist.*"
})
var err error
repoRoot, err = os.Getwd()
repoRoot, err := os.Getwd()
Expect(err).ToNot(HaveOccurred())
libRepo := &tests.MockLibraryRepo{}
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}})
artistRepo = tests.CreateMockArtistRepo()
albumRepo = tests.CreateMockAlbumRepo()
folderRepo = &fakeFolderRepo{}
ds = &tests.MockDataStore{
MockedArtist: artistRepo,
MockedAlbum: albumRepo,
MockedFolder: folderRepo,
MockedLibrary: libRepo,
}
ds = newTestDS(ctx)
useLibrary(ctx, ds, repoRoot)
ffm = tests.NewMockFFmpeg("")
ag = agents.GetAgents(&tests.MockDataStore{}, nil)
t = &ChainTrace{}
ctx = withTrace(context.Background(), t)
ag = agents.GetAgents(ds, nil)
})
It("records the upload short-circuit as a hit", func() {
path := uploadPath("ar1_test.jpg")
artistRepo.SetData(model.Artists{{ID: "ar1", Name: "Artist", UploadedImage: "ar1_test.jpg"}})
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar1", Name: "Artist", UploadedImage: "ar1_test.jpg"})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar1"})
Expect(err).ToNot(HaveOccurred())
@ -332,7 +311,7 @@ var _ = Describe("resolveArtist tracing", func() {
})
It("records an upload miss before walking the chain", func() {
artistRepo.SetData(model.Artists{{ID: "ar2", Name: "Artist"}})
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar2", Name: "Artist"})
_, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar2"})
Expect(err).ToNot(HaveOccurred())
@ -340,13 +319,9 @@ var _ = Describe("resolveArtist tracing", func() {
})
It("labels each step with the configured priority token", func() {
folderRepo.result = []model.Folder{{
LibraryPath: testFileLibPath(repoRoot),
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"artist.png"},
}}
artistRepo.SetData(model.Artists{{ID: "ar4", Name: "Artist"}})
albumRepo.All = model.Albums{{ID: "al9", Name: "Album", LibraryID: 0, FolderIDs: []string{"f1"}}}
fid := putFolder(ctx, ds, fixtureAlbumDir, "artist.png")
putArtistAlbums(ctx, ds, model.Artist{ID: "ar4", Name: "Artist"},
model.Album{ID: "al9", Name: "Album", FolderIDs: []string{fid}})
res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar4"})
Expect(err).ToNot(HaveOccurred())
@ -360,7 +335,7 @@ var _ = Describe("resolveArtist tracing", func() {
})
It("records a configured pattern that could not be evaluated", func() {
artistRepo.SetData(model.Artists{{ID: "ar5", Name: "Artist"}})
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar5", Name: "Artist"})
_, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar5"})
Expect(err).ToNot(HaveOccurred())
@ -372,8 +347,8 @@ var _ = Describe("resolveArtist tracing", func() {
It("records why an artist folder pattern was skipped", func() {
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "artist.*" })
artistRepo.SetData(model.Artists{{ID: "ar6", Name: "Artist"}})
albumRepo.All = model.Albums{{ID: "al10", Name: "Album", LibraryID: 0, FolderIDs: []string{"f1"}}}
putArtistAlbums(ctx, ds, model.Artist{ID: "ar6", Name: "Artist"},
model.Album{ID: "al10", Name: "Album", FolderIDs: []string{"f1"}})
_, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar6"})
Expect(err).ToNot(HaveOccurred())
@ -390,7 +365,7 @@ var _ = Describe("resolveArtist tracing", func() {
path := uploadPath("ar3_test.jpg")
Expect(os.Chmod(path, 0o000)).To(Succeed())
DeferCleanup(func() { _ = os.Chmod(path, 0o600) })
artistRepo.SetData(model.Artists{{ID: "ar3", Name: "Artist", UploadedImage: "ar3_test.jpg"}})
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar3", Name: "Artist", UploadedImage: "ar3_test.jpg"})
_, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar3"})
Expect(err).ToNot(HaveOccurred())
@ -402,16 +377,23 @@ var _ = Describe("resolveArtist tracing", func() {
var _ = Describe("NewTracingResolver", func() {
var (
ds *tests.MockDataStore
albumRepo *tests.MockAlbumRepo
artistRepo *tests.MockArtistRepo
artworkRepo *tests.MockArtworkRepo
queueRepo *tests.MockArtworkQueueRepo
ffm *tests.MockFFmpeg
t *ChainTrace
ctx context.Context
ds model.DataStore
ffm *tests.MockFFmpeg
t *ChainTrace
)
// Explain must leave both tables as it found them.
expectNothingPersisted := func() {
GinkgoHelper()
var rows int
Expect(db.Db().QueryRow("SELECT count(*) FROM item_artwork").Scan(&rows)).To(Succeed())
Expect(rows).To(BeZero(), "explain is read-only; a diagnostic walk must never become the stored answer")
Expect(queueCount(ctx, ds)).To(BeZero())
}
BeforeEach(func() {
ctx = GinkgoT().Context()
conf.Update(func(c *conf.Options) {
c.DataFolder = conf.NewDir(GinkgoT().TempDir())
c.CoverArtPriority = "external, embedded"
@ -419,20 +401,8 @@ var _ = Describe("NewTracingResolver", func() {
})
repoRoot, err := os.Getwd()
Expect(err).ToNot(HaveOccurred())
libRepo := &tests.MockLibraryRepo{}
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}})
albumRepo = tests.CreateMockAlbumRepo()
artistRepo = tests.CreateMockArtistRepo()
artworkRepo = tests.CreateMockArtworkRepo()
queueRepo = tests.CreateMockArtworkQueueRepo()
ds = &tests.MockDataStore{
MockedAlbum: albumRepo,
MockedArtist: artistRepo,
MockedFolder: &fakeFolderRepo{},
MockedLibrary: libRepo,
MockedArtwork: artworkRepo,
MockedArtworkQueue: queueRepo,
}
ds = newTestDS(ctx)
useLibrary(ctx, ds, repoRoot)
ffm = tests.NewMockFFmpeg("")
t = &ChainTrace{}
})
@ -443,14 +413,14 @@ var _ = Describe("NewTracingResolver", func() {
BeforeEach(func() {
// Misses, so the chain falls through to the local tier and both are traced.
fake = &fakeImageAgent{name: "probe", err: agents.ErrNotFound}
albumRepo.SetData(model.Albums{{
ID: "al1", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"},
}})
artistRepo.SetData(model.Artists{{ID: "ar1", Name: "Artist"}})
persistencetest.PutAlbums(ctx, ds, model.Album{
ID: "al1", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3", FolderIDs: []string{putFolder(ctx, ds, fixtureAlbumDir)},
})
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar1", Name: "Artist"})
})
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 +429,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,32 +438,29 @@ 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(),
"explain is read-only; a diagnostic walk must never become the stored answer")
Expect(queueRepo.Data).To(BeEmpty())
expectNothingPersisted()
})
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())
Expect(fake.artistCalls).To(Equal(1))
Expect(artworkRepo.ItemData).To(BeEmpty())
Expect(queueRepo.Data).To(BeEmpty())
expectNothingPersisted()
})
It("closes the reader it does not hand back", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "embedded" })
ffm = tests.NewMockFFmpeg("fake image bytes")
albumRepo.SetData(model.Albums{{
ID: "al2", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/no-such-file.mp3", FolderIDs: []string{"f1"},
}})
persistencetest.PutAlbums(ctx, ds, model.Album{
ID: "al2", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/no-such-file.mp3", FolderIDs: []string{putFolder(ctx, ds, fixtureAlbumDir)},
})
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"))
@ -508,15 +475,12 @@ var _ = Describe("NewTracingResolver", func() {
c.CoverArtPriority = "external, cover.*"
c.EnableMediaFileCoverArt = true
})
mfRepo := tests.CreateMockMediaFileRepo()
mfRepo.SetData(model.MediaFiles{{ID: "mf1", LibraryID: 0, HasCoverArt: true,
Path: "tests/fixtures/artist/an-album/test.mp3"}})
ds.MockedMediaFile = mfRepo
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", HasCoverArt: true, Path: fixtureAlbumDir + "/test.mp3"})
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 +488,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))
})
})
@ -532,37 +496,33 @@ var _ = Describe("NewTracingResolver", func() {
var _ = Describe("resolveDisc tracing", func() {
var (
ctx context.Context
ds *tests.MockDataStore
albumRepo *tests.MockAlbumRepo
folderRepo *fakeFolderRepo
ffm *tests.MockFFmpeg
t *ChainTrace
ctx context.Context
ds model.DataStore
ffm *tests.MockFFmpeg
t *ChainTrace
)
// putDiscAlbum stores al1 with its disc-2 track in the fixture folder, listing images there.
putDiscAlbum := func(images ...string) {
GinkgoHelper()
fid := putFolder(ctx, ds, fixtureAlbumDir, images...)
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", FolderIDs: []string{fid}})
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", AlbumID: "al1", DiscNumber: 2, FolderID: fid, Path: fixtureAlbumDir + "/test.mp3"})
}
BeforeEach(func() {
t = &ChainTrace{}
ctx = withTrace(GinkgoT().Context(), t)
repoRoot, err := os.Getwd()
Expect(err).ToNot(HaveOccurred())
libRepo := &tests.MockLibraryRepo{}
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}})
albumRepo = tests.CreateMockAlbumRepo()
albumRepo.SetData(model.Albums{{ID: "al1", Name: "Album", FolderIDs: []string{"f1"}}})
folderRepo = &fakeFolderRepo{}
mfRepo := tests.CreateMockMediaFileRepo()
mfRepo.SetData(model.MediaFiles{{ID: "mf1", AlbumID: "al1", DiscNumber: 2, Path: "tests/fixtures/artist/an-album/test.mp3"}})
ds = &tests.MockDataStore{
MockedAlbum: albumRepo,
MockedMediaFile: mfRepo,
MockedFolder: folderRepo,
MockedLibrary: libRepo,
}
ds = newTestDS(ctx)
useLibrary(ctx, ds, repoRoot)
ffm = tests.NewMockFFmpeg("")
t = &ChainTrace{}
ctx = withTrace(context.Background(), t)
})
It("accounts for every configured entry, including the ones that map to no source", func() {
conf.Update(func(c *conf.Options) { c.DiscArtPriority = "external, discsubtitle, cover.jpg" })
putDiscAlbum()
res, err := newResolver(ds, nil, ffm, nil).resolveDisc(ctx, model.DiscArtworkID("al1", 2))
@ -577,10 +537,7 @@ var _ = Describe("resolveDisc tracing", func() {
It("records the entry that won and stops there", func() {
conf.Update(func(c *conf.Options) { c.DiscArtPriority = "disc*.*, cover.jpg, embedded" })
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
putDiscAlbum("cover.jpg")
res, err := newResolver(ds, nil, ffm, nil).resolveDisc(ctx, model.DiscArtworkID("al1", 2))
@ -599,6 +556,7 @@ var _ = Describe("resolveDisc tracing", func() {
It("reports an unparseable disc id rather than explaining another disc", func() {
conf.Update(func(c *conf.Options) { c.DiscArtPriority = "cover.jpg" })
putDiscAlbum()
_, err := newResolver(ds, nil, ffm, nil).resolveDisc(ctx, "al1")
Expect(err).To(HaveOccurred())
})
@ -606,27 +564,22 @@ var _ = Describe("resolveDisc tracing", func() {
var _ = Describe("resolveMediaFile tracing", func() {
var (
ctx context.Context
ds *tests.MockDataStore
mfRepo *tests.MockMediaFileRepo
ffm *tests.MockFFmpeg
t *ChainTrace
ctx context.Context
ds model.DataStore
ffm *tests.MockFFmpeg
t *ChainTrace
)
BeforeEach(func() {
t = &ChainTrace{}
ctx = withTrace(GinkgoT().Context(), t)
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
repoRoot, err := os.Getwd()
Expect(err).ToNot(HaveOccurred())
libRepo := &tests.MockLibraryRepo{}
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}})
mfRepo = tests.CreateMockMediaFileRepo()
mfRepo.SetData(model.MediaFiles{{
ID: "mf1", Title: "Song", HasCoverArt: true, Path: "tests/fixtures/artist/an-album/test.mp3",
}})
ds = &tests.MockDataStore{MockedMediaFile: mfRepo, MockedLibrary: libRepo}
ds = newTestDS(ctx)
useLibrary(ctx, ds, repoRoot)
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", Title: "Song", HasCoverArt: true, Path: fixtureAlbumDir + "/test.mp3"})
ffm = tests.NewMockFFmpeg("")
t = &ChainTrace{}
ctx = withTrace(context.Background(), t)
})
It("separates a disabled setting from a track with nothing embedded", func() {
@ -641,7 +594,7 @@ var _ = Describe("resolveMediaFile tracing", func() {
})
It("records a track with no embedded art as a miss", func() {
mfRepo.SetData(model.MediaFiles{{ID: "mf2", Title: "Song", HasCoverArt: false}})
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf2", Title: "Song", Path: "song.mp3", HasCoverArt: false})
_, err := newResolver(ds, nil, ffm, nil).resolveMediaFile(ctx, "mf2")

View file

@ -9,7 +9,6 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
@ -18,16 +17,16 @@ var _ = Describe("Uploader", func() {
var ctx context.Context
var svc Uploader
var tmpDir string
var artRepo *tests.MockArtworkRepo
var queueRepo *tests.MockArtworkQueueRepo
var artRepo model.ArtworkRepository
var queueRepo model.ArtworkQueueRepository
BeforeEach(func() {
ctx = GinkgoT().Context()
tmpDir = GinkgoT().TempDir()
conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) })
artRepo = tests.CreateMockArtworkRepo()
queueRepo = tests.CreateMockArtworkQueueRepo()
ds := &tests.MockDataStore{MockedArtwork: artRepo, MockedArtworkQueue: queueRepo}
ds := newTestDS(ctx)
artRepo = ds.Artwork()
queueRepo = ds.ArtworkQueue()
svc = NewUploader(ds)
})
@ -109,7 +108,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

@ -11,6 +11,7 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -34,26 +35,16 @@ var _ = Describe("Worker soak", func() {
repoRoot, err := os.Getwd()
Expect(err).ToNot(HaveOccurred())
libRepo := &tests.MockLibraryRepo{}
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}})
folderRepo := &fakeFolderRepo{result: []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}}
ds := newTestDS(ctx)
useLibrary(ctx, ds, repoRoot)
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
ffm := tests.NewMockFFmpeg("")
ag := agents.GetAgents(&tests.MockDataStore{}, nil)
artRepo := tests.CreateMockArtworkRepo()
albumRepo := tests.CreateMockAlbumRepo()
albumRepo.SetData(model.Albums{
{ID: "al-folder", Name: "Folder Album", FolderIDs: []string{"f1"}},
{ID: "al-embed", Name: "Embedded Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}},
})
ds := &tests.MockDataStore{
MockedFolder: folderRepo,
MockedLibrary: libRepo,
MockedArtwork: artRepo,
MockedAlbum: albumRepo,
}
ag := agents.GetAgents(ds, nil)
artRepo := ds.Artwork()
persistencetest.PutAlbums(ctx, ds,
model.Album{ID: "al-folder", Name: "Folder Album", FolderIDs: []string{fid}},
model.Album{ID: "al-embed", Name: "Embedded Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3"},
)
store := NewImageStore(GinkgoT().TempDir())
proc := &processor{ds: ds, store: store, resolver: newResolver(ds, ag, ffm, nil)}
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg, embedded" })
@ -99,7 +90,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

@ -13,8 +13,9 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/server/events"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/utils/cache"
@ -51,24 +52,42 @@ func (c *recordingCache) getKeys() []string {
// Simulates a concurrent Enqueue between DequeueBatch and the worker's delete, so
// DeleteIfUnchanged on the dequeued value no-ops.
type reenqueueOnDequeue struct {
*tests.MockArtworkQueueRepo
model.ArtworkQueueRepository
done bool
}
func (r *reenqueueOnDequeue) DequeueBatch(ctx context.Context, n int, kinds ...string) ([]model.ArtworkQueueItem, error) {
items, err := r.MockArtworkQueueRepo.DequeueBatch(ctx, n, kinds...)
if !r.done && len(items) > 0 {
r.done = true
for k, it := range r.Data {
if it.ItemKind == items[0].ItemKind && it.ItemID == items[0].ItemID {
it.RetryAt = items[0].RetryAt.Add(time.Minute)
r.Data[k] = it
}
}
items, err := r.ArtworkQueueRepository.DequeueBatch(ctx, n, kinds...)
if err != nil || r.done || len(items) == 0 {
return items, err
}
r.done = true
_, err = db.Db().ExecContext(ctx, "UPDATE artwork_queue SET retry_at = ? WHERE item_kind = ? AND item_id = ?",
items[0].RetryAt.Add(time.Minute), items[0].ItemKind, items[0].ItemID)
return items, err
}
func withQueue(ds model.DataStore, queue model.ArtworkQueueRepository) model.DataStore {
return persistencetest.Stub(ds, persistencetest.Repos{
ArtworkQueue: func(model.ArtworkQueueRepository) model.ArtworkQueueRepository { return queue },
})
}
func withRacingQueue(ds model.DataStore) model.DataStore {
return withQueue(ds, &reenqueueOnDequeue{ArtworkQueueRepository: ds.ArtworkQueue()})
}
// cancelOnDequeue cancels the drain right after its batch is read, so nothing is dispatched.
type cancelOnDequeue struct {
model.ArtworkQueueRepository
cancel context.CancelFunc
}
func (c *cancelOnDequeue) DequeueBatch(ctx context.Context, n int, kinds ...string) ([]model.ArtworkQueueItem, error) {
defer c.cancel()
return c.ArtworkQueueRepository.DequeueBatch(ctx, n, kinds...)
}
type fakeEventBroker struct {
http.Handler
mu sync.Mutex
@ -95,108 +114,40 @@ func (f *fakeEventBroker) getEvents() []events.Event {
var _ events.Broker = (*fakeEventBroker)(nil)
// expireQueued ages a row past the retry budget, so the next drain settles it instead of retrying.
func expireQueued(q *tests.MockArtworkQueueRepo, id string) {
GinkgoHelper()
for k, v := range q.Data {
if v.ItemID == id {
v.EnqueuedAt = time.Now().Add(-(giveUpAfter + time.Hour))
q.Data[k] = v
}
}
}
func findQueued(q *tests.MockArtworkQueueRepo, kind, id string) *model.ArtworkQueueItem {
for _, it := range q.Data {
if it.ItemKind == kind && it.ItemID == id {
return &it
}
}
return nil
}
// visibilityPlaylistDS models playlist_repository's userFilter: a private playlist is only
// visible when the ctx carries an admin, so headless work must wrap ctx with one first.
type visibilityPlaylistDS struct {
*tests.MockDataStore
private model.Playlist
tracks model.PlaylistTrackRepository
}
func (v *visibilityPlaylistDS) Playlist() model.PlaylistRepository {
repo := tests.CreateMockPlaylistRepo()
repo.TracksRepo = v.tracks
repo.SetData(model.Playlists{v.private})
return &visibilityPlaylistRepo{MockPlaylistRepo: repo}
}
type visibilityPlaylistRepo struct {
*tests.MockPlaylistRepo
}
func (v *visibilityPlaylistRepo) Get(ctx context.Context, id string) (*model.Playlist, error) {
if u, ok := request.UserFrom(ctx); !ok || !u.IsAdmin {
return nil, model.ErrNotFound
}
return v.MockPlaylistRepo.Get(ctx, id)
}
type panickingAlbumRepo struct {
*tests.MockAlbumRepo
model.AlbumRepository
panicID string
}
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)
}
func adminUserRepo() *tests.MockedUserRepo {
repo := tests.CreateMockUserRepo()
Expect(repo.Put(GinkgoT().Context(), &model.User{ID: "admin", UserName: "admin", IsAdmin: true})).To(Succeed())
return repo
return r.AlbumRepository.Get(ctx, id)
}
var _ = Describe("Worker", func() {
var (
ctx context.Context
ds *tests.MockDataStore
folderRepo *fakeFolderRepo
libRepo *tests.MockLibraryRepo
ffm *tests.MockFFmpeg
ag *agents.Agents
store *ImageStore
artRepo *tests.MockArtworkRepo
queueRepo *tests.MockArtworkQueueRepo
broker *fakeEventBroker
imgCache *recordingCache
repoRoot string
w *Worker
ctx context.Context
ds model.DataStore
ffm *tests.MockFFmpeg
ag *agents.Agents
store *ImageStore
broker *fakeEventBroker
imgCache *recordingCache
w *Worker
)
BeforeEach(func() {
ctx = GinkgoT().Context()
var err error
repoRoot, err = os.Getwd()
repoRoot, err := os.Getwd()
Expect(err).ToNot(HaveOccurred())
conf.Update(func(c *conf.Options) { c.CacheFolder = conf.NewDir(GinkgoT().TempDir()) })
folderRepo = &fakeFolderRepo{}
libRepo = &tests.MockLibraryRepo{}
libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}})
ds = newTestDS(ctx)
useLibrary(ctx, ds, repoRoot)
ffm = tests.NewMockFFmpeg("")
ag = agents.GetAgents(&tests.MockDataStore{}, nil)
artRepo = tests.CreateMockArtworkRepo()
queueRepo = tests.CreateMockArtworkQueueRepo()
ds = &tests.MockDataStore{
MockedFolder: folderRepo,
MockedLibrary: libRepo,
MockedArtwork: artRepo,
MockedArtworkQueue: queueRepo,
}
ds.MockedAlbum = tests.CreateMockAlbumRepo()
ag = agents.GetAgents(ds, nil)
store = NewImageStore(GinkgoT().TempDir())
conf.Update(func(c *conf.Options) {
c.CoverArtPriority = "cover.jpg, embedded"
@ -214,14 +165,9 @@ var _ = Describe("Worker", func() {
Describe("drain", func() {
It("processes a seeded queue item and removes it from the queue", func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al1", Name: "Album", FolderIDs: []string{"f1"}},
})
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", FolderIDs: []string{fid}})
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{
ItemKind: "al", ItemID: "al1", Priority: model.ArtworkPriorityScan,
})).To(Succeed())
@ -229,22 +175,17 @@ var _ = Describe("Worker", func() {
Expect(err).ToNot(HaveOccurred())
Expect(n).To(Equal(1))
ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al1", model.ImageTypePrimary)
ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al1", model.ImageTypePrimary)
Expect(err).ToNot(HaveOccurred())
Expect(ia.Source).To(Equal("folder"))
count, err := queueRepo.Count(ctx)
Expect(err).ToNot(HaveOccurred())
Expect(count).To(BeZero(), "a found item must be deleted from the queue")
Expect(queueCount(ctx, ds)).To(BeZero(), "a found item must be deleted from the queue")
})
It("processes an mf queue item, writing state and storing embedded bytes", func() {
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
ds.MockedMediaFile = tests.CreateMockMediaFileRepo()
ds.MockedMediaFile.(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: "mf1", LibraryID: 0, Path: "tests/fixtures/artist/an-album/test.mp3", HasCoverArt: true},
})
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", Path: fixtureAlbumDir + "/test.mp3", HasCoverArt: true})
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{
ItemKind: "mf", ItemID: "mf1", Priority: model.ArtworkPriorityBump,
})).To(Succeed())
@ -252,12 +193,12 @@ var _ = Describe("Worker", func() {
Expect(err).ToNot(HaveOccurred())
Expect(n).To(Equal(1))
ia, err := artRepo.GetItemArtwork(ctx, model.KindMediaFileArtwork, "mf1", model.ImageTypePrimary)
ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindMediaFileArtwork, "mf1", model.ImageTypePrimary)
Expect(err).ToNot(HaveOccurred())
Expect(ia.Source).To(Equal("embedded"))
Expect(ia.Hash).ToNot(BeEmpty())
art, err := artRepo.GetImage(ctx, ia.Hash)
art, err := ds.Artwork().GetImage(ctx, ia.Hash)
Expect(err).ToNot(HaveOccurred())
r, err := store.Open(ia.Hash, art.Mime)
Expect(err).ToNot(HaveOccurred())
@ -266,99 +207,91 @@ var _ = Describe("Worker", func() {
Expect(err).ToNot(HaveOccurred())
Expect(data).ToNot(BeEmpty(), "embedded bytes must be written to the store")
count, err := queueRepo.Count(ctx)
Expect(err).ToNot(HaveOccurred())
Expect(count).To(BeZero())
Expect(queueCount(ctx, ds)).To(BeZero())
})
It("reschedules a failed item via MarkFailed with a backed-off retry_at", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al4", Name: "Album"}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al4", Name: "Album"})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al4"})).To(Succeed())
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al4"})).To(Succeed())
n, err := w.drain(ctx, 2)
Expect(err).ToNot(HaveOccurred())
Expect(n).To(Equal(1))
it := findQueued(queueRepo, "al", "al4")
it := queued(ctx, ds, "al", "al4")
Expect(it).ToNot(BeNil())
Expect(it.Attempts).To(Equal(1))
Expect(it.RetryAt).To(BeTemporally(">", time.Now()))
_, err = artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al4", model.ImageTypePrimary)
_, err = ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al4", model.ImageTypePrimary)
Expect(err).To(MatchError(model.ErrNotFound), "a timeout must never settle on absent")
})
It("fails an item that panics, without stopping the rest of the batch", func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
albums := tests.CreateMockAlbumRepo()
albums.SetData(model.Albums{
{ID: "alboom", Name: "Album", FolderIDs: []string{"f1"}},
{ID: "alok", Name: "Album", FolderIDs: []string{"f1"}},
})
ds.MockedAlbum = &panickingAlbumRepo{MockAlbumRepo: albums, panicID: "alboom"}
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alboom"})).To(Succeed())
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alok"})).To(Succeed())
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds,
model.Album{ID: "alboom", Name: "Album", FolderIDs: []string{fid}},
model.Album{ID: "alok", Name: "Album", FolderIDs: []string{fid}},
)
panicky := persistencetest.Stub(ds, persistencetest.Repos{Album: func(r model.AlbumRepository) model.AlbumRepository {
return &panickingAlbumRepo{AlbumRepository: r, panicID: "alboom"}
}})
w = NewWorker(panicky, store, ag, ffm, broker, imgCache)
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alboom"})).To(Succeed())
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alok"})).To(Succeed())
n, err := w.drain(ctx, 1)
Expect(err).ToNot(HaveOccurred())
Expect(n).To(Equal(2))
it := findQueued(queueRepo, "al", "alboom")
it := queued(ctx, ds, "al", "alboom")
Expect(it).ToNot(BeNil(), "a panicking item must be rescheduled, not dropped")
Expect(it.Attempts).To(Equal(1))
Expect(it.RetryAt).To(BeTemporally(">", time.Now()))
Expect(it.Trace).To(ContainSubstring("boom"))
Expect(findQueued(queueRepo, "al", "alok")).To(BeNil())
ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "alok", model.ImageTypePrimary)
Expect(queued(ctx, ds, "al", "alok")).To(BeNil())
ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "alok", model.ImageTypePrimary)
Expect(err).ToNot(HaveOccurred())
Expect(ia.Source).To(Equal("folder"))
})
It("reschedules past the provider's requested delay when it exceeds the backoff", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al9", Name: "Album"}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al9", Name: "Album"})
// Well above backoff(0)'s jittered ceiling, so only the hint can produce this retry_at.
const askedFor = 90 * time.Minute
imageAgents(&fakeImageAgent{name: "throttledAgent", err: &agents.RetryLaterError{RetryIn: askedFor}})
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al9"})).To(Succeed())
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al9"})).To(Succeed())
n, err := w.drain(ctx, 2)
Expect(err).ToNot(HaveOccurred())
Expect(n).To(Equal(1))
it := findQueued(queueRepo, "al", "al9")
it := queued(ctx, ds, "al", "al9")
Expect(it).ToNot(BeNil())
Expect(it.RetryAt).To(BeTemporally("~", time.Now().Add(askedFor), time.Minute))
})
It("reschedules a found-stale item via MarkFailed while keeping its served state", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external, cover.jpg" })
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "alstale", Name: "Album", FolderIDs: []string{"f1"}},
})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alstale", Name: "Album", FolderIDs: []string{fid}})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alstale"})).To(Succeed())
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alstale"})).To(Succeed())
n, err := w.drain(ctx, 2)
Expect(err).ToNot(HaveOccurred())
Expect(n).To(Equal(1))
it := findQueued(queueRepo, "al", "alstale")
it := queued(ctx, ds, "al", "alstale")
Expect(it).ToNot(BeNil(), "a found-stale row must survive for a higher-priority retry")
Expect(it.Attempts).To(Equal(1))
Expect(it.RetryAt).To(BeTemporally(">", time.Now()))
ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "alstale", model.ImageTypePrimary)
ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "alstale", model.ImageTypePrimary)
Expect(err).ToNot(HaveOccurred())
Expect(ia.Source).To(Equal("folder"), "the fallback art is served meanwhile")
@ -368,17 +301,10 @@ var _ = Describe("Worker", func() {
})
It("keeps a row re-enqueued between dequeue and delete", func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al7", Name: "Album", FolderIDs: []string{"f1"}},
})
racing := &reenqueueOnDequeue{MockArtworkQueueRepo: queueRepo}
ds.MockedArtworkQueue = racing
w = NewWorker(ds, store, ag, ffm, broker, imgCache)
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al7", Name: "Album", FolderIDs: []string{fid}})
w = NewWorker(withRacingQueue(ds), store, ag, ffm, broker, imgCache)
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{
ItemKind: "al", ItemID: "al7", Priority: model.ArtworkPriorityScan,
})).To(Succeed())
@ -387,28 +313,26 @@ var _ = Describe("Worker", func() {
Expect(n).To(Equal(1))
// The concurrent re-enqueue changed retry_at, so the found-path delete was a no-op.
Expect(findQueued(queueRepo, "al", "al7")).ToNot(BeNil())
ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al7", model.ImageTypePrimary)
Expect(queued(ctx, ds, "al", "al7")).ToNot(BeNil())
ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al7", model.ImageTypePrimary)
Expect(err).ToNot(HaveOccurred())
Expect(ia.Source).To(Equal("folder"))
})
It("keeps a fresh re-enqueue ahead of a stale failure backoff", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al8", Name: "Album"}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al8", Name: "Album"})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
racing := &reenqueueOnDequeue{MockArtworkQueueRepo: queueRepo}
ds.MockedArtworkQueue = racing
w = NewWorker(ds, store, ag, ffm, broker, imgCache)
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al8"})).To(Succeed())
dequeued := findQueued(queueRepo, "al", "al8").RetryAt
w = NewWorker(withRacingQueue(ds), store, ag, ffm, broker, imgCache)
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al8"})).To(Succeed())
dequeued := queued(ctx, ds, "al", "al8").RetryAt
n, err := w.drain(ctx, 1)
Expect(err).ToNot(HaveOccurred())
Expect(n).To(Equal(1))
// The re-enqueue reset retry_at; the failure path must not stomp it nor bump attempts.
it := findQueued(queueRepo, "al", "al8")
it := queued(ctx, ds, "al", "al8")
Expect(it).ToNot(BeNil())
Expect(it.Attempts).To(BeZero())
Expect(it.RetryAt).To(BeTemporally("==", dequeued.Add(time.Minute)))
@ -416,56 +340,56 @@ var _ = Describe("Worker", func() {
It("gives up and settles absent once the retry budget is exhausted", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al9", Name: "Album"}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al9", Name: "Album"})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
w = NewWorker(ds, store, ag, ffm, broker, imgCache)
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al9"})).To(Succeed())
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al9"})).To(Succeed())
// Age the row past the retry budget.
expireQueued(queueRepo, "al9")
expireQueued("al", "al9")
n, err := w.drain(ctx, 1)
Expect(err).ToNot(HaveOccurred())
Expect(n).To(Equal(1))
Expect(findQueued(queueRepo, "al", "al9")).To(BeNil())
ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al9", model.ImageTypePrimary)
Expect(queued(ctx, ds, "al", "al9")).To(BeNil())
ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al9", model.ImageTypePrimary)
Expect(err).ToNot(HaveOccurred())
Expect(ia.Hash).To(BeEmpty())
})
It("keeps already-served art when the retry budget is exhausted", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al10", Name: "Album"}})
Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al10", Name: "Album"})
Expect(ds.Artwork().PutItemArtwork(ctx, &model.ItemArtwork{
ItemKind: "al", ItemID: "al10", ImageType: model.ImageTypePrimary,
Hash: "cafebabe", Source: "external:lastfm",
})).To(Succeed())
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
w = NewWorker(ds, store, ag, ffm, broker, imgCache)
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al10"})).To(Succeed())
expireQueued(queueRepo, "al10")
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al10"})).To(Succeed())
expireQueued("al", "al10")
n, err := w.drain(ctx, 1)
Expect(err).ToNot(HaveOccurred())
Expect(n).To(Equal(1))
Expect(findQueued(queueRepo, "al", "al10")).To(BeNil())
ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al10", model.ImageTypePrimary)
Expect(queued(ctx, ds, "al", "al10")).To(BeNil())
ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al10", model.ImageTypePrimary)
Expect(err).ToNot(HaveOccurred())
Expect(ia.Hash).To(Equal("cafebabe"), "a persistent outage must not discard served art")
})
It("records on the queue row why the last attempt failed", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al11", Name: "Album"}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al11", Name: "Album"})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
w = NewWorker(ds, store, ag, ffm, broker, imgCache)
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al11"})).To(Succeed())
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al11"})).To(Succeed())
_, err := w.drain(ctx, 1)
Expect(err).ToNot(HaveOccurred())
it := findQueued(queueRepo, "al", "al11")
it := queued(ctx, ds, "al", "al11")
Expect(it).ToNot(BeNil())
Expect(DecodeTrace(it.Trace, "")).To(ContainElement(SatisfyAll(
HaveField("Candidate", "external:failAgent"),
@ -478,16 +402,16 @@ var _ = Describe("Worker", func() {
// failure is written. Recording first would silently lose it for every unresolved item.
It("keeps the failure for an item that never resolved at all", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al13", Name: "Album"}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al13", Name: "Album"})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
w = NewWorker(ds, store, ag, ffm, broker, imgCache)
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al13"})).To(Succeed())
expireQueued(queueRepo, "al13")
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al13"})).To(Succeed())
expireQueued("al", "al13")
_, err := w.drain(ctx, 1)
Expect(err).ToNot(HaveOccurred())
ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al13", model.ImageTypePrimary)
ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al13", model.ImageTypePrimary)
Expect(err).ToNot(HaveOccurred(), "settling absent must create the row the failure is written to")
Expect(ia.Hash).To(BeEmpty())
Expect(DecodeTrace(ia.LastFailure, "")).ToNot(BeEmpty())
@ -495,21 +419,21 @@ var _ = Describe("Worker", func() {
It("keeps the failure on the state row after the queue row is deleted", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al12", Name: "Album"}})
Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al12", Name: "Album"})
Expect(ds.Artwork().PutItemArtwork(ctx, &model.ItemArtwork{
ItemKind: "al", ItemID: "al12", ImageType: model.ImageTypePrimary,
Hash: "cafebabe", Source: "external:lastfm",
})).To(Succeed())
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
w = NewWorker(ds, store, ag, ffm, broker, imgCache)
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al12"})).To(Succeed())
expireQueued(queueRepo, "al12")
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al12"})).To(Succeed())
expireQueued("al", "al12")
_, err := w.drain(ctx, 1)
Expect(err).ToNot(HaveOccurred())
Expect(findQueued(queueRepo, "al", "al12")).To(BeNil())
ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al12", model.ImageTypePrimary)
Expect(queued(ctx, ds, "al", "al12")).To(BeNil())
ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al12", model.ImageTypePrimary)
Expect(err).ToNot(HaveOccurred())
Expect(DecodeTrace(ia.LastFailure, "")).ToNot(BeEmpty(),
"the queue row is gone, so this is the only remaining record of the failure")
@ -520,19 +444,16 @@ var _ = Describe("Worker", func() {
// doing so: a transient read error would look permanent.
It("does not settle absent on exhaustion for a media file", func() {
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true })
ds.MockedMediaFile = tests.CreateMockMediaFileRepo()
ds.MockedMediaFile.(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: "mfX", LibraryID: 0, Path: "tests/fixtures/artist/an-album/gone.mp3", HasCoverArt: true},
})
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "mf", ItemID: "mfX"})).To(Succeed())
expireQueued(queueRepo, "mfX")
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mfX", Path: fixtureAlbumDir + "/gone.mp3", HasCoverArt: true})
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "mf", ItemID: "mfX"})).To(Succeed())
expireQueued("mf", "mfX")
n, err := w.drain(ctx, 1)
Expect(err).ToNot(HaveOccurred())
Expect(n).To(Equal(1))
Expect(findQueued(queueRepo, "mf", "mfX")).To(BeNil(), "the row must stop retrying")
_, err = artRepo.GetItemArtwork(ctx, model.KindMediaFileArtwork, "mfX", model.ImageTypePrimary)
Expect(queued(ctx, ds, "mf", "mfX")).To(BeNil(), "the row must stop retrying")
_, err = ds.Artwork().GetItemArtwork(ctx, model.KindMediaFileArtwork, "mfX", model.ImageTypePrimary)
Expect(err).To(MatchError(model.ErrNotFound),
"no row leaves the track unresolved, so a later view can still recover it")
// Known gap: with no row and no absent settle, there is nowhere to keep the failure.
@ -540,21 +461,15 @@ var _ = Describe("Worker", func() {
})
It("resolves a private playlist under an admin context instead of failing forever", func() {
ds.MockedUser = adminUserRepo()
vds := &visibilityPlaylistDS{
MockDataStore: ds,
private: model.Playlist{ID: "plPriv", OwnerID: "admin"},
tracks: &tests.MockPlaylistTrackRepo{},
}
w = NewWorker(vds, store, ag, ffm, broker, imgCache)
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "plPriv"})).To(Succeed())
putPlaylist(ctx, ds, model.Playlist{ID: "plPriv", Name: "Private", Public: false})
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "plPriv"})).To(Succeed())
n, err := w.drain(ctx, 1)
Expect(err).ToNot(HaveOccurred())
Expect(n).To(Equal(1))
Expect(findQueued(queueRepo, "pl", "plPriv")).To(BeNil())
ia, err := artRepo.GetItemArtwork(ctx, model.KindPlaylistArtwork, "plPriv", model.ImageTypePrimary)
Expect(queued(ctx, ds, "pl", "plPriv")).To(BeNil())
ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindPlaylistArtwork, "plPriv", model.ImageTypePrimary)
Expect(err).ToNot(HaveOccurred())
Expect(ia.Hash).To(BeEmpty())
})
@ -566,17 +481,14 @@ var _ = Describe("Worker", func() {
})
It("broadcasts a single refresh event for the found items in a batch", func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al1", Name: "Album 1", FolderIDs: []string{"f1"}},
{ID: "al2", Name: "Album 2", FolderIDs: []string{"f1"}},
})
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al1", Priority: model.ArtworkPriorityScan})).To(Succeed())
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al2", Priority: model.ArtworkPriorityScan})).To(Succeed())
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar1", Priority: model.ArtworkPriorityScan})).To(Succeed())
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds,
model.Album{ID: "al1", Name: "Album 1", FolderIDs: []string{fid}},
model.Album{ID: "al2", Name: "Album 2", FolderIDs: []string{fid}},
)
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al1", Priority: model.ArtworkPriorityScan})).To(Succeed())
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al2", Priority: model.ArtworkPriorityScan})).To(Succeed())
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar1", Priority: model.ArtworkPriorityScan})).To(Succeed())
n, err := w.drain(ctx, 3)
Expect(err).ToNot(HaveOccurred())
@ -621,9 +533,8 @@ var _ = Describe("Worker", func() {
It("broadcasts a refresh when an item resolves to absent (removed cover)", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*" }) // local-only; no folder image → absent
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al3", Name: "Artless"}})
folderRepo.result = nil
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al3", Priority: model.ArtworkPriorityScan})).To(Succeed())
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al3", Name: "Artless"})
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al3", Priority: model.ArtworkPriorityScan})).To(Succeed())
n, err := w.drain(ctx, 2)
Expect(err).ToNot(HaveOccurred())
@ -633,16 +544,16 @@ var _ = Describe("Worker", func() {
Expect(evts).To(HaveLen(1), "a removed cover must live-refresh clients so they drop it")
Expect(evts[0].(*events.RefreshResource).Data(evts[0])).To(ContainSubstring("al3"))
ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al3", model.ImageTypePrimary)
ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al3", model.ImageTypePrimary)
Expect(err).ToNot(HaveOccurred())
Expect(ia.Hash).To(BeEmpty(), "the outcome was absent, not found")
})
It("does not broadcast when no item is found", func() {
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" })
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alx", Name: "Album"}})
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alx", Name: "Album"})
imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")})
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alx"})).To(Succeed())
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alx"})).To(Succeed())
n, err := w.drain(ctx, 2)
Expect(err).ToNot(HaveOccurred())
@ -768,15 +679,10 @@ var _ = Describe("Worker", func() {
Describe("precache", func() {
BeforeEach(func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "alpc", Name: "Album", FolderIDs: []string{"f1"}},
})
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alpc", Name: "Album", FolderIDs: []string{fid}})
conf.Update(func(c *conf.Options) { c.UICoverArtSize = 300 })
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{
ItemKind: "al", ItemID: "alpc", Priority: model.ArtworkPriorityScan,
})).To(Succeed())
})
@ -848,12 +754,8 @@ var _ = Describe("Worker", func() {
c.CoverArtPriority = "cover.jpg"
c.ArtistArtPriority = "external"
})
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alx", Name: "Album", FolderIDs: []string{"f1"}}})
ds.MockedArtist = tests.CreateMockArtistRepo()
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alx", Name: "Album", FolderIDs: []string{fid}})
// Every artist lookup blocks until released, standing in for the rate limiter.
block := make(chan struct{})
@ -861,16 +763,16 @@ var _ = Describe("Worker", func() {
for i := range 8 {
artists = append(artists, model.Artist{ID: fmt.Sprintf("arx%d", i), Name: "A"})
}
ds.MockedArtist.(*tests.MockArtistRepo).SetData(artists)
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artists...)
imageAgents(&fakeImageAgent{name: "slowAgent", block: block})
// Artists first, exactly as Backfill orders them.
for _, a := range artists {
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{
ItemKind: "ar", ItemID: a.ID, Priority: model.ArtworkPriorityBackfill,
})).To(Succeed())
}
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{
ItemKind: "al", ItemID: "alx", Priority: model.ArtworkPriorityBackfill,
})).To(Succeed())
@ -885,12 +787,12 @@ var _ = Describe("Worker", func() {
})
Eventually(func() bool {
ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "alx", model.ImageTypePrimary)
ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "alx", model.ImageTypePrimary)
return err == nil && ia.Hash != ""
}, 5*time.Second, 50*time.Millisecond).Should(BeTrue(),
"a blocked external pool must not hold up local artwork")
_, err := artRepo.GetItemArtwork(ctx, model.KindArtistArtwork, "arx0", model.ImageTypePrimary)
_, err := ds.Artwork().GetItemArtwork(ctx, model.KindArtistArtwork, "arx0", model.ImageTypePrimary)
Expect(err).To(MatchError(model.ErrNotFound), "artists are still blocked, as intended")
})
})
@ -902,55 +804,52 @@ var _ = Describe("Worker", func() {
for i := range 8 {
id := fmt.Sprintf("alc%d", i)
albums = append(albums, model.Album{ID: id, Name: "Album"})
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{
ItemKind: "al", ItemID: id, Priority: model.ArtworkPriorityScan,
})).To(Succeed())
}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(albums)
cancelledCtx, cancel := context.WithCancel(ctx)
cancel()
persistencetest.PutAlbums(ctx, ds, albums...)
drainCtx, cancel := context.WithCancel(ctx)
w = NewWorker(withQueue(ds, &cancelOnDequeue{ArtworkQueueRepository: ds.ArtworkQueue(), cancel: cancel}),
store, ag, ffm, broker, imgCache)
_, err := w.drain(cancelledCtx, 1)
n, err := w.drain(drainCtx, 1)
Expect(err).ToNot(HaveOccurred())
Expect(n).To(Equal(8), "the whole batch was read before the cancellation")
for i := range 8 {
id := fmt.Sprintf("alc%d", i)
Expect(findQueued(queueRepo, "al", id)).ToNot(BeNil(), "row "+id+" must survive a cancelled drain")
Expect(queued(ctx, ds, "al", id)).ToNot(BeNil(), "row "+id+" must survive a cancelled drain")
}
})
It("stops dispatching and leaves the rest queued when paused mid-batch", func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
albums := model.Albums{}
for i := range 8 {
id := fmt.Sprintf("alp%d", i)
albums = append(albums, model.Album{ID: id, Name: "Album", FolderIDs: []string{"f1"}})
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
albums = append(albums, model.Album{ID: id, Name: "Album", FolderIDs: []string{fid}})
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{
ItemKind: "al", ItemID: id, Priority: model.ArtworkPriorityScan,
})).To(Succeed())
}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(albums)
persistencetest.PutAlbums(ctx, ds, albums...)
// Pauses as soon as the first item has left the queue.
w.PauseWhile(func() bool {
n, _ := queueRepo.Count(ctx)
n, _ := ds.ArtworkQueue().Count(ctx)
return n < 8
})
_, err := w.drain(ctx, 1)
Expect(err).ToNot(HaveOccurred())
count, err := queueRepo.Count(ctx)
Expect(err).ToNot(HaveOccurred())
Expect(count).To(Equal(int64(7)), "only the item dispatched before the pause may leave the queue")
Expect(queueCount(ctx, ds)).To(Equal(int64(7)), "only the item dispatched before the pause may leave the queue")
})
It("dequeues past the worker pool so one drain covers many items", func() {
for i := range 16 {
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: fmt.Sprintf("alb%d", i), Name: "Album"}})
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
persistencetest.PutAlbums(ctx, ds, model.Album{ID: fmt.Sprintf("alb%d", i), Name: "Album"})
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{
ItemKind: "al", ItemID: fmt.Sprintf("alb%d", i), Priority: model.ArtworkPriorityScan,
})).To(Succeed())
}
@ -978,14 +877,9 @@ var _ = Describe("Worker", func() {
})
It("does not drain the queue while paused", func() {
folderRepo.result = []model.Folder{{
Path: "tests/fixtures/artist/an-album",
ImageFiles: []string{"cover.jpg"},
}}
ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: "al1", Name: "Album", FolderIDs: []string{"f1"}},
})
Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{
fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg")
persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", FolderIDs: []string{fid}})
Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{
ItemKind: "al", ItemID: "al1", Priority: model.ArtworkPriorityScan,
})).To(Succeed())
w.PauseWhile(func() bool { return true })
@ -998,7 +892,7 @@ var _ = Describe("Worker", func() {
Eventually(done, 2*time.Second).Should(Receive(BeNil()))
})
Consistently(func() any { return findQueued(queueRepo, "al", "al1") }, 300*time.Millisecond).ShouldNot(BeNil())
Consistently(func() any { return queued(ctx, ds, "al", "al1") }, 300*time.Millisecond).ShouldNot(BeNil())
})
It("does not leak goroutines after Run exits", func() {
@ -1006,8 +900,7 @@ var _ = Describe("Worker", func() {
ignore := goleak.IgnoreCurrent()
DeferCleanup(func() { goleak.VerifyNone(GinkgoT(), ignore) })
localDS := &tests.MockDataStore{MockedArtworkQueue: tests.CreateMockArtworkQueueRepo()}
lw := NewWorker(localDS, NewImageStore(GinkgoT().TempDir()), agents.GetAgents(localDS, nil), tests.NewMockFFmpeg(""), &fakeEventBroker{}, imgCache)
lw := NewWorker(ds, NewImageStore(GinkgoT().TempDir()), ag, tests.NewMockFFmpeg(""), &fakeEventBroker{}, imgCache)
runCtx, cancel := context.WithCancel(ctx)
done := make(chan error, 1)

View file

@ -8,6 +8,7 @@ import (
"time"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/gomega"
)
@ -83,8 +84,9 @@ func TestArtworkBreakerDoesNotCloseOnAnIsolatedAnswer(t *testing.T) {
func TestArtworkGatePerAgentBreakerIsolation(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
g := NewWithT(t)
w := NewWorker(&tests.MockDataStore{}, NewImageStore(t.TempDir()),
agents.GetAgents(&tests.MockDataStore{}, nil), tests.NewMockFFmpeg(""), &fakeEventBroker{}, nil)
noDS := struct{ model.DataStore }{}
w := NewWorker(noDS, NewImageStore(t.TempDir()),
agents.GetAgents(noDS, nil), tests.NewMockFFmpeg(""), &fakeEventBroker{}, nil)
fail := func() (io.ReadCloser, string, error) { return nil, "", errors.New("boom") }
for range breakerThreshold {

View file

@ -8,20 +8,24 @@ import (
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestAuth(t *testing.T) {
log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Auth Test Suite")
}
var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()
const (
oneDay = 24 * time.Hour
@ -34,10 +38,7 @@ var _ = BeforeSuite(func() {
var _ = Describe("Auth", func() {
BeforeEach(func() {
ds := &tests.MockDataStore{
MockedProperty: &tests.MockedPropertyRepo{},
}
auth.Init(ds)
auth.Init(persistence.New(db.Db()))
})
Describe("Validate", func() {
@ -87,7 +88,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

@ -7,48 +7,49 @@ import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
)
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"))
})
})
Describe("AbsolutePath", func() {
var (
ds *tests.MockDataStore
ds model.DataStore
libId int
path string
)
BeforeEach(func() {
ds = &tests.MockDataStore{}
libId = 1
ds = persistence.New(db.Db())
path = "music/file.mp3"
mockLib := &tests.MockLibraryRepo{}
mockLib.SetData(model.Libraries{{ID: libId, Path: "/library/root"}})
ds.MockedLibrary = mockLib
libId = persistencetest.SetLibraries(ctx, ds, "/other", "/library/root")[1]
})
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

@ -5,6 +5,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -13,8 +14,10 @@ import (
func TestCore(t *testing.T) {
tests.Init(t, false)
log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Core Suite")
}
var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

4
core/external/export_test.go vendored Normal file
View file

@ -0,0 +1,4 @@
package external
func QueuedAlbumRefreshes(p Provider) int { return len(p.(*provider).albumQueue) }
func QueuedArtistRefreshes(p Provider) int { return len(p.(*provider).artistQueue) }

View file

@ -6,175 +6,40 @@ import (
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/utils/slice"
"github.com/stretchr/testify/mock"
)
// --- Shared Mock Implementations ---
var adminUser = model.User{ID: "admin-1", UserName: "admin-1", IsAdmin: true}
// mockArtistRepo mocks model.ArtistRepository
type mockArtistRepo struct {
mock.Mock
// credited returns participants crediting the artists in the main artist role.
func credited(artists ...model.Artist) model.Participants {
p := model.Participants{}
p.Add(model.RoleArtist, artists...)
return p
}
var errDBDown = errors.New("db down")
// failingArtists serves an artist repository whose lookups fail with err.
func failingArtists(ds model.DataStore, err error) model.DataStore {
return persistencetest.Stub(ds, persistencetest.Repos{Artist: func(r model.ArtistRepository) model.ArtistRepository {
return failingArtistRepo{r, err}
}})
}
type failingArtistRepo struct {
model.ArtistRepository
err error
}
func newMockArtistRepo() *mockArtistRepo {
return &mockArtistRepo{}
func (r failingArtistRepo) Get(context.Context, string) (*model.Artist, error) {
return nil, r.err
}
// SetData sets up basic Get expectations.
func (m *mockArtistRepo) SetData(artists model.Artists) {
for _, a := range artists {
artistCopy := a
m.On("Get", artistCopy.ID).Return(&artistCopy, nil)
}
}
// Get implements model.ArtistRepository.
func (m *mockArtistRepo) Get(_ context.Context, id string) (*model.Artist, error) {
args := m.Called(id)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*model.Artist), args.Error(1)
}
// GetAll implements model.ArtistRepository.
func (m *mockArtistRepo) GetAll(_ context.Context, options ...model.QueryOptions) (model.Artists, error) {
argsSlice := make([]any, len(options))
for i, v := range options {
argsSlice[i] = v
}
args := m.Called(argsSlice...)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(model.Artists), args.Error(1)
}
// SetError is a helper to set up a generic error for GetAll.
func (m *mockArtistRepo) SetError(hasError bool) {
if hasError {
m.On("GetAll", mock.Anything).Return(nil, errors.New("mock repo error"))
}
}
// FindByName is a helper to set up a GetAll expectation for finding by name.
func (m *mockArtistRepo) FindByName(name string, artist model.Artist) {
m.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
return opt.Filters != nil
})).Return(model.Artists{artist}, nil).Once()
}
// mockMediaFileRepo mocks model.MediaFileRepository
type mockMediaFileRepo struct {
mock.Mock
model.MediaFileRepository
}
func newMockMediaFileRepo() *mockMediaFileRepo {
return &mockMediaFileRepo{}
}
// SetData sets up basic Get expectations.
func (m *mockMediaFileRepo) SetData(mediaFiles model.MediaFiles) {
for _, mf := range mediaFiles {
mfCopy := mf
m.On("Get", mfCopy.ID).Return(&mfCopy, nil)
}
}
// Get implements model.MediaFileRepository.
func (m *mockMediaFileRepo) Get(ctx context.Context, id string) (*model.MediaFile, error) {
args := m.Called(id)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*model.MediaFile), args.Error(1)
}
// GetAllByTags implements model.MediaFileRepository.
func (m *mockMediaFileRepo) GetAllByTags(ctx context.Context, _ model.TagName, _ []string, options ...model.QueryOptions) (model.MediaFiles, error) {
return m.GetAll(ctx, options...)
}
// GetAll implements model.MediaFileRepository.
func (m *mockMediaFileRepo) GetAll(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) {
argsSlice := make([]any, len(options))
for i, v := range options {
argsSlice[i] = v
}
args := m.Called(argsSlice...)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(model.MediaFiles), args.Error(1)
}
// GetRandom implements model.MediaFileRepository.
func (m *mockMediaFileRepo) GetRandom(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) {
argsSlice := make([]any, len(options))
for i, v := range options {
argsSlice[i] = v
}
args := m.Called(argsSlice...)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(model.MediaFiles), args.Error(1)
}
// SetError is a helper to set up a generic error for GetAll.
func (m *mockMediaFileRepo) SetError(hasError bool) {
if hasError {
m.On("GetAll", mock.Anything).Return(nil, errors.New("mock repo error"))
}
}
// FindByMBID is a helper to set up a GetAll expectation for finding by MBID.
func (m *mockMediaFileRepo) FindByMBID(mbid string, mediaFile model.MediaFile) {
m.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
return opt.Filters != nil
})).Return(model.MediaFiles{mediaFile}, nil).Once()
}
// FindByArtistAndTitle is a helper to set up a GetAll expectation for finding by artist/title.
func (m *mockMediaFileRepo) FindByArtistAndTitle(artistID string, title string, mediaFile model.MediaFile) {
m.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool {
return opt.Filters != nil
})).Return(model.MediaFiles{mediaFile}, nil).Once()
}
// mockAlbumRepo mocks model.AlbumRepository
type mockAlbumRepo struct {
mock.Mock
model.AlbumRepository
}
func newMockAlbumRepo() *mockAlbumRepo {
return &mockAlbumRepo{}
}
// Get implements model.AlbumRepository.
func (m *mockAlbumRepo) Get(_ context.Context, id string) (*model.Album, error) {
args := m.Called(id)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*model.Album), args.Error(1)
}
// GetAll implements model.AlbumRepository.
func (m *mockAlbumRepo) GetAll(_ context.Context, options ...model.QueryOptions) (model.Albums, error) {
argsSlice := make([]any, len(options))
for i, v := range options {
argsSlice[i] = v
}
args := m.Called(argsSlice...)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(model.Albums), args.Error(1)
func (r failingArtistRepo) GetAll(context.Context, ...model.QueryOptions) (model.Artists, error) {
return nil, r.err
}
// mockSimilarArtistAgent mocks agents implementing ArtistTopSongsRetriever and ArtistSimilarRetriever

View file

@ -5,6 +5,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@ -13,8 +14,10 @@ import (
func TestExternal(t *testing.T) {
tests.Init(t, false)
log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail)
RunSpecs(t, "External Suite")
}
var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

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"
@ -87,10 +87,11 @@ type Agents interface {
agents.SimilarSongsByArtistRetriever
}
func NewProvider(ds model.DataStore, agents Agents, m *matcher.Matcher, broker events.Broker) Provider {
// NewProvider runs background info refreshes until ctx is done.
func NewProvider(ctx context.Context, ds model.DataStore, agents Agents, m *matcher.Matcher, broker events.Broker) Provider {
e := &provider{ds: ds, ag: agents, matcher: m, broker: broker}
e.artistQueue = newRefreshQueue(context.TODO(), e.populateArtistInfo)
e.albumQueue = newRefreshQueue(context.TODO(), e.populateAlbumInfo)
e.artistQueue = newRefreshQueue(ctx, e.populateArtistInfo)
e.albumQueue = newRefreshQueue(ctx, e.populateAlbumInfo)
return e
}
@ -125,7 +126,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)
@ -133,10 +134,7 @@ func (e *provider) UpdateAlbumInfo(ctx context.Context, id string) (*model.Album
if err != nil {
return nil, err
}
}
// If info is expired, trigger a populateAlbumInfo in the background
if time.Since(updatedAt) > conf.Server().DevAlbumInfoTimeToLive {
} else if time.Since(updatedAt) > conf.Server().DevAlbumInfoTimeToLive {
log.Debug("Found expired cached AlbumInfo, refreshing in the background", "updatedAt", album.ExternalInfoUpdatedAt, "name", albumName)
e.albumQueue.enqueue(&album)
}
@ -232,7 +230,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)
@ -240,10 +238,7 @@ func (e *provider) refreshArtistInfo(ctx context.Context, id string) (auxArtist,
if err != nil {
return auxArtist{}, err
}
}
// If info is expired, trigger a populateArtistInfo in the background
if time.Since(updatedAt) > conf.Server().DevArtistInfoTimeToLive {
} else if time.Since(updatedAt) > conf.Server().DevArtistInfoTimeToLive {
log.Debug("Found expired cached ArtistInfo, refreshing in the background", "updatedAt", updatedAt, "name", artistName)
e.artistQueue.enqueue(&artist)
}

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