Compare commits

..

66 commits

Author SHA1 Message Date
Santhi Prakash
375615253f
fix(release): skip useradd's /etc/skel copy to prevent SELinux AVC (#6364)
useradd --create-home copies /etc/skel as useradd_t, and SELinux denies
file creation on the var_lib_t target, so installing the RPM on an
enforcing distro logs an AVC for .bash_logout (and the file never lands).

Use --no-create-home and create /var/lib/navidrome with install -d in the
scriptlet context instead. The home dir no longer receives skel files,
which are useless for a system service account.

Fixes #6360

Signed-off-by: Santhi Prakash <b.santhiprakash@gmail.com>
2026-11-24 21:05:57 -05:00
Deluan Quintão
49a122f045
refactor(api): bind API v1 request bodies to the validated value (#6543) 2026-11-24 20:23:17 -05:00
Deluan Quintão
a1b4d679ab
feat(api): add API v1 authentication with grants and password login (#6245) 2026-11-24 20:01:06 -05:00
Deluan Quintão
6c48059005
fix(search): keep artist library filter for users without every library (#6542) 2026-11-24 19:40:42 -05:00
Kris Anderson
49ad44d987
fix(server): omit public image URLs for artwork with no ID (#6538) 2026-11-24 18:44:25 -05:00
Deluan
41eb9d459f ci: fail PRs that change the golangci-lint config
The nolint gate only looked for new //nolint directives in Go files. A PR
could get the same result without any directive, by adding an exclusion
rule or disabling a linter in .golangci.yml. The gate now also fails when
a PR changes any .golangci.* file, since golangci-lint also reads the
.yaml, .toml and .json forms. The allow-nolint label still lets a
maintainer approve the change.

Signed-off-by: Deluan <deluan@navidrome.org>
2026-11-24 18:12:46 -05:00
Deluan
a4034da7ad fix(ui): add missing Portuguese (BR) translations 2026-11-24 17:26:04 -05:00
Deluan Quintão
a9d5321dda
fix(ui): stop the user edit form from saying libraries can be left empty (#6539) 2026-11-24 17:14:00 -05:00
Deluan
db3cb311cd docs: add instructions for AI coding agents and update pull request template 2026-11-24 16:23:48 -05:00
Steve Jason
f6da1ebef7
fix(lyrics): match external sidecar with alternate Unicode normalization (#6062) 2026-11-24 12:52:13 -05:00
Deluan Quintão
bb4c789dc6
refactor(cache): simplify the HTTP cache now that it only caches GETs (#6532) 2026-11-23 23:42:23 -05:00
Kris Anderson
7450e1be40
fix(cache): skip the HTTP response cache for non-GET requests (#6531) 2026-11-23 23:20:14 -05:00
Kris Anderson
fbcd90f0ee
fix(scrobbler): log a failed now-playing update once, at warn (#6530)
A failed now-playing call was logged twice: at warn by the ListenBrainz
or Last.fm agent, then at error by dispatchNowPlaying. Now-playing
updates are not retried and the next one replaces them, so a dropped
update is not an error. Log it at warn in dispatchNowPlaying and move
the agents' own lines to debug. Plugin scrobblers don't log the error
themselves, so the worker's warn stays their only line.

Agreed in #6522.

Signed-off-by: Kris Anderson <1562427+kris-anderson@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 21:17:46 -05:00
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
665 changed files with 22343 additions and 15992 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,19 +20,19 @@
### 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.
### How to Test
<!-- Describe the steps to test your changes. Include setup, commands actually run, and results actually observed before and after the change. State how you personally checked the affected functionality. List failed or unrun checks, untested cases, and limitations. -->
### Screenshots / Demos (if applicable)
### Screenshots / Demos
<!-- Add screenshots, GIFs, or links to demos if your change includes UI updates or visual changes. -->
### Additional Notes

65
.github/workflows/check-new-nolint.sh vendored Executable file
View file

@ -0,0 +1,65 @@
#!/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),
# or changes the golangci-lint config, which can silence linters without any //nolint.
# 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}"
status=0
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
}
}' || status=$?
# golangci-lint picks up any of .golangci.{yml,yaml,toml,json}, so a new file in another format counts too.
config_changes=$(git diff --name-only --no-color "$BASE_REF"...HEAD -- '.golangci.*')
if [ -n "$config_changes" ]; then
for f in $config_changes; do
echo "$f: golangci-lint config changed"
if [ "${GITHUB_ACTIONS:-}" = "true" ]; then
echo "::error file=$f::The golangci-lint config changed. A maintainer must approve this with the allow-nolint label."
fi
done
printf "\nThe golangci-lint config changed. A maintainer can approve this with the allow-nolint label.\n"
status=1
fi
exit "$status"

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 and lint config changes 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'),
});

2
.gitignore vendored
View file

@ -28,7 +28,7 @@ docker-compose.yml
binaries
navidrome-*
/ndpgen
AGENTS.md
AGENTS.override.md
.github/prompts
.github/instructions
.github/git-commit-instructions.md

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

55
AGENTS.md Normal file
View file

@ -0,0 +1,55 @@
# Instructions for AI coding agents
Read [CONTRIBUTING.md](CONTRIBUTING.md) before you change code or open a pull request.
## Commands
- Use `make` targets, not raw `go` commands. Raw `go` commands do not set the required `netgo,sqlite_fts5` build tags.
- `make test` runs the Go tests. `make test PKG=./path` runs one package.
- `make lint`, `make format` and `make build` lint, format and build the code.
- Run `make help` to get the up-to-date list of commands
## Tests
- Write Go tests with Ginkgo/Gomega. Use one test file for each production file.
- A test must fail when the behavior it names breaks. Do not write tests that cannot fail, such as:
- a test that checks a mock returns what the test told it to return
- a test that computes the expected value with the same logic as the code under test
- a test that checks fields or constants it just set
- a test that only checks the code runs without an error
- For a bug fix, run the new test without the fix and confirm that it fails.
- If the only possible test is tautological, say so instead of writing it.
## Code comments
- Prefer self-documenting code. Add a comment only to explain *why*, never *what* the code already states.
- Keep each comment to 1 line, 2 at most.
- In a doc comment, the text after the symbol's name must say something the name does not.
- Never put PR or issue history, rejected alternatives, or benchmark numbers in a comment. Put them in the commit message or PR body.
## Do not change without maintainer agreement
- Do not change (Open)Subsonic API routes or behavior. Clients depend on them.
- Add new UI strings only to `ui/src/i18n/en.json`. Do not machine-translate the other languages.
## Commits
- Sign off every commit with `git commit --signoff` (DCO).
- Use the format `<type>(scope): <description>`, as [CONTRIBUTING.md](CONTRIBUTING.md#commit-conventions-and-dco) describes.
- Do not force-push after the PR is open.
## Opening a pull request
- Keep the PR to the agreed scope. Do not add refactors that nobody asked for.
- Write the PR description from [.github/pull_request_template.md](.github/pull_request_template.md). Keep all of its sections. Follow the instructions in the template comment.
- Never check these two boxes:
- "I personally read and reviewed the entire diff..."
- "For code changes, I have the development knowledge..."
Only the person who submits the PR can make these claims. Leave both boxes unchecked. Tell the person to review the diff and check the boxes themselves.
- Answer the "AI use" question with "Yes".
- Leave every other checklist item unchecked unless you verified it.
- Under "How to Test", list only commands that you really ran, with their real results. Say which checks failed or did not run.
- If the change makes any visible change in the UI, add before and after screenshots or a screen recording under "Screenshots / Demos". If you cannot capture them, ask the person to add them.
- Never make up an issue link or a maintainer agreement. If there is none, ask the person.
- Keep the PR text short.

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

@ -22,7 +22,7 @@ DOCKER_TAG ?= navidrome/navidrome:develop
GOLANGCI_LINT_VERSION ?= v2.14.0
VACUUM_VERSION ?= v0.30.6
OAPI_CODEGEN_VERSION ?= v2.8.0
OAPI_CODEGEN_VERSION ?= v2.9.0
OASDIFF_VERSION ?= v1.32.1
API_DIFF_BASE ?= origin/master

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")
)
@ -376,7 +377,7 @@ func (l *lastfmAgent) NowPlaying(ctx context.Context, userId string, track *mode
albumArtist: l.getArtistForScrobble(track, model.RoleAlbumArtist, track.AlbumArtist),
})
if err != nil {
log.Warn(ctx, "Last.fm client.updateNowPlaying returned error", "track", track.Title, err)
log.Debug(ctx, "Last.fm client.updateNowPlaying returned error", "track", track.Title, err)
return errors.Join(err, scrobbler.ErrUnrecoverable)
}
return nil
@ -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

@ -80,7 +80,7 @@ func (l *listenBrainzAgent) NowPlaying(ctx context.Context, userId string, track
li := l.formatListen(track)
err = l.client.updateNowPlaying(ctx, sk, li)
if err != nil {
log.Warn(ctx, "ListenBrainz updateNowPlaying returned error", "track", track.Title, err)
log.Debug(ctx, "ListenBrainz updateNowPlaying returned error", "track", track.Title, err)
return errors.Join(err, scrobbler.ErrUnrecoverable)
}
return nil
@ -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

@ -36,6 +36,15 @@ rules:
- sharing
- radio
- admin
- password
- grants
nd-operation-security-required:
description: Every operation declares security explicitly (use [] for public operations).
severity: error
given: $.paths[*][get,put,post,delete,patch]
then:
field: security
function: defined
nd-operation-stability-level-required:
description: Every operation declares its stability level, which the breaking-change gate relies on.
severity: error

View file

@ -3,7 +3,7 @@
"info": {
"title": "Navidrome API",
"version": "1.0.0",
"description": "Navidrome API v1. Spec-first, additive within v1. Clients discover implemented\ncapability modules through `GET /server` and never sniff versions.\n\nEnums are open: new values may be added to any enum within v1. Clients must\naccept values they do not recognise instead of failing.\n\nEvery operation declares `x-stability-level`: `alpha` operations may change or\ndisappear without notice, `beta` and `stable` operations only change additively.\nA level is only ever raised, never lowered.\n\n`HEAD` is accepted wherever `GET` is. A `405` response lists the allowed methods\nin its `Allow` header.\n",
"description": "Navidrome API v1. Spec-first, additive within v1. Clients discover implemented\ncapability modules through `GET /capabilities` and never sniff versions.\n\nEnums are open: new values may be added to any enum within v1. Clients must\naccept values they do not recognise instead of failing.\n\nEvery operation declares `x-stability-level`: `alpha` operations may change or\ndisappear without notice, `beta` and `stable` operations only change additively.\nA level is only ever raised, never lowered.\n\n`HEAD` is accepted wherever `GET` is. A `405` response lists the allowed methods\nin its `Allow` header.\n\nOperations that need a grant declare `security: [{bearerAuth: []}]` and the scope they need in\n`x-scope` (OpenAPI 3.0 does not allow scopes on bearer schemes). Clients send the grant secret as\n`Authorization: Bearer \u003csecret\u003e`. A revoked grant stops working within one minute at most.\n",
"license": {
"name": "GPL-3.0",
"url": "https://www.gnu.org/licenses/gpl-3.0.html"
@ -18,6 +18,10 @@
{
"name": "server",
"description": "Server discovery and the published OpenAPI document."
},
{
"name": "auth",
"description": "Grants and login methods."
}
],
"paths": {
@ -29,8 +33,9 @@
"tags": [
"server"
],
"security": [],
"summary": "Describe the server",
"description": "Returns the public server description. No authentication required.\nAuthenticated requests will additionally receive the implemented capability modules\nonce authentication is available.\n",
"description": "Returns the public server description. No authentication required.\nCapability modules are listed by `GET /capabilities`.\n",
"responses": {
"200": {
"description": "Server description.",
@ -48,6 +53,41 @@
}
}
},
"/capabilities": {
"get": {
"operationId": "getCapabilities",
"x-module": "core",
"x-stability-level": "alpha",
"tags": [
"server"
],
"summary": "List implemented capability modules",
"description": "The capability modules this server implements. Any valid grant may read it, whatever its scopes.",
"security": [
{
"bearerAuth": []
}
],
"responses": {
"200": {
"description": "Implemented modules.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Capabilities"
}
}
}
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/openapi.json": {
"get": {
"operationId": "getOpenAPISpecJSON",
@ -56,6 +96,7 @@
"tags": [
"server"
],
"security": [],
"summary": "Get the OpenAPI document (JSON)",
"description": "The bundled OpenAPI document of the running server version. Supports ETag revalidation.",
"responses": {
@ -81,6 +122,56 @@
}
}
},
"/auth/grants": {
"get": {
"operationId": "listGrants",
"x-module": "grants",
"x-scope": "grants",
"x-stability-level": "alpha",
"tags": [
"auth"
],
"summary": "List my grants",
"description": "The caller's grants, most recently used first. Grants idle long enough to have expired are not listed.",
"security": [
{
"bearerAuth": []
}
],
"parameters": [
{
"$ref": "#/components/parameters/offset"
},
{
"$ref": "#/components/parameters/limit"
}
],
"responses": {
"200": {
"description": "A page of grants.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/GrantList"
}
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"403": {
"$ref": "#/components/responses/Forbidden"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/openapi.yaml": {
"get": {
"operationId": "getOpenAPISpecYAML",
@ -89,6 +180,7 @@
"tags": [
"server"
],
"security": [],
"summary": "Get the OpenAPI document (YAML)",
"description": "The bundled OpenAPI document of the running server version. Supports ETag revalidation.",
"responses": {
@ -113,6 +205,261 @@
}
}
}
},
"/auth/grants/{id}": {
"delete": {
"operationId": "revokeGrant",
"x-module": "grants",
"x-scope": "grants",
"x-stability-level": "alpha",
"tags": [
"auth"
],
"summary": "Revoke one of my grants",
"description": "Revokes the grant; requests with its secret fail from then on. Another user's grant id answers 404.",
"security": [
{
"bearerAuth": []
}
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"description": "Grant id.",
"schema": {
"type": "string",
"maxLength": 64
}
}
],
"responses": {
"204": {
"description": "Revoked."
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/auth/logout": {
"post": {
"operationId": "logout",
"x-module": "core",
"x-stability-level": "alpha",
"tags": [
"auth"
],
"summary": "Log out",
"description": "Revokes the grant that made this request. Needs no scope, so any grant can end itself.",
"security": [
{
"bearerAuth": []
}
],
"responses": {
"200": {
"description": "Logged out.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/LogoutResponse"
}
}
}
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"403": {
"$ref": "#/components/responses/Forbidden"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/auth/login": {
"post": {
"operationId": "login",
"x-module": "password",
"x-stability-level": "alpha",
"tags": [
"auth"
],
"summary": "Log in with a password",
"description": "Checks the username and password and returns a new grant. Unknown user and wrong password fail the same way.",
"security": [],
"requestBody": {
"description": "The credentials and a description of the client.",
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/CredentialsRequest"
}
}
}
},
"responses": {
"200": {
"description": "The new grant.",
"headers": {
"Cache-Control": {
"$ref": "#/components/headers/CacheControlNoStore"
}
},
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/GrantCreated"
}
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/TooManyRequests"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/auth/setup": {
"post": {
"operationId": "setupFirstAdmin",
"x-module": "password",
"x-stability-level": "alpha",
"tags": [
"auth"
],
"summary": "Create the first admin",
"description": "Creates the first administrator while `setupRequired` is true and returns a grant for it. Answers 409 `setup_complete` once any user exists. A server with no setup step always answers 409.",
"security": [],
"requestBody": {
"description": "The credentials and a description of the client.",
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/CredentialsRequest"
}
}
}
},
"responses": {
"201": {
"description": "The admin was created.",
"headers": {
"Cache-Control": {
"$ref": "#/components/headers/CacheControlNoStore"
}
},
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/GrantCreated"
}
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"409": {
"$ref": "#/components/responses/Conflict"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/TooManyRequests"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
},
"/auth/password": {
"post": {
"operationId": "changePassword",
"x-module": "password",
"x-scope": "password",
"x-stability-level": "alpha",
"tags": [
"auth"
],
"summary": "Change my password",
"description": "Changes the caller's password. By default every other grant of the user is revoked; the calling grant survives. On Navidrome the change also ends the user's sessions on its other APIs, regardless of `revokeOtherGrants`, which only covers API v1 grants. Answers 409 `password_managed_externally` when the password is not stored by this server.",
"security": [
{
"bearerAuth": []
}
],
"requestBody": {
"description": "The current and the new password.",
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PasswordChangeRequest"
}
}
}
},
"responses": {
"204": {
"description": "Password changed."
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"403": {
"$ref": "#/components/responses/Forbidden"
},
"409": {
"$ref": "#/components/responses/Conflict"
},
"413": {
"$ref": "#/components/responses/PayloadTooLarge"
},
"429": {
"$ref": "#/components/responses/TooManyRequests"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
}
},
"components": {
@ -120,8 +467,7 @@
"bearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
"description": "Short-lived access token minted from a device grant. Not yet applied to any operation."
"description": "Grant secret from a login method (`POST /auth/login`, `POST /auth/setup`). Opaque. The required scope is in each operation's `x-scope`."
}
},
"schemas": {
@ -153,17 +499,23 @@
"description": "True until the first admin user has been created."
},
"loginMethods": {
"type": "array",
"description": "Login methods this server accepts. New methods may be added; clients ignore values they do not recognise.",
"items": {
"type": "string",
"enum": [
"password"
]
}
"$ref": "#/components/schemas/LoginMethods"
}
}
},
"LoginMethods": {
"type": "object",
"description": "Login methods this server accepts, keyed by method. A missing key means the method is not offered.\nKeys are optional on purpose: discovery is read by clients of any version against servers of any\nversion, so new methods are added as new optional keys. Clients ignore keys they do not know.\n",
"properties": {
"password": {
"$ref": "#/components/schemas/PasswordLoginMethod"
}
}
},
"PasswordLoginMethod": {
"type": "object",
"description": "Username and password login (`POST /auth/login`). No settings yet."
},
"Problem": {
"type": "object",
"description": "RFC 9457 problem details, returned for every 4xx and 5xx response.",
@ -187,7 +539,7 @@
},
"detail": {
"type": "string",
"description": "Human-readable explanation specific to this occurrence. Omitted for internal errors."
"description": "Human-readable explanation specific to this occurrence. Omitted unless the server marked the text as safe to show clients."
},
"code": {
"type": "string",
@ -196,12 +548,21 @@
"validation",
"unauthorized",
"forbidden",
"insufficient_scope",
"not_found",
"method_not_allowed",
"setup_complete",
"password_managed_externally",
"payload_too_large",
"rate_limited",
"unavailable",
"internal"
]
},
"referenceId": {
"type": "string",
"description": "Present on internal errors. Quote it when reporting a problem; it tags the server's log lines for this request."
},
"errors": {
"type": "array",
"description": "Per-field failures. Present only when `code` is `validation`.",
@ -228,6 +589,327 @@
"description": "Why the value was rejected."
}
}
},
"Capabilities": {
"type": "object",
"description": "Capability modules this server implements, keyed by module. Keys are optional; a missing key means the\nmodule is not implemented. New modules are added as new optional keys. These are server facts, not what\nthe calling grant may use.\n",
"properties": {
"core": {
"$ref": "#/components/schemas/CoreCapability"
},
"password": {
"$ref": "#/components/schemas/PasswordCapability"
},
"grants": {
"$ref": "#/components/schemas/GrantsCapability"
}
}
},
"CoreCapability": {
"type": "object",
"description": "The mandatory core module.",
"required": [
"version"
],
"properties": {
"version": {
"type": "integer",
"description": "Module version. Bumped only on semantic change."
}
}
},
"PasswordCapability": {
"type": "object",
"description": "The password login module (login, first-admin setup, password change).",
"required": [
"version"
],
"properties": {
"version": {
"type": "integer",
"description": "Module version. Bumped only on semantic change."
}
}
},
"GrantsCapability": {
"type": "object",
"description": "The grants module (listing and revoking the user's own grants). Logout stays in core and needs no scope.",
"required": [
"version"
],
"properties": {
"version": {
"type": "integer",
"description": "Module version. Bumped only on semantic change."
}
}
},
"GrantList": {
"type": "object",
"description": "A page of the caller's grants.",
"required": [
"items",
"total",
"offset",
"limit"
],
"properties": {
"items": {
"type": "array",
"description": "Grants on this page, by last use, most recent first; never-used grants last.",
"items": {
"$ref": "#/components/schemas/Grant"
}
},
"total": {
"type": "integer",
"description": "Total number of grants."
},
"offset": {
"type": "integer",
"description": "Zero-based index of the first returned item."
},
"limit": {
"type": "integer",
"description": "Maximum number of items in this page."
}
}
},
"LogoutResponse": {
"type": "object",
"description": "Result of a logout.",
"required": [
"logoutUrl"
],
"properties": {
"logoutUrl": {
"type": "string",
"nullable": true,
"description": "Where to send the browser to finish logging out of an external provider. Null when there is nothing more to do."
}
}
},
"CredentialsRequest": {
"type": "object",
"description": "Username, password and client description for a login or first-admin setup.",
"required": [
"username",
"password",
"client"
],
"properties": {
"username": {
"type": "string",
"minLength": 1,
"maxLength": 255,
"description": "Login name."
},
"password": {
"type": "string",
"minLength": 1,
"maxLength": 1024,
"description": "Password."
},
"client": {
"type": "string",
"minLength": 1,
"maxLength": 64,
"description": "Name of the client app."
},
"clientVersion": {
"type": "string",
"maxLength": 32,
"description": "Version of the client app."
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 64,
"description": "Label for this grant. Defaults to `client`."
},
"scopes": {
"type": "array",
"maxItems": 32,
"description": "Scopes the grant may hold. Omit for `all`.",
"items": {
"$ref": "#/components/schemas/ScopeRequest"
}
}
}
},
"GrantCreated": {
"type": "object",
"description": "Returned by every login method. The secret is shown only here; store it and never parse it.",
"required": [
"secret",
"grant",
"user"
],
"properties": {
"secret": {
"type": "string",
"maxLength": 512,
"description": "Opaque grant secret. Send it as `Authorization: Bearer \u003csecret\u003e`."
},
"grant": {
"description": "The new grant.",
"allOf": [
{
"$ref": "#/components/schemas/Grant"
}
]
},
"user": {
"description": "The user the grant belongs to.",
"allOf": [
{
"$ref": "#/components/schemas/AuthUser"
}
]
}
}
},
"PasswordChangeRequest": {
"type": "object",
"description": "Change the caller's own password.",
"required": [
"currentPassword",
"newPassword"
],
"properties": {
"currentPassword": {
"type": "string",
"minLength": 1,
"maxLength": 1024,
"description": "The current password."
},
"newPassword": {
"type": "string",
"minLength": 1,
"maxLength": 1024,
"description": "The new password."
},
"revokeOtherGrants": {
"type": "boolean",
"default": true,
"description": "Revoke every other grant of the user. The calling grant always survives. Default true."
}
}
},
"Grant": {
"type": "object",
"description": "A long-lived grant held by one client of one user.",
"required": [
"id",
"name",
"client",
"clientVersion",
"scopes",
"provider",
"createdAt",
"lastUsedAt",
"lastUsedIp",
"current"
],
"properties": {
"id": {
"type": "string",
"description": "Grant id."
},
"name": {
"type": "string",
"description": "Label shown to the user."
},
"client": {
"type": "string",
"description": "Name of the client app that holds the grant."
},
"clientVersion": {
"type": "string",
"nullable": true,
"description": "Version of the client app, when it sent one."
},
"scopes": {
"type": "array",
"description": "Scopes this grant carries.",
"items": {
"$ref": "#/components/schemas/Scope"
}
},
"provider": {
"type": "string",
"description": "How the grant was created, for example `password` or `setup`. Free-form; new values may appear."
},
"createdAt": {
"type": "string",
"format": "date-time",
"description": "When the grant was created."
},
"lastUsedAt": {
"type": "string",
"format": "date-time",
"nullable": true,
"description": "When the grant was last used, at a coarse granularity. Null until first use."
},
"lastUsedIp": {
"type": "string",
"nullable": true,
"description": "Client IP of the last use. Null until first use."
},
"current": {
"type": "boolean",
"description": "True for the grant that made this request."
}
}
},
"Scope": {
"type": "string",
"description": "A permission scope. Scopes mirror capability modules; `x:write` includes `x`. `all` appears only on\ngrants and means every scope the user is entitled to, now and in future releases. New scopes may be added.\n",
"enum": [
"all",
"read",
"password",
"grants"
]
},
"ScopeRequest": {
"type": "string",
"description": "A requested scope. Scopes the server does not know are dropped, not rejected, so newer clients keep working.",
"pattern": "^[a-z][a-z-]*(:write)?$",
"maxLength": 64
},
"AuthUser": {
"type": "object",
"description": "The user a grant belongs to.",
"required": [
"id",
"userName",
"name",
"isAdmin",
"passwordChangeable"
],
"properties": {
"id": {
"type": "string",
"description": "User id."
},
"userName": {
"type": "string",
"description": "Login name."
},
"name": {
"type": "string",
"description": "Display name."
},
"isAdmin": {
"type": "boolean",
"description": "Whether the user is an administrator."
},
"passwordChangeable": {
"type": "boolean",
"description": "Whether `POST /auth/password` can change this user's password. Clients hide \"change password\" when false."
}
}
}
},
"responses": {
@ -241,6 +923,21 @@
}
}
},
"Unauthorized": {
"description": "Missing, invalid, or expired credentials.",
"headers": {
"WWW-Authenticate": {
"$ref": "#/components/headers/WWWAuthenticate"
}
},
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
}
},
"NotModified": {
"description": "Not modified.",
"headers": {
@ -248,14 +945,127 @@
"$ref": "#/components/headers/ETag"
}
}
},
"BadRequest": {
"description": "The request is malformed or fails validation.",
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
}
},
"Forbidden": {
"description": "The caller is authenticated but not allowed to do this.",
"headers": {
"WWW-Authenticate": {
"$ref": "#/components/headers/WWWAuthenticate"
}
},
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
}
},
"NotFound": {
"description": "No such resource or endpoint.",
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
}
},
"PayloadTooLarge": {
"description": "The request body is too large (`payload_too_large`).",
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
}
},
"TooManyRequests": {
"description": "Rate limited (`rate_limited`). Retry after the `Retry-After` seconds.",
"headers": {
"Retry-After": {
"description": "Seconds to wait before retrying.",
"schema": {
"type": "integer"
}
}
},
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
}
},
"Conflict": {
"description": "The request conflicts with the server's state, for example `setup_complete` or `password_managed_externally`.",
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
}
}
},
"parameters": {
"offset": {
"name": "offset",
"in": "query",
"description": "Zero-based index of the first item to return.",
"required": false,
"schema": {
"type": "integer",
"minimum": 0,
"default": 0
}
},
"limit": {
"name": "limit",
"in": "query",
"description": "Maximum number of items to return.",
"required": false,
"schema": {
"type": "integer",
"minimum": 1,
"maximum": 2000,
"default": 100
}
}
},
"headers": {
"WWWAuthenticate": {
"description": "RFC 6750 Bearer challenge, for example `Bearer error=\"insufficient_scope\", scope=\"read\"`.",
"schema": {
"type": "string"
}
},
"ETag": {
"description": "Entity tag for `If-None-Match` revalidation.",
"schema": {
"type": "string"
}
},
"CacheControlNoStore": {
"description": "Always `no-store`, because the response carries a secret.",
"schema": {
"type": "string",
"enum": [
"no-store"
]
}
}
}
}

View file

@ -4,7 +4,7 @@ info:
version: 1.0.0
description: |
Navidrome API v1. Spec-first, additive within v1. Clients discover implemented
capability modules through `GET /server` and never sniff versions.
capability modules through `GET /capabilities` and never sniff versions.
Enums are open: new values may be added to any enum within v1. Clients must
accept values they do not recognise instead of failing.
@ -15,6 +15,10 @@ info:
`HEAD` is accepted wherever `GET` is. A `405` response lists the allowed methods
in its `Allow` header.
Operations that need a grant declare `security: [{bearerAuth: []}]` and the scope they need in
`x-scope` (OpenAPI 3.0 does not allow scopes on bearer schemes). Clients send the grant secret as
`Authorization: Bearer <secret>`. A revoked grant stops working within one minute at most.
license:
name: GPL-3.0
url: https://www.gnu.org/licenses/gpl-3.0.html
@ -23,6 +27,8 @@ servers:
tags:
- name: server
description: Server discovery and the published OpenAPI document.
- name: auth
description: Grants and login methods.
paths:
/server:
get:
@ -30,11 +36,11 @@ paths:
x-module: core
x-stability-level: alpha
tags: [server]
security: []
summary: Describe the server
description: |
Returns the public server description. No authentication required.
Authenticated requests will additionally receive the implemented capability modules
once authentication is available.
Capability modules are listed by `GET /capabilities`.
responses:
'200':
description: Server description.
@ -44,12 +50,30 @@ paths:
$ref: '#/components/schemas/ServerInfo'
'500':
$ref: '#/components/responses/InternalError'
/capabilities:
get:
operationId: getCapabilities
x-module: core
x-stability-level: alpha
tags: [server]
summary: List implemented capability modules
description: The capability modules this server implements. Any valid grant may read it, whatever its scopes.
security: [{bearerAuth: []}]
responses:
'200':
description: Implemented modules.
content:
application/json:
schema: {$ref: '#/components/schemas/Capabilities'}
'401': {$ref: '#/components/responses/Unauthorized'}
'500': {$ref: '#/components/responses/InternalError'}
/openapi.json:
get:
operationId: getOpenAPISpecJSON
x-module: core
x-stability-level: alpha
tags: [server]
security: []
summary: Get the OpenAPI document (JSON)
description: The bundled OpenAPI document of the running server version. Supports ETag revalidation.
responses:
@ -65,12 +89,41 @@ paths:
description: OpenAPI 3.0 document.
'304':
$ref: '#/components/responses/NotModified'
/auth/grants:
get:
operationId: listGrants
x-module: grants
x-scope: grants
x-stability-level: alpha
tags: [auth]
summary: List my grants
description: "The caller's grants, most recently used first. Grants idle long enough to have expired are not listed."
security: [{bearerAuth: []}]
parameters:
- $ref: '#/components/parameters/offset'
- $ref: '#/components/parameters/limit'
responses:
'200':
description: A page of grants.
content:
application/json:
schema:
$ref: '#/components/schemas/GrantList'
'400':
$ref: '#/components/responses/BadRequest'
'401':
$ref: '#/components/responses/Unauthorized'
'403':
$ref: '#/components/responses/Forbidden'
'500':
$ref: '#/components/responses/InternalError'
/openapi.yaml:
get:
operationId: getOpenAPISpecYAML
x-module: core
x-stability-level: alpha
tags: [server]
security: []
summary: Get the OpenAPI document (YAML)
description: The bundled OpenAPI document of the running server version. Supports ETag revalidation.
responses:
@ -86,13 +139,171 @@ paths:
description: OpenAPI 3.0 document.
'304':
$ref: '#/components/responses/NotModified'
/auth/grants/{id}:
delete:
operationId: revokeGrant
x-module: grants
x-scope: grants
x-stability-level: alpha
tags: [auth]
summary: Revoke one of my grants
description: "Revokes the grant; requests with its secret fail from then on. Another user's grant id answers 404."
security: [{bearerAuth: []}]
parameters:
- name: id
in: path
required: true
description: Grant id.
schema:
type: string
maxLength: 64
responses:
'204':
description: Revoked.
'400':
$ref: '#/components/responses/BadRequest'
'401':
$ref: '#/components/responses/Unauthorized'
'403':
$ref: '#/components/responses/Forbidden'
'404':
$ref: '#/components/responses/NotFound'
'500':
$ref: '#/components/responses/InternalError'
/auth/logout:
post:
operationId: logout
x-module: core
x-stability-level: alpha
tags: [auth]
summary: Log out
description: Revokes the grant that made this request. Needs no scope, so any grant can end itself.
security: [{bearerAuth: []}]
responses:
'200':
description: Logged out.
content:
application/json:
schema:
$ref: '#/components/schemas/LogoutResponse'
'401':
$ref: '#/components/responses/Unauthorized'
'403':
$ref: '#/components/responses/Forbidden'
'500':
$ref: '#/components/responses/InternalError'
/auth/login:
post:
operationId: login
x-module: password
x-stability-level: alpha
tags: [auth]
summary: Log in with a password
description: Checks the username and password and returns a new grant. Unknown user and wrong password fail the same way.
security: []
requestBody:
description: The credentials and a description of the client.
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CredentialsRequest'
responses:
'200':
description: The new grant.
headers:
Cache-Control:
$ref: '#/components/headers/CacheControlNoStore'
content:
application/json:
schema:
$ref: '#/components/schemas/GrantCreated'
'400':
$ref: '#/components/responses/BadRequest'
'401':
$ref: '#/components/responses/Unauthorized'
'413':
$ref: '#/components/responses/PayloadTooLarge'
'429':
$ref: '#/components/responses/TooManyRequests'
'500':
$ref: '#/components/responses/InternalError'
/auth/setup:
post:
operationId: setupFirstAdmin
x-module: password
x-stability-level: alpha
tags: [auth]
summary: Create the first admin
description: "Creates the first administrator while `setupRequired` is true and returns a grant for it. Answers 409 `setup_complete` once any user exists. A server with no setup step always answers 409."
security: []
requestBody:
description: The credentials and a description of the client.
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CredentialsRequest'
responses:
'201':
description: The admin was created.
headers:
Cache-Control:
$ref: '#/components/headers/CacheControlNoStore'
content:
application/json:
schema:
$ref: '#/components/schemas/GrantCreated'
'400':
$ref: '#/components/responses/BadRequest'
'409':
$ref: '#/components/responses/Conflict'
'413':
$ref: '#/components/responses/PayloadTooLarge'
'429':
$ref: '#/components/responses/TooManyRequests'
'500':
$ref: '#/components/responses/InternalError'
/auth/password:
post:
operationId: changePassword
x-module: password
x-scope: password
x-stability-level: alpha
tags: [auth]
summary: Change my password
description: "Changes the caller's password. By default every other grant of the user is revoked; the calling grant survives. On Navidrome the change also ends the user's sessions on its other APIs, regardless of `revokeOtherGrants`, which only covers API v1 grants. Answers 409 `password_managed_externally` when the password is not stored by this server."
security: [{bearerAuth: []}]
requestBody:
description: The current and the new password.
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/PasswordChangeRequest'
responses:
'204':
description: Password changed.
'400':
$ref: '#/components/responses/BadRequest'
'401':
$ref: '#/components/responses/Unauthorized'
'403':
$ref: '#/components/responses/Forbidden'
'409':
$ref: '#/components/responses/Conflict'
'413':
$ref: '#/components/responses/PayloadTooLarge'
'429':
$ref: '#/components/responses/TooManyRequests'
'500':
$ref: '#/components/responses/InternalError'
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
description: Short-lived access token minted from a device grant. Not yet applied to any operation.
description: "Grant secret from a login method (`POST /auth/login`, `POST /auth/setup`). Opaque. The required scope is in each operation's `x-scope`."
schemas:
ServerInfo:
type: object
@ -117,12 +328,19 @@ components:
type: boolean
description: True until the first admin user has been created.
loginMethods:
type: array
description: Login methods this server accepts. New methods may be added; clients ignore values they do not recognise.
items:
type: string
enum:
- password
$ref: '#/components/schemas/LoginMethods'
LoginMethods:
type: object
description: |
Login methods this server accepts, keyed by method. A missing key means the method is not offered.
Keys are optional on purpose: discovery is read by clients of any version against servers of any
version, so new methods are added as new optional keys. Clients ignore keys they do not know.
properties:
password:
$ref: '#/components/schemas/PasswordLoginMethod'
PasswordLoginMethod:
type: object
description: Username and password login (`POST /auth/login`). No settings yet.
Problem:
type: object
description: RFC 9457 problem details, returned for every 4xx and 5xx response.
@ -145,7 +363,7 @@ components:
description: HTTP status code of this response.
detail:
type: string
description: Human-readable explanation specific to this occurrence. Omitted for internal errors.
description: Human-readable explanation specific to this occurrence. Omitted unless the server marked the text as safe to show clients.
code:
type: string
description: Machine-readable error code, and the value clients switch on. New codes may be added.
@ -153,10 +371,18 @@ components:
- validation
- unauthorized
- forbidden
- insufficient_scope
- not_found
- method_not_allowed
- setup_complete
- password_managed_externally
- payload_too_large
- rate_limited
- unavailable
- internal
referenceId:
type: string
description: Present on internal errors. Quote it when reporting a problem; it tags the server's log lines for this request.
errors:
type: array
description: Per-field failures. Present only when `code` is `validation`.
@ -175,6 +401,250 @@ components:
message:
type: string
description: Why the value was rejected.
Capabilities:
type: object
description: |
Capability modules this server implements, keyed by module. Keys are optional; a missing key means the
module is not implemented. New modules are added as new optional keys. These are server facts, not what
the calling grant may use.
properties:
core:
$ref: '#/components/schemas/CoreCapability'
password:
$ref: '#/components/schemas/PasswordCapability'
grants:
$ref: '#/components/schemas/GrantsCapability'
CoreCapability:
type: object
description: The mandatory core module.
required:
- version
properties:
version:
type: integer
description: Module version. Bumped only on semantic change.
PasswordCapability:
type: object
description: The password login module (login, first-admin setup, password change).
required:
- version
properties:
version:
type: integer
description: Module version. Bumped only on semantic change.
GrantsCapability:
type: object
description: The grants module (listing and revoking the user's own grants). Logout stays in core and needs no scope.
required:
- version
properties:
version:
type: integer
description: Module version. Bumped only on semantic change.
GrantList:
type: object
description: "A page of the caller's grants."
required:
- items
- total
- offset
- limit
properties:
items:
type: array
description: "Grants on this page, by last use, most recent first; never-used grants last."
items:
$ref: '#/components/schemas/Grant'
total:
type: integer
description: Total number of grants.
offset:
type: integer
description: Zero-based index of the first returned item.
limit:
type: integer
description: Maximum number of items in this page.
LogoutResponse:
type: object
description: Result of a logout.
required:
- logoutUrl
properties:
logoutUrl:
type: string
nullable: true
description: "Where to send the browser to finish logging out of an external provider. Null when there is nothing more to do."
CredentialsRequest:
type: object
description: "Username, password and client description for a login or first-admin setup."
required:
- username
- password
- client
properties:
username:
type: string
minLength: 1
maxLength: 255
description: Login name.
password:
type: string
minLength: 1
maxLength: 1024
description: Password.
client:
type: string
minLength: 1
maxLength: 64
description: Name of the client app.
clientVersion:
type: string
maxLength: 32
description: Version of the client app.
name:
type: string
minLength: 1
maxLength: 64
description: "Label for this grant. Defaults to `client`."
scopes:
type: array
maxItems: 32
description: "Scopes the grant may hold. Omit for `all`."
items:
$ref: '#/components/schemas/ScopeRequest'
GrantCreated:
type: object
description: "Returned by every login method. The secret is shown only here; store it and never parse it."
required:
- secret
- grant
- user
properties:
secret:
type: string
maxLength: 512
description: "Opaque grant secret. Send it as `Authorization: Bearer <secret>`."
grant:
description: The new grant.
allOf:
- $ref: '#/components/schemas/Grant'
user:
description: The user the grant belongs to.
allOf:
- $ref: '#/components/schemas/AuthUser'
PasswordChangeRequest:
type: object
description: "Change the caller's own password."
required:
- currentPassword
- newPassword
properties:
currentPassword:
type: string
minLength: 1
maxLength: 1024
description: The current password.
newPassword:
type: string
minLength: 1
maxLength: 1024
description: The new password.
revokeOtherGrants:
type: boolean
default: true
description: "Revoke every other grant of the user. The calling grant always survives. Default true."
Grant:
type: object
description: A long-lived grant held by one client of one user.
required:
- id
- name
- client
- clientVersion
- scopes
- provider
- createdAt
- lastUsedAt
- lastUsedIp
- current
properties:
id:
type: string
description: Grant id.
name:
type: string
description: Label shown to the user.
client:
type: string
description: Name of the client app that holds the grant.
clientVersion:
type: string
nullable: true
description: "Version of the client app, when it sent one."
scopes:
type: array
description: Scopes this grant carries.
items:
$ref: '#/components/schemas/Scope'
provider:
type: string
description: "How the grant was created, for example `password` or `setup`. Free-form; new values may appear."
createdAt:
type: string
format: date-time
description: When the grant was created.
lastUsedAt:
type: string
format: date-time
nullable: true
description: "When the grant was last used, at a coarse granularity. Null until first use."
lastUsedIp:
type: string
nullable: true
description: Client IP of the last use. Null until first use.
current:
type: boolean
description: True for the grant that made this request.
Scope:
type: string
description: |
A permission scope. Scopes mirror capability modules; `x:write` includes `x`. `all` appears only on
grants and means every scope the user is entitled to, now and in future releases. New scopes may be added.
enum:
- all
- read
- password
- grants
ScopeRequest:
type: string
description: "A requested scope. Scopes the server does not know are dropped, not rejected, so newer clients keep working."
pattern: '^[a-z][a-z-]*(:write)?$'
maxLength: 64
AuthUser:
type: object
description: The user a grant belongs to.
required:
- id
- userName
- name
- isAdmin
- passwordChangeable
properties:
id:
type: string
description: User id.
userName:
type: string
description: Login name.
name:
type: string
description: Display name.
isAdmin:
type: boolean
description: Whether the user is an administrator.
passwordChangeable:
type: boolean
description: "Whether `POST /auth/password` can change this user's password. Clients hide \"change password\" when false."
responses:
InternalError:
description: Unexpected server failure. Details are in the server log.
@ -182,13 +652,96 @@ components:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
Unauthorized:
description: Missing, invalid, or expired credentials.
headers:
WWW-Authenticate:
$ref: '#/components/headers/WWWAuthenticate'
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
NotModified:
description: Not modified.
headers:
ETag:
$ref: '#/components/headers/ETag'
BadRequest:
description: The request is malformed or fails validation.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
Forbidden:
description: The caller is authenticated but not allowed to do this.
headers:
WWW-Authenticate:
$ref: '#/components/headers/WWWAuthenticate'
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
NotFound:
description: No such resource or endpoint.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
PayloadTooLarge:
description: "The request body is too large (`payload_too_large`)."
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
TooManyRequests:
description: "Rate limited (`rate_limited`). Retry after the `Retry-After` seconds."
headers:
Retry-After:
description: Seconds to wait before retrying.
schema:
type: integer
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
Conflict:
description: "The request conflicts with the server's state, for example `setup_complete` or `password_managed_externally`."
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
parameters:
offset:
name: offset
in: query
description: Zero-based index of the first item to return.
required: false
schema:
type: integer
minimum: 0
default: 0
limit:
name: limit
in: query
description: Maximum number of items to return.
required: false
schema:
type: integer
minimum: 1
maximum: 2000
default: 100
headers:
WWWAuthenticate:
description: 'RFC 6750 Bearer challenge, for example `Bearer error="insufficient_scope", scope="read"`.'
schema:
type: string
ETag:
description: Entity tag for `If-None-Match` revalidation.
schema:
type: string
CacheControlNoStore:
description: Always `no-store`, because the response carries a secret.
schema:
type: string
enum:
- no-store

View file

@ -0,0 +1,4 @@
description: Always `no-store`, because the response carries a secret.
schema:
type: string
enum: [no-store]

View file

@ -0,0 +1,3 @@
description: 'RFC 6750 Bearer challenge, for example `Bearer error="insufficient_scope", scope="read"`.'
schema:
type: string

View file

@ -0,0 +1,5 @@
description: "The request conflicts with the server's state, for example `setup_complete` or `password_managed_externally`."
content:
application/problem+json:
schema:
$ref: ../schemas/Problem.yaml

View file

@ -1,4 +1,7 @@
description: The caller is authenticated but not allowed to do this.
headers:
WWW-Authenticate:
$ref: ../headers/WWWAuthenticate.yaml
content:
application/problem+json:
schema:

View file

@ -0,0 +1,5 @@
description: "The request body is too large (`payload_too_large`)."
content:
application/problem+json:
schema:
$ref: ../schemas/Problem.yaml

View file

@ -0,0 +1,10 @@
description: "Rate limited (`rate_limited`). Retry after the `Retry-After` seconds."
headers:
Retry-After:
description: Seconds to wait before retrying.
schema:
type: integer
content:
application/problem+json:
schema:
$ref: ../schemas/Problem.yaml

View file

@ -1,4 +1,7 @@
description: Missing, invalid, or expired credentials.
headers:
WWW-Authenticate:
$ref: ../headers/WWWAuthenticate.yaml
content:
application/problem+json:
schema:

View file

@ -0,0 +1,19 @@
type: object
description: The user a grant belongs to.
required: [id, userName, name, isAdmin, passwordChangeable]
properties:
id:
type: string
description: User id.
userName:
type: string
description: Login name.
name:
type: string
description: Display name.
isAdmin:
type: boolean
description: Whether the user is an administrator.
passwordChangeable:
type: boolean
description: "Whether `POST /auth/password` can change this user's password. Clients hide \"change password\" when false."

View file

@ -0,0 +1,12 @@
type: object
description: |
Capability modules this server implements, keyed by module. Keys are optional; a missing key means the
module is not implemented. New modules are added as new optional keys. These are server facts, not what
the calling grant may use.
properties:
core:
$ref: ./CoreCapability.yaml
password:
$ref: ./PasswordCapability.yaml
grants:
$ref: ./GrantsCapability.yaml

View file

@ -0,0 +1,5 @@
type: object
description: The mandatory core module.
required: [version]
properties:
version: {type: integer, description: Module version. Bumped only on semantic change.}

View file

@ -0,0 +1,34 @@
type: object
description: "Username, password and client description for a login or first-admin setup."
required: [username, password, client]
properties:
username:
type: string
minLength: 1
maxLength: 255
description: Login name.
password:
type: string
minLength: 1
maxLength: 1024
description: Password.
client:
type: string
minLength: 1
maxLength: 64
description: Name of the client app.
clientVersion:
type: string
maxLength: 32
description: Version of the client app.
name:
type: string
minLength: 1
maxLength: 64
description: "Label for this grant. Defaults to `client`."
scopes:
type: array
maxItems: 32
description: "Scopes the grant may hold. Omit for `all`."
items:
$ref: ./ScopeRequest.yaml

View file

@ -0,0 +1,41 @@
type: object
description: A long-lived grant held by one client of one user.
required: [id, name, client, clientVersion, scopes, provider, createdAt, lastUsedAt, lastUsedIp, current]
properties:
id:
type: string
description: Grant id.
name:
type: string
description: Label shown to the user.
client:
type: string
description: Name of the client app that holds the grant.
clientVersion:
type: string
nullable: true
description: "Version of the client app, when it sent one."
scopes:
type: array
description: Scopes this grant carries.
items:
$ref: ./Scope.yaml
provider:
type: string
description: "How the grant was created, for example `password` or `setup`. Free-form; new values may appear."
createdAt:
type: string
format: date-time
description: When the grant was created.
lastUsedAt:
type: string
format: date-time
nullable: true
description: "When the grant was last used, at a coarse granularity. Null until first use."
lastUsedIp:
type: string
nullable: true
description: Client IP of the last use. Null until first use.
current:
type: boolean
description: True for the grant that made this request.

View file

@ -0,0 +1,16 @@
type: object
description: "Returned by every login method. The secret is shown only here; store it and never parse it."
required: [secret, grant, user]
properties:
secret:
type: string
maxLength: 512
description: "Opaque grant secret. Send it as `Authorization: Bearer <secret>`."
grant:
description: The new grant.
allOf:
- $ref: ./Grant.yaml
user:
description: The user the grant belongs to.
allOf:
- $ref: ./AuthUser.yaml

View file

@ -0,0 +1,18 @@
type: object
description: "A page of the caller's grants."
required: [items, total, offset, limit]
properties:
items:
type: array
description: "Grants on this page, by last use, most recent first; never-used grants last."
items:
$ref: ./Grant.yaml
total:
type: integer
description: Total number of grants.
offset:
type: integer
description: Zero-based index of the first returned item.
limit:
type: integer
description: Maximum number of items in this page.

View file

@ -0,0 +1,5 @@
type: object
description: The grants module (listing and revoking the user's own grants). Logout stays in core and needs no scope.
required: [version]
properties:
version: {type: integer, description: Module version. Bumped only on semantic change.}

View file

@ -0,0 +1,8 @@
type: object
description: |
Login methods this server accepts, keyed by method. A missing key means the method is not offered.
Keys are optional on purpose: discovery is read by clients of any version against servers of any
version, so new methods are added as new optional keys. Clients ignore keys they do not know.
properties:
password:
$ref: ./PasswordLoginMethod.yaml

View file

@ -0,0 +1,8 @@
type: object
description: Result of a logout.
required: [logoutUrl]
properties:
logoutUrl:
type: string
nullable: true
description: "Where to send the browser to finish logging out of an external provider. Null when there is nothing more to do."

View file

@ -0,0 +1,5 @@
type: object
description: The password login module (login, first-admin setup, password change).
required: [version]
properties:
version: {type: integer, description: Module version. Bumped only on semantic change.}

View file

@ -0,0 +1,18 @@
type: object
description: "Change the caller's own password."
required: [currentPassword, newPassword]
properties:
currentPassword:
type: string
minLength: 1
maxLength: 1024
description: The current password.
newPassword:
type: string
minLength: 1
maxLength: 1024
description: The new password.
revokeOtherGrants:
type: boolean
default: true
description: "Revoke every other grant of the user. The calling grant always survives. Default true."

View file

@ -0,0 +1,2 @@
type: object
description: Username and password login (`POST /auth/login`). No settings yet.

View file

@ -16,7 +16,7 @@ properties:
description: HTTP status code of this response.
detail:
type: string
description: Human-readable explanation specific to this occurrence. Omitted for internal errors.
description: Human-readable explanation specific to this occurrence. Omitted unless the server marked the text as safe to show clients.
code:
type: string
description: Machine-readable error code, and the value clients switch on. New codes may be added.
@ -24,10 +24,18 @@ properties:
- validation
- unauthorized
- forbidden
- insufficient_scope
- not_found
- method_not_allowed
- setup_complete
- password_managed_externally
- payload_too_large
- rate_limited
- unavailable
- internal
referenceId:
type: string
description: Present on internal errors. Quote it when reporting a problem; it tags the server's log lines for this request.
errors:
type: array
description: Per-field failures. Present only when `code` is `validation`.

View file

@ -0,0 +1,5 @@
type: string
description: |
A permission scope. Scopes mirror capability modules; `x:write` includes `x`. `all` appears only on
grants and means every scope the user is entitled to, now and in future releases. New scopes may be added.
enum: [all, read, password, grants]

View file

@ -0,0 +1,4 @@
type: string
description: "A requested scope. Scopes the server does not know are dropped, not rejected, so newer clients keep working."
pattern: '^[a-z][a-z-]*(:write)?$'
maxLength: 64

View file

@ -15,8 +15,4 @@ properties:
type: boolean
description: True until the first admin user has been created.
loginMethods:
type: array
description: Login methods this server accepts. New methods may be added; clients ignore values they do not recognise.
items:
type: string
enum: [password]
$ref: ./LoginMethods.yaml

View file

@ -4,7 +4,7 @@ info:
version: 1.0.0
description: |
Navidrome API v1. Spec-first, additive within v1. Clients discover implemented
capability modules through `GET /server` and never sniff versions.
capability modules through `GET /capabilities` and never sniff versions.
Enums are open: new values may be added to any enum within v1. Clients must
accept values they do not recognise instead of failing.
@ -15,6 +15,10 @@ info:
`HEAD` is accepted wherever `GET` is. A `405` response lists the allowed methods
in its `Allow` header.
Operations that need a grant declare `security: [{bearerAuth: []}]` and the scope they need in
`x-scope` (OpenAPI 3.0 does not allow scopes on bearer schemes). Clients send the grant secret as
`Authorization: Bearer <secret>`. A revoked grant stops working within one minute at most.
license:
name: GPL-3.0
url: https://www.gnu.org/licenses/gpl-3.0.html
@ -23,17 +27,32 @@ servers:
tags:
- name: server
description: Server discovery and the published OpenAPI document.
- name: auth
description: Grants and login methods.
paths:
/server:
$ref: ./paths/server.yaml
/capabilities:
$ref: ./paths/capabilities.yaml
/openapi.json:
$ref: ./paths/openapi.yaml#/json
/openapi.yaml:
$ref: ./paths/openapi.yaml#/yaml
/auth/grants:
$ref: ./paths/auth.yaml#/grants
/auth/grants/{id}:
$ref: ./paths/auth.yaml#/grant
/auth/logout:
$ref: ./paths/auth.yaml#/logout
/auth/login:
$ref: ./paths/auth.yaml#/login
/auth/setup:
$ref: ./paths/auth.yaml#/setup
/auth/password:
$ref: ./paths/auth.yaml#/password
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
description: Short-lived access token minted from a device grant. Not yet applied to any operation.
description: "Grant secret from a login method (`POST /auth/login`, `POST /auth/setup`). Opaque. The required scope is in each operation's `x-scope`."

187
api/openapi/paths/auth.yaml Normal file
View file

@ -0,0 +1,187 @@
grants:
get:
operationId: listGrants
x-module: grants
x-scope: grants
x-stability-level: alpha
tags: [auth]
summary: List my grants
description: "The caller's grants, most recently used first. Grants idle long enough to have expired are not listed."
security: [{bearerAuth: []}]
parameters:
- $ref: ../components/parameters/offset.yaml
- $ref: ../components/parameters/limit.yaml
responses:
'200':
description: A page of grants.
content:
application/json:
schema:
$ref: ../components/schemas/GrantList.yaml
'400':
$ref: ../components/responses/BadRequest.yaml
'401':
$ref: ../components/responses/Unauthorized.yaml
'403':
$ref: ../components/responses/Forbidden.yaml
'500':
$ref: ../components/responses/InternalError.yaml
grant:
delete:
operationId: revokeGrant
x-module: grants
x-scope: grants
x-stability-level: alpha
tags: [auth]
summary: Revoke one of my grants
description: "Revokes the grant; requests with its secret fail from then on. Another user's grant id answers 404."
security: [{bearerAuth: []}]
parameters:
- name: id
in: path
required: true
description: Grant id.
schema:
type: string
maxLength: 64
responses:
'204':
description: Revoked.
'400':
$ref: ../components/responses/BadRequest.yaml
'401':
$ref: ../components/responses/Unauthorized.yaml
'403':
$ref: ../components/responses/Forbidden.yaml
'404':
$ref: ../components/responses/NotFound.yaml
'500':
$ref: ../components/responses/InternalError.yaml
logout:
post:
operationId: logout
x-module: core
x-stability-level: alpha
tags: [auth]
summary: Log out
description: Revokes the grant that made this request. Needs no scope, so any grant can end itself.
security: [{bearerAuth: []}]
responses:
'200':
description: Logged out.
content:
application/json:
schema:
$ref: ../components/schemas/LogoutResponse.yaml
'401':
$ref: ../components/responses/Unauthorized.yaml
'403':
$ref: ../components/responses/Forbidden.yaml
'500':
$ref: ../components/responses/InternalError.yaml
login:
post:
operationId: login
x-module: password
x-stability-level: alpha
tags: [auth]
summary: Log in with a password
description: Checks the username and password and returns a new grant. Unknown user and wrong password fail the same way.
security: []
requestBody:
description: The credentials and a description of the client.
required: true
content:
application/json:
schema:
$ref: ../components/schemas/CredentialsRequest.yaml
responses:
'200':
description: The new grant.
headers:
Cache-Control:
$ref: ../components/headers/CacheControlNoStore.yaml
content:
application/json:
schema:
$ref: ../components/schemas/GrantCreated.yaml
'400':
$ref: ../components/responses/BadRequest.yaml
'401':
$ref: ../components/responses/Unauthorized.yaml
'413':
$ref: ../components/responses/PayloadTooLarge.yaml
'429':
$ref: ../components/responses/TooManyRequests.yaml
'500':
$ref: ../components/responses/InternalError.yaml
setup:
post:
operationId: setupFirstAdmin
x-module: password
x-stability-level: alpha
tags: [auth]
summary: Create the first admin
description: "Creates the first administrator while `setupRequired` is true and returns a grant for it. Answers 409 `setup_complete` once any user exists. A server with no setup step always answers 409."
security: []
requestBody:
description: The credentials and a description of the client.
required: true
content:
application/json:
schema:
$ref: ../components/schemas/CredentialsRequest.yaml
responses:
'201':
description: The admin was created.
headers:
Cache-Control:
$ref: ../components/headers/CacheControlNoStore.yaml
content:
application/json:
schema:
$ref: ../components/schemas/GrantCreated.yaml
'400':
$ref: ../components/responses/BadRequest.yaml
'409':
$ref: ../components/responses/Conflict.yaml
'413':
$ref: ../components/responses/PayloadTooLarge.yaml
'429':
$ref: ../components/responses/TooManyRequests.yaml
'500':
$ref: ../components/responses/InternalError.yaml
password:
post:
operationId: changePassword
x-module: password
x-scope: password
x-stability-level: alpha
tags: [auth]
summary: Change my password
description: "Changes the caller's password. By default every other grant of the user is revoked; the calling grant survives. On Navidrome the change also ends the user's sessions on its other APIs, regardless of `revokeOtherGrants`, which only covers API v1 grants. Answers 409 `password_managed_externally` when the password is not stored by this server."
security: [{bearerAuth: []}]
requestBody:
description: The current and the new password.
required: true
content:
application/json:
schema:
$ref: ../components/schemas/PasswordChangeRequest.yaml
responses:
'204':
description: Password changed.
'400':
$ref: ../components/responses/BadRequest.yaml
'401':
$ref: ../components/responses/Unauthorized.yaml
'403':
$ref: ../components/responses/Forbidden.yaml
'409':
$ref: ../components/responses/Conflict.yaml
'413':
$ref: ../components/responses/PayloadTooLarge.yaml
'429':
$ref: ../components/responses/TooManyRequests.yaml
'500':
$ref: ../components/responses/InternalError.yaml

View file

@ -0,0 +1,16 @@
get:
operationId: getCapabilities
x-module: core
x-stability-level: alpha
tags: [server]
summary: List implemented capability modules
description: The capability modules this server implements. Any valid grant may read it, whatever its scopes.
security: [{bearerAuth: []}]
responses:
'200':
description: Implemented modules.
content:
application/json:
schema: {$ref: ../components/schemas/Capabilities.yaml}
'401': {$ref: ../components/responses/Unauthorized.yaml}
'500': {$ref: ../components/responses/InternalError.yaml}

View file

@ -4,6 +4,7 @@ json:
x-module: core
x-stability-level: alpha
tags: [server]
security: []
summary: Get the OpenAPI document (JSON)
description: The bundled OpenAPI document of the running server version. Supports ETag revalidation.
responses:
@ -25,6 +26,7 @@ yaml:
x-module: core
x-stability-level: alpha
tags: [server]
security: []
summary: Get the OpenAPI document (YAML)
description: The bundled OpenAPI document of the running server version. Supports ETag revalidation.
responses:

View file

@ -3,11 +3,11 @@ get:
x-module: core
x-stability-level: alpha
tags: [server]
security: []
summary: Describe the server
description: |
Returns the public server description. No authentication required.
Authenticated requests will additionally receive the implemented capability modules
once authentication is available.
Capability modules are listed by `GET /capabilities`.
responses:
'200':
description: Server description.

View file

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

View file

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

@ -34,6 +34,7 @@ const (
JWTPublicSecretKey = "JWTPublicSecret"
JWTIssuer = "ND"
DefaultSessionTimeout = 48 * time.Hour
APIv1GrantIdleExpiry = 90 * 24 * time.Hour
DefaultSmartRefresh = 5 * time.Second
DefaultShareExpiration = 8760 * time.Hour
CookieExpiry = 365 * 24 * 3600 // One year
@ -83,6 +84,8 @@ const (
DefaultInfoLanguage = "en"
DefaultMinScrobbleDuration = 30 * time.Second
ArtistInfoTimeToLive = 24 * time.Hour
AlbumInfoTimeToLive = 7 * 24 * time.Hour
UpdateLastAccessFrequency = time.Minute
@ -90,6 +93,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 +213,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,6 +3,7 @@ package agents
import (
"context"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
)
@ -13,6 +14,7 @@ type SessionKeys struct {
}
func (sk *SessionKeys) Put(ctx context.Context, userId, sessionKey string) error {
ctx = log.WithSecrets(ctx, sessionKey)
return sk.DataStore.UserProps().Put(ctx, userId, sk.KeyName, sessionKey)
}

View file

@ -1,37 +1,86 @@
package agents
import (
"bytes"
"context"
"os"
"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/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")
Expect(err).To(MatchError(model.ErrNotFound))
})
It("never logs the session key, but still logs the user id and key name", func() {
logged := model.User{ID: "logged-user-id", UserName: "logged-user-id"}
Expect(ds.User().Put(ctx, &logged)).To(Succeed())
dbKeys := SessionKeys{DataStore: ds, KeyName: "LastFMSessionKey"}
logs := &bytes.Buffer{}
log.SetOutput(logs)
log.SetLevel(log.LevelTrace)
DeferCleanup(func() {
log.SetOutput(os.Stderr)
log.SetLevel(log.LevelFatal)
})
Expect(dbKeys.Put(ctx, logged.ID, "inserted-session-key")).To(Succeed())
Expect(dbKeys.Put(ctx, logged.ID, "updated-session-key")).To(Succeed())
Expect(dbKeys.Get(ctx, logged.ID)).To(Equal("updated-session-key"))
Expect(logs.String()).To(ContainSubstring("INSERT INTO user_props"))
Expect(logs.String()).To(ContainSubstring("UPDATE user_props"))
Expect(logs.String()).To(ContainSubstring("logged-user-id"))
Expect(logs.String()).To(ContainSubstring("LastFMSessionKey"))
Expect(logs.String()).ToNot(ContainSubstring("inserted-session-key"))
Expect(logs.String()).ToNot(ContainSubstring("updated-session-key"))
})
})

View file

@ -0,0 +1,23 @@
package apiauth
import (
"testing"
"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"
)
func TestAPIAuth(t *testing.T) {
tests.Init(t, false)
log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail)
RunSpecs(t, "API Auth Suite")
}
var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

14
core/apiauth/context.go Normal file
View file

@ -0,0 +1,14 @@
package apiauth
import "context"
type principalKey struct{}
func WithPrincipal(ctx context.Context, p *Principal) context.Context {
return context.WithValue(ctx, principalKey{}, p)
}
func PrincipalFrom(ctx context.Context) (*Principal, bool) {
p, ok := ctx.Value(principalKey{}).(*Principal)
return p, ok
}

View file

@ -0,0 +1,71 @@
package apiauth
import (
"context"
"crypto/subtle"
"errors"
"fmt"
"github.com/navidrome/navidrome/model"
)
type Outcome int
const (
NotMine Outcome = iota
Authenticated
Rejected
Unavailable
)
type CredentialResult struct {
Outcome Outcome
User *model.User
Provider string
PasswordLocal bool
}
type CredentialChecker interface {
Check(ctx context.Context, username, password string) (CredentialResult, error)
}
// checkCredentials asks each checker in turn; only NotMine moves on, so an owning provider's "no" is final.
func checkCredentials(ctx context.Context, checkers []CredentialChecker, username, password string) (CredentialResult, error) {
for _, c := range checkers {
res, err := c.Check(ctx, username, password)
if err != nil {
return CredentialResult{}, err
}
switch res.Outcome {
case NotMine:
continue
case Authenticated:
return res, nil
case Unavailable:
return CredentialResult{}, model.ErrNotAvailable
case Rejected:
return CredentialResult{}, model.ErrInvalidAuth
default:
return CredentialResult{}, fmt.Errorf("unknown credential outcome %d", res.Outcome)
}
}
return CredentialResult{}, model.ErrInvalidAuth
}
type dbChecker struct {
ds model.DataStore
}
func (c dbChecker) Check(ctx context.Context, username, password string) (CredentialResult, error) {
u, err := c.ds.User().FindByUsernameWithPassword(ctx, username)
if errors.Is(err, model.ErrNotFound) {
return CredentialResult{Outcome: NotMine}, nil
}
if err != nil {
return CredentialResult{}, err
}
if subtle.ConstantTimeCompare([]byte(u.Password), []byte(password)) != 1 {
return CredentialResult{Outcome: Rejected}, nil
}
return CredentialResult{Outcome: Authenticated, User: u, Provider: "password", PasswordLocal: true}, nil
}

View file

@ -0,0 +1,63 @@
package apiauth
import (
"context"
"errors"
"github.com/navidrome/navidrome/model"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
type fakeChecker struct {
res CredentialResult
err error
hit bool
}
func (f *fakeChecker) Check(context.Context, string, string) (CredentialResult, error) {
f.hit = true
return f.res, f.err
}
var _ = Describe("credential chain", func() {
var ctx context.Context
BeforeEach(func() {
ctx = GinkgoT().Context()
})
It("authenticates against the database with the stored password", func() {
u := createUser(ctx, "pw", false)
res, err := checkCredentials(ctx, []CredentialChecker{dbChecker{ds: realDS}}, u.UserName, "pw")
Expect(err).ToNot(HaveOccurred())
Expect(res.Outcome).To(Equal(Authenticated))
Expect(res.User.ID).To(Equal(u.ID))
Expect(res.Provider).To(Equal("password"))
Expect(res.PasswordLocal).To(BeTrue())
})
It("rejects a wrong password and an unknown user the same way", func() {
u := createUser(ctx, "pw", false)
_, err := checkCredentials(ctx, []CredentialChecker{dbChecker{ds: realDS}}, u.UserName, "nope")
Expect(err).To(MatchError(model.ErrInvalidAuth))
_, err = checkCredentials(ctx, []CredentialChecker{dbChecker{ds: realDS}}, "ghost", "pw")
Expect(err).To(MatchError(model.ErrInvalidAuth))
})
It("moves on only from NotMine, and an owner's rejection stops the chain", func() {
owner := &fakeChecker{res: CredentialResult{Outcome: Rejected}}
later := &fakeChecker{res: CredentialResult{Outcome: Authenticated, User: &model.User{ID: "x"}}}
_, err := checkCredentials(ctx, []CredentialChecker{&fakeChecker{res: CredentialResult{Outcome: NotMine}}, owner, later}, "a", "b")
Expect(err).To(MatchError(model.ErrInvalidAuth))
Expect(later.hit).To(BeFalse())
})
It("maps Unavailable to ErrNotAvailable and passes through checker errors", func() {
_, err := checkCredentials(ctx, []CredentialChecker{&fakeChecker{res: CredentialResult{Outcome: Unavailable}}}, "a", "b")
Expect(err).To(MatchError(model.ErrNotAvailable))
boom := errors.New("boom")
_, err = checkCredentials(ctx, []CredentialChecker{&fakeChecker{err: boom}}, "a", "b")
Expect(err).To(MatchError(boom))
})
})

36
core/apiauth/db_test.go Normal file
View file

@ -0,0 +1,36 @@
package apiauth
import (
"context"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/id"
"github.com/navidrome/navidrome/persistence"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var realDS model.DataStore
var _ = BeforeSuite(func() {
realDS = persistence.New(db.Db())
})
func createUser(ctx context.Context, password string, admin bool) model.User {
name := "user-" + id.NewRandom()
u := model.User{UserName: name, Name: name, NewPassword: password, IsAdmin: admin}
ExpectWithOffset(1, realDS.User().Put(ctx, &u)).To(Succeed())
stored, err := realDS.User().FindByUsername(ctx, name)
ExpectWithOffset(1, err).ToNot(HaveOccurred())
return *stored
}
// login signs u in (nil scopes asks for all) and authenticates with the new grant secret.
func login(ctx context.Context, svc *Service, u model.User, password string, scopes []string) (*Issued, *Principal) {
issued, err := svc.Login(ctx, u.UserName, password, meta, scopes)
ExpectWithOffset(1, err).ToNot(HaveOccurred())
p, err := svc.Authenticate(ctx, issued.Secret, "")
ExpectWithOffset(1, err).ToNot(HaveOccurred())
return issued, p
}

View file

@ -0,0 +1,11 @@
package apiauth
import (
"time"
"github.com/navidrome/navidrome/model"
)
func (s *Service) SetClock(now func() time.Time) { s.now = now }
func (s *Service) SetCheckers(f func(model.DataStore) []CredentialChecker) { s.checkers = f }

64
core/apiauth/scopes.go Normal file
View file

@ -0,0 +1,64 @@
package apiauth
import (
"slices"
"strings"
)
const (
ScopeAll = "all"
ScopeRead = "read"
ScopePassword = "password"
ScopeGrants = "grants"
ScopeAdmin = "admin"
)
// KnownScopes lists the scopes of modules this server implements; `all` expands to these.
var KnownScopes = []string{ScopeRead, ScopePassword, ScopeGrants}
func known(s string) bool {
return slices.Contains(KnownScopes, s)
}
func grantable(s string, isAdmin bool) bool {
return known(s) && (s != ScopeAdmin || isAdmin)
}
func normalize(in []string) []string {
out := slices.Clone(in)
slices.Sort(out)
return slices.Compact(out)
}
// Entitled returns the scopes a new grant stores.
func Entitled(requested []string, isAdmin bool) []string {
if requested == nil {
return []string{ScopeAll}
}
var out []string
for _, s := range requested {
if s == ScopeAll || grantable(s, isAdmin) {
out = append(out, s)
}
}
return normalize(out)
}
// Expand turns a grant's stored scopes into the concrete scopes it carries right now.
func Expand(granted []string, isAdmin bool) []string {
var out []string
for _, s := range granted {
if s == ScopeAll {
out = append(out, KnownScopes...)
continue
}
out = append(out, s)
}
out = slices.DeleteFunc(out, func(s string) bool { return !grantable(s, isAdmin) })
return normalize(out)
}
func Satisfies(scopes []string, required string) bool {
return slices.Contains(scopes, required) ||
(!strings.HasSuffix(required, ":write") && slices.Contains(scopes, required+":write"))
}

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