Compare commits

...

131 commits

Author SHA1 Message Date
Deluan Quintão
7fa50022c6
ci: fix deprecation warnings in GitHub Actions workflows (#6561) 2026-11-26 23:15:43 -05:00
Deluan Quintão
3fc792d4a5
feat(plugins): add host-owned streams for plugins (#6546) 2026-11-26 22:55:28 -05:00
Deluan Quintão
4874adf7a4
fix(artwork): keep covers current when files change mid-resolve (#6557) 2026-11-26 22:35:07 -05:00
Deluan Quintão
969d1c3f4a
build: skip JS checks in pre-push hook when ui/ is unchanged (#6560) 2026-11-26 22:14:46 -05:00
Deluan Quintão
60b19a37f8
chore(deps): update Go dependencies, keep unix socket proxies working (#6558) 2026-11-26 21:01:47 -05:00
ump45nose
934fa2d03f
fix(smartplaylists): honor AlbumPlayCountMode when filtering albumPlayCount (#6554) 2026-11-26 19:58:57 -05:00
Deluan Quintão
019cbfc46d
fix(ui): show the recently added date the song list sorts by (#6555) 2026-11-26 13:29:23 -05:00
Deluan Quintão
5e2ea49823
feat(scanner): add RecentlyAddedBy option, default to scan time (#6545) 2026-11-26 10:32:27 -05:00
Deluan Quintão
09dc488c55
fix(plugins): free host response memory in generated Go and Rust clients (#6547) 2026-11-26 09:05:46 -05:00
Nikita Sobakin
c9567f95e2
perf(scanner): track external lyrics files per folder (#6535) 2026-11-24 21:45:33 -05:00
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
Deluan Quintão
4ee78867c9
refactor(conf): make the global config copy-on-write to stop config data races in tests (#6455) 2026-11-13 11:42:14 -05:00
Deluan Quintão
94a6e59fee
fix(stream): match the estimated Content-Length on uncached transcodes, and return 200 on HEAD (#6449) 2026-11-12 16:53:15 -05:00
Deluan Quintão
a7f19c7c7a
fix(transcoding): declare the duration of a piped mp3 transcode (#6218) 2026-11-11 19:03:55 -05:00
Kendall Garner
ff58ca5d1f
fix(play tracker): record local play count even if external scrobbling is disabled on the player (#6387) 2026-11-11 14:15:15 -05:00
Deluan
2fecb718c0 ci: raise golangci-lint timeout to 3m
Package loading alone hit the 2m limit on a slow runner.
2026-11-11 08:16:03 -05:00
Junker der Provinz
514207faf1
fix(server): classify library path validation errors instead of a catch-all (#4595) (#5919) 2026-11-10 21:56:14 -05:00
Deluan Quintão
d22a31aee0
fix(subsonic): honour explicit download format over player transcoding (#6446) 2026-11-10 19:53:12 -05:00
Adrián Sánchez Zapico
1efd5c467b
fix(jellyfin): list the user's libraries at the /Items user root (#6214)
* fix(jellyfin): list the user's libraries at the /Items user root

An unfiltered, non-recursive /Items query with no ParentId is answered by
Jellyfin with the user's libraries (the user root folder's children), not
their contents. Navidrome defaulted to albums there, so Symfonium found no
music library and synced nothing.

Fixes #6199

Signed-off-by: zapisanchez <zapisanchez@gmail.com>

* fix(jellyfin): page the user-root /Items libraries by StartIndex and Limit

* fix(jellyfin): sort the user-root /Items libraries by SortBy and SortOrder before paging

* refactor(jellyfin): simplify user-root sorting and filter detection

Share the first-SortOrder rule between applySort and sortViews through a new
isDescending helper, and make sortViews compare string keys instead of building
comparator closures. hasFilters now compares itemFilters to its zero value, so
a filter added there later also counts at the user root. Read the Recursive
param once, fix the paginate comment that said it only served the multi-type
path, and cut comments that restated the code. The user-root specs share one
library fixture and one request helper.

---------

Signed-off-by: zapisanchez <zapisanchez@gmail.com>
Co-authored-by: Deluan <deluan@navidrome.org>
2026-11-10 17:44:00 -05:00
Santhi Prakash
64cf86fae9
fix(jellyfin): clamp negative StartIndex to zero - #6341 (#6366) 2026-11-10 16:12:19 -05:00
ump45nose
27d041486c
fix(jellyfin): honour every value of repeated list params (#6414)
* fix(jellyfin): honour every value of repeated list params - #6389

Jellyfin's model binder accepts an array query param both as one
comma-separated value and as repeated keys, and @jellyfin/sdk clients
(Jellify) send the latter. parseItemsQuery read IncludeItemTypes with
StringOr, so IncludeItemTypes=MusicArtist&IncludeItemTypes=Audio&...
behaved as an artist-only query and a mixed search silently lost songs,
albums and playlists. Filters had the same single-value read.

knownItemKinds now takes all values of the param, and parseItemFilters
walks them too, keeping the comma splitting each already did. Absent or
all-unknown lists still mean "no type filter", so the inferred-type and
album-default paths are unchanged.

Signed-off-by: yuwk <1729065730@qq.com>

* fix(jellyfin): join repeated query params so every value is parsed

Jellyfin binds a list param as one comma-separated value or as repeated
keys. joinedStrings feeds every value into the parsers that already
split on commas, so IncludeItemTypes, Filters, SortBy, SortOrder, the
artist id lists and Container all accept both spellings.

ArtistIds, AlbumArtistIds and contributingArtistIds now match every
artist in the list instead of only the first. SortOrder is paired with
each SortBy key, and a key past the end of the list reuses the first
direction, which is what Jellyfin's GetOrderBy does. Playlist SearchTerm
is left for a follow-up.

Signed-off-by: Vincent <52391318+ump45nose@users.noreply.github.com>
Co-authored-by: ump45nose <ump45nose@users.noreply.github.com>

* fix(jellyfin): apply multi-id artist filters as a single slice

ORing one contributing-artist filter per id let an album whose album
artist is one of the ids still match as Featured On via another id in
the list. ParticipantIDFilter and NotParticipantIDFilter already accept
a slice, so contributingArtistIds now uses one IN/NOT IN pair over the
whole list. Album and song artist filters do the same, which also avoids
one subquery per id.

Signed-off-by: Vincent <52391318+ump45nose@users.noreply.github.com>
Co-authored-by: ump45nose <ump45nose@users.noreply.github.com>

* refactor(jellyfin): trim comments in repeated list params change

Signed-off-by: Deluan <deluan@navidrome.org>

---------

Signed-off-by: yuwk <1729065730@qq.com>
Signed-off-by: Vincent <52391318+ump45nose@users.noreply.github.com>
Signed-off-by: Deluan <deluan@navidrome.org>
Co-authored-by: ump45nose <ump45nose@users.noreply.github.com>
Co-authored-by: Deluan <deluan@navidrome.org>
2026-11-10 12:41:46 -05:00
Deluan Quintão
9f0441352c
fix(transcoding): keep the DSD cap unless the client declares an upper rate limit (#6445)
* fix(transcoding): keep the DSD cap unless the client declares an upper rate limit

Any audioSamplerate limitation on the target codec turned off the 88.2kHz
DSD cap, including GreaterThanEqual, NotEquals, empty or non-numeric limits.
None of those lower the rate, so DSD64 still went out at 352.8kHz. Only
LessThanEqual with a number, or Equals with at least one number, now replaces
the cap.

Follow-up to #6367, addressing
https://github.com/navidrome/navidrome/pull/6367#discussion_r4526602338

* refactor(stream): share upper-bound parsing between the DSD cap check and limits

applyIntLimitation and the DSD cap check now read LessThanEqual and Equals values through one upperBounds helper, so the two can't disagree on which limits lower a rate.
2026-11-10 10:59:28 -05:00
Junker der Provinz
ecbd4b7d55
fix(transcoding): default DSD transcoded to lossless PCM to 88.2kHz
* fix(stream): cap DSD transcoded to lossless PCM at 88.2kHz

DSD64 was sent as 352.8kHz FLAC/WAV, which many clients cannot play.
Client and codec profile limits below 88.2kHz still apply.

ffprobe already reports DSD at rate/8 with 8 bits per sample, so only
rates read from tags are divided, and any DSD depth maps to 24-bit PCM.
Probed files used to come out at 44.1kHz with a bit depth of 8.

Fixes #6288

Co-authored-by: Olli Sulopuisto <1051255+ollisulopuisto@users.noreply.github.com>
Signed-off-by: Junker der Provinz <133605895+junkerderprovinz@users.noreply.github.com>

* fix(stream): let a client's sample rate limit replace the DSD cap

The 88.2kHz cap on DSD transcoded to lossless PCM is meant for clients that
say nothing about sample rates, like the legacy stream endpoint. Applied
unconditionally, it also overrode clients that declared their own
audioSamplerate limit: a client accepting up to 192kHz got 88.2kHz, and one
accepting only 96kHz or 192kHz got no compatible profile at all.

The cap now applies only when the client has no audioSamplerate limitation
for the target codec. Otherwise the client's limit decides the rate.

* refactor(stream): share the audio codec profile matcher

Direct play checks, transcode limitations and the new DSD cap check each
looped over the client's codec profiles with the same audio-type and codec
alias filter. They now use one audioCodecProfiles iterator, so the DSD cap
decision cannot drift from the limitations that are actually applied.
targetSampleRate takes a single capDSD flag instead of two adjacent bools.

* test(stream): table-drive the DSD to FLAC sample rate specs

Six specs repeated the same DSD source and FLAC transcoding profile and
differed only in the source rate, the client's codec profiles and the
expected rate. A DescribeTable lists the cap policy case by case, and
every entry now also checks the 24-bit depth.

---------

Signed-off-by: Junker der Provinz <133605895+junkerderprovinz@users.noreply.github.com>
Co-authored-by: Olli Sulopuisto <1051255+ollisulopuisto@users.noreply.github.com>
Co-authored-by: Deluan Quintão <deluan@navidrome.org>
2026-11-10 10:14:37 -05:00
Alen Požun
818603436c
fix(smartplaylists): preserve empty nested groups in smart playlist criteria marshaling (#6438)
* fix: preserve empty nested groups in smart playlist criteria marshaling

Fixes #6316

Empty nested groups were serialized incorrectly because of omitempty.
Now only the active conjunction key is emitted, so empty groups become [].

* docs: add changelog entry for #6316

* fix: recover playlists previously saved with empty nested groups

Treats the old broken {} form as an empty All on unmarshal so existing
playlists load again.

* docs: mention recovery of previously broken playlists in changelog

* style: run gofmt

* fix: safer recovery of empty groups and nil slices

- only treat {} as empty All when the group has no other rules
- marshal nil slices as [] instead of null
- drop CHANGELOG.md (release notes are generated from commits)

* test: remove hand-built criteria test

* test: add Ginkgo round-trip specs for empty nested groups

* chore: remove CHANGELOG.md

* docs: add docstrings to criteria json helpers

* Revert "docs: add docstrings to criteria json helpers"

This reverts commit 9f74c604a1.

* docs: add docstrings to criteria json helpers

* test: fix criteria round-trip specs to use Criteria and gomega

* fix(criteria): keep only the marshal fix for empty nested groups

Remove the recovery that turned a group made only of {} elements into an
empty All. It lived in the parser shared by POST bodies, .nsp files and
scrobble filters, so it accepted inputs such as {"all":[{}]} that were
rejected before, and turned them into rules that match the whole library.
It also had to guess whether a saved {} was an empty all or an empty any.
Rows already saved broken are a one-time cleanup, not something the parser
should carry.

Also remove the {}/null short-circuit (null was already handled, and {}
only widened what the parser accepts), drop the doc comments that restated
function names, and fold the round-trip specs into one table that checks
the exact marshaled output for empty nested all and any groups.

---------

Co-authored-by: kukirin-ui <kukirin-ui@users.noreply.github.com>
Co-authored-by: Deluan <deluan@navidrome.org>
2026-11-10 09:26:16 -05:00
Deluan Quintão
93cead9b16
fix(search): scope artist search counts to the requested libraries (#6434) 2026-11-09 12:15:16 -05:00
ump45nose
e40d54fd40
fix(search): apply the artist library scope to every search path - #6340 (#6415)
* fix(persistence): apply the artist library scope to every search path - #6340

Signed-off-by: yuwk <1729065730@qq.com>

* test(persistence): expect a scoped artist search to find the artist

The library-scope specs only showed that searching another library
returns nothing. Also search with library_id = [lib2.ID] and expect
the artist that belongs to that library.

Signed-off-by: Vincent <52391318+ump45nose@users.noreply.github.com>
Co-authored-by: ump45nose <ump45nose@users.noreply.github.com>

* refactor(search): streamline artist search configuration and improve library filtering logic

---------

Signed-off-by: yuwk <1729065730@qq.com>
Signed-off-by: Vincent <52391318+ump45nose@users.noreply.github.com>
Co-authored-by: Deluan Quintão <deluan@navidrome.org>
Co-authored-by: ump45nose <ump45nose@users.noreply.github.com>
2026-11-09 11:35:05 -05:00
Deluan Quintão
93e01f390e
fix(ui): remember the player play mode across reloads (#6433)
* fix(ui): remember the player play mode across reloads - #6361

The play mode was kept only in memory, so a page reload always reset it to
"In order". It is now saved to localStorage with the rest of the player
state, and clearing the queue (closing the player) keeps it too.

* test(ui): wait for the throttled save before reloading the store
2026-11-09 08:07:00 -05:00
Coffeeicus
f5b6805b31
fix(ui): update Turkish localisation (#6412)
* fix(ui): update Turkish localisation

* Update tr.json

* Update tr.json

* Update tr.json

---------

Co-authored-by: Deluan Quintão <deluan@navidrome.org>
2026-11-08 18:22:44 -05:00
Deluan
97ae17cab3 docs: ask before working on an issue someone offered to fix
When an issue author or another contributor offers to submit a fix, others
should ask in the issue before starting their own PR. This avoids duplicate
work and gives the person who did the investigation the first chance to
contribute the fix.

Signed-off-by: Deluan <deluan@navidrome.org>
2026-11-08 18:01:18 -05:00
Deluan Quintão
a4f75cf6c4
docs: update contribution policy and PR/Issues templates (#6417)
* docs(contributing): propose updated contribution policy

Draft proposal for maintainer review. Rewrite the contribution guide around prior scope agreement, personal review, AI disclosure and maintainability, while keeping the commit conventions and DCO sign-off. Add AI use and review items to the PR template, keeping its headings.

Simplify the bug form so only what happened, the version and the Code of Conduct are required, and it no longer asks for an upgrade or a duplicate-search attestation. Update the selector text and point README feature requests to Discussions.

Keep the pull-requests anchor because the stale workflow links to it.

Signed-off-by: Deluan <deluan@navidrome.org>

* docs(contributing): allow AI-assisted PR text and review replies

Let contributors use AI tools to draft, edit, or translate PR explanations and review replies, as long as they review the final text, agree with it, and take responsibility for it. The PR template description hint now says the same instead of asking for the contributor's own words.

Signed-off-by: Deluan <deluan@navidrome.org>

* docs(contributing): route closed-issue regressions and no-agreement PRs

The bug form told reporters to add details to a matching report, but the lock workflow locks inactive issues and asks for a new issue instead. It now says to use a matching open report, or open a new one that links a closed issue.

The PR template and guide only offered the small-change exception when prior agreement isn't needed, which doesn't fit translation updates. Both now ask contributors to explain why agreement isn't needed.

Signed-off-by: Deluan <deluan@navidrome.org>

* docs(contributing): ask contributors to be mindful of the maintainer's time

Add the request to the end of the communication paragraph in the guide and to the PR template's description hint.

Signed-off-by: Deluan <deluan@navidrome.org>

* docs(issues): require reproducing bugs on the latest release

Restore a required checkbox in the bug form, placed before the version field: "I'm using the latest Navidrome release and can reproduce the issue on it." Drop the version help sentence that said upgrading isn't required, since it now contradicts the checkbox.

Signed-off-by: Deluan <deluan@navidrome.org>

* docs(issues): turn the bug form search guidance into a checkbox

The long intro paragraph was easy to skip. It now only thanks the reporter and links private security reporting. A required checkbox, grouped with the latest-release one at the top, confirms the reporter searched open and closed issues. The "What happened" help asks reporters to link a matching closed issue.

The steps help now says "If it happens only sometimes" instead of mentioning problems that can't be reproduced, so it no longer conflicts with the required reproduction checkbox.

Signed-off-by: Deluan <deluan@navidrome.org>

* docs(pr-template): ask for AI use with Yes and No checkboxes

Replace the free-text "Yes / No" line with two checkboxes. Contributors tick exactly one, so empty boxes clearly mean the question wasn't answered.

Signed-off-by: Deluan <deluan@navidrome.org>

---------

Signed-off-by: Deluan <deluan@navidrome.org>
2026-11-08 13:20:09 -05:00
Deluan Quintão
6a38dc988b
fix(ui): bump navidrome-music-player to 4.25.5 (#6416)
Picks up the progress slider focus fix from navidrome/react-music-player#11. On 4.25.4, focus changes on the progress handle started and committed a synthetic rc-slider drag, which seeked the audio. 4.25.5 keeps native focus but does not start a drag on focus.
2026-11-07 16:59:42 -05:00
ump45nose
7c1e68a1e4
fix(subsonic): reject setRating values outside the 0-5 range - #6411 (#6413) 2026-11-03 11:26:14 -05:00
Tiago Carrondo
755da3ea59
feat(ui): add Cave theme (#6374)
* feat(themes): add Cave theme

Near-black background with a single orange accent, based on the colors
of https://acave.pt.

Signed-off-by: Tiago Carrondo <tiago@carrondo.pt>

* fix(themes): raise Cave button hover contrast

Dark text on the hover color was 4.27:1; #e84518 brings it to 4.96:1.

Signed-off-by: Tiago Carrondo <tiago@carrondo.pt>

* fix(themes): keep Cave in alphabetical order in the themes list

---------

Signed-off-by: Tiago Carrondo <tiago@carrondo.pt>
Co-authored-by: Deluan Quintão <deluan@navidrome.org>
2026-11-03 10:58:48 -05:00
Pujitha Paladugu
c9c70c952b
fix(scanner): map TagLib's normalized "initialkey" tag to the key tag (#6384)
Motivation: The `key` tag was never populated from MP3 (TKEY), M4A
(iTunes initialkey) or FLAC (INITIALKEY) files. TagLib exposes all three
as the raw tag "initialkey", which was not among the aliases for `key`
in mappings.yaml, so the value showed up in rawTags but not in mappedTags.

Approach: Add the lowercase alias `initialkey` to the `key` entry in
resources/mappings.yaml, plus a unit test.

Validation: Added a test in model/metadata/metadata_test.go that feeds
{"initialkey": ["Ebm"]} to metadata.New and expects `key` == "Ebm". It
fails without the alias and passes with it (go test ./model/metadata/).
`go test ./model/...` passes and gofmt is clean. I did not scan real
audio files end to end; the raw tag name comes from the issue's
`navidrome inspect` output.

Report: https://github.com/navidrome/navidrome/issues/6369

Assisted-by: claude-sonnet-5-5 (via Claude Code)

Signed-off-by: Pujitha Paladugu <10557236+pujitha24@users.noreply.github.com>
Co-authored-by: Pujitha Paladugu <10557236+pujitha24@users.noreply.github.com>
2026-11-02 21:54:46 -05:00
DawidKrynski
563c5c72a1
fix(db): refuse to restore a backup file that is not a Navidrome database - #6295 (#6296) 2026-11-02 19:43:23 -05:00
Xabi
2a57570e90
fix(ui): update Basque localisation (#6133)
* Update Basque localisation

Added strings:
refresh
scrobbleFilter
scrobbleFilter
invalidScrobbleFilter
choices {noDefaultBitRate}
starred
idHelp
metadataRefreshStarted
onlyFavourites

* Update eu.json

some syntax issue

---------

Co-authored-by: Deluan Quintão <deluan@navidrome.org>
2026-11-01 14:35:11 -05:00
Deluan Quintão
ec2e0a9ea9
fix(ui): stop the playlist list from overflowing on mobile (#6376)
On phone-width screens the playlist table needs about 473px (cover, name, duration, favourite and edit columns), so even a short playlist name made the whole page wider than a 390px viewport and pushed the app bar icons off screen. react-admin's layout root uses min-width: fit-content, so the page grows to fit its widest content. On xs screens the list card now has a max-width of 100vw and scrolls horizontally, keeping the page at screen width while the favourite and edit buttons stay reachable by swiping the table. Long playlist names without spaces can also wrap there. Desktop and tablet layouts are unchanged.
2026-10-23 16:25:10 +01:00
Deluan Quintão
56cc32aede
fix(scanner): map movement number and count from ID3 MVIN and MP4 tags (#6357)
TagLib reports ID3 MVIN and MP4 ©mvi as movementnumber, and MP4 ©mvc as
movementcount. Neither name was aliased in mappings.yaml, so getSong
returned movements with the name only. Add both aliases.

ID3 MVIN stores the value as n/N (e.g. 1/4), which parsed as 0. Split it
at scan time, like track and disc numbers, so the stored movement tag holds
the number and movementtotal gets the count when the file has no explicit
total. Storing the clean value also lets smart playlist rules on the
movement tag match. Existing files need a full scan to pick this up.

Fixes #6356
2026-10-21 13:26:26 +01:00
Deluan Quintão
df77c462e8
feat(ui): add a Date Format setting to choose language or browser dates (#6263)
* feat(ui): add a Date Format setting to choose language or browser dates

Since #6160 dates follow the selected UI language, which is wrong for users who run the UI in one language but want their own region's date format. The Personal page now has a Date Format select with "Match language" (default, current behavior) and "Match browser". The choice is kept in localStorage and read by useDateLocale, which returns no locale in browser mode so Intl uses the browser's own.

Six screens imported react-admin's DateField directly and so ignored the language setting (playlist, radio and missing files lists, album table, song and album info). They now use the common DateField wrapper, which also reads the record from the record context.

* feat(ui): add pt-BR translations for the Date Format setting
2026-10-18 01:00:24 -07:00
Deluan Quintão
a45adbbb2e
chore: move README badge and dev image tag to navidrome/navidrome 2026-10-16 14:54:33 -07:00
Deluan Quintão
be201a2d79
ci: also publish Docker images to navidrome/navidrome on Docker Hub (#6327)
Run the Docker Hub manifest job as a matrix over the target repositories,
so the existing DOCKER_HUB_REPO (deluan/navidrome) push is unchanged and
the upstream repository also pushes the same tags to navidrome/navidrome.
Each leg fails independently, so a problem with one repository does not
block the other.

Signed-off-by: Deluan <deluan@navidrome.org>
2026-10-14 07:23:26 -07:00
Deluan Quintão
30663f7d4f
fix(jellyfin): honor likes on /Rating and add POST UserData endpoints
* fix(jellyfin): honor likes on /Rating and add POST UserData endpoints

POST .../Rating only read a numeric `rating` param that upstream Jellyfin
does not define, so a request using Jellyfin's `likes` flag (or no value
at all, or a malformed one) silently cleared the user's rating. The
handler now reads `likes` like Jellyfin (true stores 5 stars, false 1
star, matching Jellyfin's 10 and 1), keeps the numeric `rating` param for
existing clients, and answers 400 without writing when the value is
missing, malformed or outside 0-10. Clearing is left to DELETE. The
current /UserItems/{itemId}/Rating spelling is now routed as well.

Adds POST /UserItems/{itemId}/UserData and the legacy
/Users/{userId}/Items/{itemId}/UserData. They write Rating, Likes and
IsFavorite with Jellyfin's precedence (Rating wins over Likes), leave
omitted or null fields untouched, and ignore play-state fields. The body
must be a single JSON object: trailing data, null, or out-of-range values
are rejected before anything is written.

Rating and UserData writes whose userId names a different user now get
403 instead of silently writing the caller's own data. Annotation
responses return the item's full UserData, including Jellyfin's derived
Likes flag (rating >= 6.5). The README compatibility notes are updated.

* refactor(jellyfin): simplify rating and UserData handlers

Moves the Jellyfin 0-10 to stars conversions (StarsFromRating,
StarsFromLikes) into the dto package next to the reverse mapping and the
Likes threshold, so both directions live together. The userId ownership
check is folded into a single applyCallerUserData helper instead of being
called by hand in three handlers, the setFavorite passthrough is dropped,
and decodeUserDataBody now writes its own 400 like the other (value, ok)
helpers.

Tests: withChiURLParam is now variadic, replacing the duplicate
withChiParams helper; the three other-user 403 specs and the
empty-object/no-event spec become table entries; and redundant specs are
removed. Behavior is unchanged.
2026-10-12 11:49:07 -07:00
Rucolastico
8e306b1f61
feat(ui): add Solarized Light and Dark themes (#6280)
* feat(ui): add Solarized Light and Dark themes

Add Light and Dark variants of Ethan Schoonover's Solarized palette, built
on the Tokyo Night theme structure so they cover the app bar, sidebar,
tables, album grid, album/playlist details, login and the player.

Text colors are one step stronger than canonical Solarized body text
(base01 on light, base1 on dark) so table text keeps WCAG AA contrast.
The Dark variant uses cyan instead of violet as the secondary accent,
since violet is too dark on base03.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: rucolastico <diegoricomartell@gmail.com>

* fix(ui): improve Solarized contrast and table row hover

Address review feedback on the Solarized themes:

- Use text-specific shades for links and the login system name, keeping
  them above 4.5:1 on table surfaces and hover rows (darkened blue on
  Light, lightened cyan on Dark). Canonical blue stays for controls.
- Darken the Light theme's violet accent, which is also used as text
  (album artist), to keep it above 4.5:1.
- Give secondary buttons readable text: base3 on violet (Light) and
  base03 on cyan (Dark), instead of the body text color.
- Apply the row hover color to table cells, whose opaque background was
  hiding the row hover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: rucolastico <diegoricomartell@gmail.com>

* fix(ui): keep Solarized app bar title and icons readable

The app bar uses the secondary color, whose contrastText matched the
app bar background (1:1 in Light, 1.15:1 in Dark). Override the app bar's
colorSecondary text with the theme foreground (4.99:1 Light, 4.86:1 Dark),
keeping secondary.contrastText for buttons on the accent color.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: rucolastico <diegoricomartell@gmail.com>

---------

Signed-off-by: rucolastico <diegoricomartell@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Deluan Quintão <deluan@navidrome.org>
2026-10-11 13:33:34 -04:00
Deluan Quintão
4ae97ab59e
Merge pull request #6313 from navidrome/investigate-6310-20261010
fix(playlists): drop unknown track ids when adding to a playlist
2026-10-11 10:05:15 -07:00
Deluan
803b2da8ee refactor(playlists): simplify #6310 tests and update check comments
Builds the removeOrphans fixture with a single INSERT instead of shifting positions in two UPDATE passes, and has the Insert test keep the playlist id instead of reading a private repository field. Two comments now say that addTracks owns the existence check as well as the library check, and that Insert closes holes left by any id keepAccessible drops. No behavior change.
2026-10-10 11:35:43 -04:00
Deluan
74e96a2bb7 fix(playlists): drop unknown track ids when adding to a playlist
Adding tracks to a playlist skipped the media_file lookup for admins and for users who can see every library, so ids matching no track were stored as orphan playlist_tracks rows and reported as added. The native API returned an inflated "added" count, and the hidden rows left gaps in the positions, so Subsonic songIndexToRemove could delete a hidden row instead of the song at that index.

keepAccessible now always checks the ids against media_file. applyLibraryFilter is already a no-op for those users, so the check only drops unknown ids. Rows stored before this fix are still removed by the existing GC removeOrphans step on the next full scan, or on any scan that finds changes.

Fixes #6310
2026-10-10 11:28:58 -04:00
Deluan Quintão
497dfe2586
Merge pull request #6300 from navidrome/docs/hosting-badges-6258
docs: render managed hosting links as proportionate badges
2026-10-09 05:45:55 -07:00
deluan
b70ba3a49e docs: use equal-size local hosting badges without stretching artwork 2026-10-08 22:19:34 -04:00
deluan
d5a2e1e813 docs: match README deployment badges to native PikaPods height 2026-10-08 22:02:28 -04:00
deluan
b4d2c3e4af docs: render hosting providers as proportionate deployment badges 2026-10-08 21:59:52 -04:00
raphmim
22ce85e5d5 Minor fixes based on AI suggestions 2026-10-08 21:59:04 -04:00
raphmim
aea60c6e99 Badges for new cloud providers 2026-10-08 21:59:04 -04:00
Deluan Quintão
b78c963931
fix(scanner): respect FollowSymlinks in watcher-triggered scans (#6293)
* fix(scanner): respect FollowSymlinks in watcher-triggered scans

With FollowSymlinks disabled, creating a folder symlink inside the library
made the watcher schedule a selective scan with the link itself as the
target. walkDirTree only checked FollowSymlinks for child entries, so it
walked the link and imported its files as duplicates (or, for links that
point outside the library, files that should never be scanned).

walkDirTree now skips any target folder whose path, or any parent folder,
is a symlink when FollowSymlinks is disabled. The skipped target stays in
lastUpdates, so rows previously imported through it are marked missing,
matching what a full scan does. localFS now implements fs.ReadLinkFS so
fs.Lstat can see symlinks instead of following them.

Fixes #6292

* test(scanner): run the #6292 symlinked target tests on Windows

Remove the SkipOnWindows guard from the symlinked target folder tests, so
the go-windows CI job covers the FollowSymlinks fix for selective scans.
2026-10-08 17:34:42 -04:00
Deluan Quintão
52135913d4
fix(artwork): don't crash the server when a playlist's tracks can't be loaded (#6267)
Playlist().Tracks returns nil when its internal Get fails (for example when the
context is canceled at shutdown), and resolvePlaylist called GetAlbumIDs on it,
panicking with a nil pointer dereference. The artwork drain runs on a bare
goroutine, so the panic killed the whole server.

resolvePlaylist now returns an error when Tracks is nil, and the worker recovers
panics per item: it logs the panic with the item details and stack, and marks
the item as a failed attempt so the rest of the batch still runs.

Fixes #6266
2026-10-06 07:57:07 -07:00
Deluan Quintão
caa2f8a0c0
fix(ui): make playlist toggle switches visible in all themes (#6277)
* fix(ui): make playlist toggle switches visible in all themes

The Public and Auto-import switches in the playlist list did not set a
color, so Material-UI used the theme's secondary color. Many themes use
secondary as a surface color close to the table background, which made
checked switches nearly invisible (Catppuccin, Rosé Pine, Monokai,
Moonbase and others).

Set color="primary" on the playlist switch, like every other switch in
the app, and make primary the default MuiSwitch color in useCurrentTheme
so future switches cannot regress. Fixes #6272.

* refactor(ui): drop secondary switch overrides from themes

Dracula, Gruvbox Dark, Tokyo Night and Tokyo Night Light styled checked
MuiSwitch colorSecondary to work around the same invisible-switch problem
(Gruvbox in #5064). With primary as the default switch color and every
switch in the app using it, no switch renders with colorSecondary anymore,
so these overrides are dead code.
2026-10-06 09:50:11 -04:00
Deluan Quintão
95f67d2c4e
fix(share): reuse cached transcodes for share streams and zip downloads (#6262)
* fix(share): reuse cached transcodes when streaming from share links

Public share streams built the stream request with only the share's format
and bit rate, leaving sample rate, bit depth and channels at zero. Regular
playback resolves those through the transcode decider (e.g. 48000 Hz for
Opus), and they are part of the transcoding cache key, so a track already
transcoded during normal playback was transcoded again into a separate,
identical cache entry when played through a share link.

The public router now resolves share stream requests with the same
TranscodeDecider.ResolveRequest used by the Subsonic stream endpoint, so
both paths produce the same request and share cache entries.

Fixes #6261

* fix(archiver): reuse cached transcodes when zipping downloads

Zip downloads (album, artist, playlist and share) built the stream request
with only the format and bit rate, leaving sample rate, bit depth and
channels at zero. Those are part of the transcoding cache key, so a track
already transcoded for playback was transcoded again into a separate cache
entry when downloaded in a zip, and vice versa.

The archiver now resolves each request with TranscodeDecider.ResolveRequest,
the same as single-song downloads and streams. This also applies the
decider's defaults, so a zip requested without a bit rate uses the target
format's default bit rate instead of leaving it to ffmpeg.

* fix(archiver): name zip entries after the resolved transcoding format

The transcode decider can pick a different format than the one requested
(for example a player's forced transcoding, or a fallback to the default
downsampling format when the requested one can't be produced). Zip entry
names and the playlist M3U were still built from the requested format, so
an entry could end in .mp3 or .flac while holding Opus data.

Each track's request is now resolved before its entry name is built, and
the name uses the resolved format.
2026-10-03 08:58:54 -07:00
Deluan Quintão
758e64c999
feat(scanner): per-library PID configuration (#6252)
* feat(model): add per-library PID config columns

* refactor(metadata): pass PID config to ToMediaFile and add spec validation

* feat(scanner): rescan only libraries whose PID config changed

* feat(server): validate library PID config and rescan on change

* feat(ui): edit per-library PID config

* fix(ui): label the PID mode selects

* fix: tighten per-library PID rescan edge cases

An interrupted PID rescan no longer upgrades every library to a full scan, a save that loses the race for the scanner logs at debug, the confirm dialog only shows when the effective PID spec changes, and it now gets translation keys.

* refactor(metadata): pass the library to ToMediaFile

ToMediaFile and core.Inspect took the library ID and its PID config as
separate arguments, so a caller could mix values from two libraries. They
now take the model.Library and resolve the effective PID config from it.

* chore: tidy per-library PID comments, PropTypes and migration

Trim comments that restated the code, add PropTypes to the new UI
components, and recreate the migration with make migration-sql.

* fix(ui): show the PID spec help under its input

* feat(cmd): make inspect use the file's library PID config

inspect always used the global PID config, so it showed different IDs than
the scanner for files in a library with an override. It now finds the
file's library in the DB and uses its effective config, falling back to
the global config when there is no DB or the file is outside every
library. It never creates a DB. The library path matcher moves from
core/playlists to model so both can use it.

* refactor: simplify per-library PID code

Share the DB-file check between CLI commands, move ErrAlreadyScanning to
model so core no longer imports scanner, read the libraries once for
insights, and let ValidatePIDSpec accept an empty spec and look tags up
directly. In the scanner, use FullScanInProgress instead of a second
flag, and skip recomputing album IDs when the album spec did not change.
In the UI, share the PID inputs between Create and Edit, and use docsUrl.

* feat(ui): add section titles to Library Create and pre-fill Custom PID specs

Custom now starts from the global spec, so admins edit a working spec
instead of typing one from scratch.

* fix(inspect): map files with the library-relative path the scanner uses

Inspect gave metadata the file's directory as typed, so folder-based PIDs
never matched the DB. It now uses the path relative to the library root,
through the scanner's helper, which moves to model.

* fix(scanner): say when a PID rescan only covers target folders

* fix: reject tag aliases in album PID specs and match root libraries

Tags are stored under canonical names, so an alias in a spec always reads
as empty. In an album spec that gives every album the same ID, so album
specs now require the tag name. Track specs keep accepting aliases, since
the default one uses them. LibraryMatcher now matches paths under a
library at the filesystem root.

* refactor(model): move the tag alias lookup to tag_mappings.go

* test: run the library matcher and inspect tests on Windows

Build test paths with filepath instead of Unix literals, so they use the
OS separator like filepath.Abs output, and drop the Windows skips.

* feat(ui): add pt-BR translations for per-library PID settings
2026-10-02 05:05:32 -04:00
Deluan Quintão
0e1893530b
fix(ui): don't crash the playlist list when rows lose their record (#6250)
* fix(ui): don't crash playlist list rows that lost their record

react-admin 3 evicts records fetched more than 10 minutes ago whenever
another getList for the same resource completes, but the list keeps its
cached ids. The Datagrid then renders those rows with an undefined record,
and the Public and Auto-import switches crashed reading record.id. This
happened when the playlist list was left open and the sidebar or the add
to playlist dialog reloaded a smaller set of playlists.

Both switches now render nothing when the row has no record; the next list
refresh fills the row in again.

* refactor(ui): merge playlist list toggles into one ToggleField

The Public and Auto-import switches were copies that differed only in the
field they flip. ToggleField now flips its source field, and
ToggleAutoImport just shows it for playlists that have a file path. The
tests render inside TestContext, so they use react-admin's real hooks
instead of mocks.
2026-09-29 13:23:36 -04:00
Deluan Quintão
e03ce87177
fix(ui): make Undo and AMusic Save buttons readable (#6249) 2026-09-29 11:21:14 -04:00
David Davó
3a31f702b5
feat(ui): add played filter to album list (#6207) 2026-09-28 22:50:13 -04:00
Matt Van Horn
a62d1629f0
fix(ui): honor EnableCoverAnimation for theme cover animations (#6234)
* fix: honor cover animation setting in Squiddies Glass

Fixes #5170

* fix(ui): move cover animation check into AlbumDetails

Apply a noCoverAnimation class from AlbumDetails when
enableCoverAnimation is off, so every theme gets the fix. Drop the
Squiddies Glass theme changes and its test, and cover the class in
AlbumDetails.test.jsx.

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: Deluan Quintão <deluan@navidrome.org>
2026-09-28 18:06:44 -04:00
Deluan Quintão
612c8290f9
feat(ui): show read-only values in edit forms as dimmed, themable inputs (#6238) 2026-09-28 08:48:36 -04:00
DawidKrynski
ab5869123d
fix(playlists): include co-credited album artists when adding an artist to a playlist - #6240 (#6241)
* fix(persistence): include co-credited album artists when adding an artist to a playlist - #6240

Signed-off-by: Dawid Krynski <188586034+DawidKrynski@users.noreply.github.com>

* test(persistence): cover first album artist and track-artist-only in AddArtists

The joint track now uses a track artist that is not an album artist, and
the AddArtists specs check all three cases: the first album artist still
matches, a co-credited album artist matches, and a track-artist-only ID
adds nothing. The last case guards against widening the role filter.

---------

Signed-off-by: Dawid Krynski <188586034+DawidKrynski@users.noreply.github.com>
Co-authored-by: Dawid Krynski <188586034+DawidKrynski@users.noreply.github.com>
Co-authored-by: Deluan <deluan@navidrome.org>
2026-09-28 08:07:05 -04:00
Deluan Quintão
4cdffd5633
feat(subsonic): OpenSubsonic API key authentication (#6219)
* feat(persistence): store hashed API keys on players

* feat(core): refresh key-bound players without renaming them

Add Players.Touch, which records usage for a player already identified by
an API key without guessing its identity or overwriting its name. Register
also stops renaming players that have an API key.

Register no longer returns player save errors (or a stale FindMatch
ErrNotFound when the save is rate-limited); save failures are only logged,
and only the transcoding lookup error is returned, same as Touch.

* feat(subsonic): authenticate with OpenSubsonic API keys

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

* feat(subsonic): add tokenInfo and advertise apiKeyAuthentication

* feat(server): add endpoints to generate and revoke player API keys

* feat(ui): manage player API keys

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

* fix(subsonic): throttle API keys per key and IP

A stale key on one device exhausted the shared per-IP bucket and locked out
every valid key from the same IP. The limiter only stores a hash of the bucket
string, so the key is not retained. Also adds e2e coverage of API key auth
through the real repository, and clarifies the player resolution log message.

* fix(ui): keep the new API key dialog open until closed

The key is shown only once, so Escape and backdrop clicks no longer dismiss
it. Also clarifies when the key can be used as a password.

* refactor: simplify API key code paths

Share the player refresh tail between Register and Touch, fold the
ownership-filtered write tail into execOwned, parse the query once for
apiKey conflicts, derive HasAPIKey in the player mock, share the player
form inputs between create and edit, and pick the delete button by key
state instead of spreading conditional props.

* feat(players): set API keys through the player record

The key is a write-only apiKey field applied on save: required and owner-only on create, optional on edit, empty to revoke. Replaces the generate/revoke endpoints.

* fix(players): reject API keys already in use

Creating or editing a player with a key another player already has now returns a validation error instead of a 500, and a create that loses the race no longer leaves a keyless player behind. Ownership is checked before the key on create.

* feat(ui): edit player API keys as a form field

Replaces the show-once dialog, whose icon-less Close button was invisible on mobile. The key is generated in the browser, required and pre-filled on create.

* fix(ui): keep new player API keys out of the record cache

The json-server create response echoes the request body, and undoable edits merge the payload into the cache, so the key could reappear on the edit page. Strip it from the create result and save player edits pessimistically. Also fall back to a prompt when the clipboard write fails.

* fix(ui): polish player API key field

Set userId on the created player record so owner actions show immediately, and show a neutral no-key message to non-owners.

* refactor: simplify player API key create and field

Write the key hash in the create INSERT so the unique index settles
races, re-read the created player instead of hand-building the cached
record, reuse isWritable for the revoke check, and collapse the key
field's derived state and generate/regenerate buttons.

* fix(ui): let the API key field size like other inputs

fullWidth is now opt-in instead of forced.

* fix(ui): align the API key field with other player inputs

Apply react-admin's input className, move the actions (now including Copy) below the field, and use a monospace font so the whole key fits.

* fix(ui): redirect to the player list after create

Matches the other create pages.

* refactor(persistence): name the write-access rule for owned rows

Owned-row writes now say which row they target and who may write it: ownedRow(rowID, ownerOrAdmin|ownerOnly) builds the WHERE, updateOwnedRow applies it, and SetAPIKey uses ownerOnly instead of a hand-built user_id filter. updateOwned/deleteOwned keep their signatures.

* fix(players): apply an edit's key change and fields atomically

Update now runs SetAPIKey and the column update in one transaction. Also shares the key format check, drops FindByAPIKey's unneeded empty-key guard, and sets the context username only on the apiKey path.

* fix(subsonic): treat any credential param sent with apiKey as a conflict

The spec requires error 43 when u, p, t or s is present with apiKey, even with an empty value.

* refactor(subsonic): leave the player cookie code unchanged for key-bound requests

Return early instead of wrapping the cookie block, so the diff (and CodeQL's view of it) matches master.

* fix(subsonic): don't count key lookup errors as failed logins

A database error while checking a key sent as the password now surfaces as a server error instead of a bad password, so it no longer feeds the failed-login limiter.

* feat(players): use nds_ as the API key prefix

Part of a Navidrome secret prefix family (nd + a letter for the kind), alongside ndg_ for API v1 grants.

* feat(ui): make player API keys easier to find

Label the Settings menu entry "Players & API keys", add an API key
filter to the player list, show the key icon in the mobile list, and
add Brazilian Portuguese translations for the new player strings.

Signed-off-by: Deluan <deluan@navidrome.org>

* feat(ui): always show the player API key filter

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(ui): hide the unset Last Seen date in the player list

Players created by hand have no last_seen yet, which showed as 12/31/1.

Signed-off-by: Deluan <deluan@navidrome.org>

---------

Signed-off-by: Deluan <deluan@navidrome.org>
Co-authored-by: amCap1712 <amCap1712@users.noreply.github.com>
2026-09-27 21:56:58 -04:00
Deluan Quintão
ce484083bf
fix(server): exit with an error code when the server fails to start (#6236)
When a startup step failed (for example, the port was already in use), runNavidrome only logged the error and returned. In service mode, service.Run() kept waiting for a stop signal, so the process stayed up serving nothing and the service manager never restarted it. A plain run exited with code 0.

runNavidrome now returns the error, unless its context was cancelled by a normal shutdown. Both the plain run and the service goroutine exit with code 1 on that error. The systemd unit no longer lists 1, 2 and 8 in SuccessExitStatus, so Restart=on-failure restarts the service on exit code 1.

Fixes #6235
2026-09-27 14:18:24 -04:00
Deluan Quintão
46c432719f
fix(log): redact LastFM keys and Prometheus password in config dump (#6233)
The startup Configuration dump is rendered with pretty.Sprintf("%# v"), which
pads multi-line struct fields with spaces after the colon. The ApiKey and
Secret redaction patterns required the quote right after the colon, so
LastFM.ApiKey and LastFM.Secret were logged in clear text even with
EnableLogRedacting on. Allow optional whitespace after the colon, like the
other config patterns already do.

Prometheus.Password had no redaction pattern at all. Add one that also skips
escaped quotes, since the password can hold any character and pretty prints
it Go-quoted.

Add tests for the padded and unpadded forms, plus one that redacts a real
pretty.Sprintf dump of LastFM- and Prometheus-shaped structs so a padding
change in pretty can't bring the leak back.

Reported in https://github.com/navidrome/navidrome/discussions/6232
2026-09-26 23:30:50 -04:00
911 changed files with 36930 additions and 18672 deletions

View file

@ -1,98 +1,74 @@
name: Bug Report name: Bug report
description: Before opening a new issue, please search to see if an issue already exists for the bug you encountered. description: Report something that is not working as expected. You do not need to know the cause or how to fix it.
title: "[Bug]: " title: "[Bug]: "
labels: ["bug", "triage"] labels: ["triage"]
#assignees: #assignees:
# - deluan # - deluan
body: body:
- type: markdown - type: markdown
attributes: attributes:
value: | value: |
### Thanks for taking the time to fill out this bug report! Thanks for reporting a problem. For a possible security vulnerability, use [private reporting](https://github.com/navidrome/navidrome/security/advisories/new).
- type: checkboxes - type: checkboxes
id: requirements id: requirements
attributes: attributes:
label: "I confirm that:" label: "I confirm that:"
options: options:
- label: I have searched the existing [open AND closed issues](https://github.com/navidrome/navidrome/issues?q=is%3Aissue) to see if an issue already exists for the bug I've encountered - label: I have searched the existing [open and closed issues](https://github.com/navidrome/navidrome/issues?q=is%3Aissue) and found no matching open report.
required: true
- label: I'm using the latest Navidrome release and can reproduce the issue on it.
required: true
- type: textarea
id: what-happened
attributes:
label: What happened
description: Describe what you observed and how it affected you. Include any error message you saw. You do not need to diagnose the cause or suggest code changes. If a closed issue matches, link it here.
validations:
required: true required: true
- label: I'm using the latest version (your issue may have been fixed already)
required: false
- type: input - type: input
id: version id: version
attributes: attributes:
label: Version label: Navidrome version
description: What version of Navidrome are you running? (please try upgrading first, as your issue may have been fixed already). description: Which Navidrome version or build are you using? If you cannot find it, enter 'not sure'. If you tried another version, mention whether the behavior changed.
validations: validations:
required: true required: true
- type: textarea - type: textarea
id: expected
attributes: attributes:
label: Current Behavior label: Expected behavior and why
description: A concise description of what you're experiencing. description: What did you expect, and why? If available, link documentation, an applicable API contract, or a previously working version. A personal expectation is useful context too; it does not by itself establish that the product should change. If you are unsure, say so.
validations: validations:
required: true required: false
- type: textarea - type: textarea
id: steps
attributes: attributes:
label: Expected Behavior label: Steps to reproduce
description: A concise description of what you expected to happen. description: List the steps, relevant settings, and how often the problem occurs. If it happens only sometimes, describe what was happening when you noticed it and what you have already tried.
validations:
required: true
- type: textarea
attributes:
label: Steps To Reproduce
description: Steps to reproduce the behavior.
placeholder: |
1. In this scenario...
2. With this config...
3. Click (or Execute) '...'
4. See error...
validations: validations:
required: false required: false
- type: textarea - type: textarea
id: env id: env
attributes: attributes:
label: Environment label: Relevant environment
description: | description: >-
examples: Include only details relevant to this problem: server operating system, installation method, and the browser or client app with its version, if involved. Leave out details you do not know. Examples of installation methods: Docker, downloaded binary, package, or source build.
- **OS**: Ubuntu 20.04
- **Browser**: Chrome 110.0.5481.177 on Windows 11
- **Client**: DSub 5.5.1
value: |
- OS:
- Browser:
- Client:
render: markdown
- type: dropdown
id: distribution
attributes:
label: How Navidrome is installed?
multiple: false
options:
- Docker
- Binary (from downloads page)
- Package
- Built from sources
validations: validations:
required: true required: false
- type: textarea - type: textarea
id: config id: config-logs
attributes: attributes:
label: Configuration label: Relevant configuration and logs
description: Please copy and paste your `navidrome.toml` (and/or `docker-compose.yml`) configuration. This will be automatically formatted into code, so no need for backticks. description: >-
render: toml Paste only the configuration settings or log excerpt related to this problem. Remove passwords, tokens, API keys, session cookies, private URLs, and identifying information before submitting. Debug logs are optional. If you cannot safely share an excerpt, explain what it shows instead. [Log guidance](https://www.navidrome.org/docs/faq/#-where-are-the-logs).
validations:
required: false
- type: textarea - type: textarea
id: logs id: additional-context
attributes: attributes:
label: Relevant log output label: Screenshots or additional context
description: Please copy and paste any relevant log output (change your `LogLevel` (`ND_LOGLEVEL`) to debug). This will be automatically formatted into code, so no need for backticks. ([Where I can find the logs?](https://www.navidrome.org/docs/faq/#where-are-the-logs)) description: Add screenshots, recordings, links, or other observations that help explain the problem. Remove private information from attachments as well.
render: shell validations:
- type: textarea required: false
attributes:
label: Anything else?
description: |
Links? References? Anything that will give us more context about the issue you are encountering!
Tip: You can attach screenshots by clicking this area to highlight it and then dragging files in.
- type: checkboxes - type: checkboxes
id: terms id: terms
attributes: attributes:

View file

@ -1,8 +1,8 @@
blank_issues_enabled: false blank_issues_enabled: false
contact_links: contact_links:
- name: Ideas for new features - name: Ideas and behavior changes
url: https://github.com/navidrome/navidrome/discussions/categories/ideas url: https://github.com/navidrome/navidrome/discussions/categories/ideas
about: This is the place to share and discuss new ideas and potentially new features. about: Describe the problem, intended outcome, and use case before starting an implementation.
- name: Support requests - name: Support requests
url: https://github.com/navidrome/navidrome/discussions/categories/q-a url: https://github.com/navidrome/navidrome/discussions/categories/q-a
about: This is the place to ask questions. about: Ask for help with setup, configuration, or using Navidrome.

View file

@ -1,8 +1,15 @@
> **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 ### Description
<!-- Please provide a clear and concise description of what this PR does and why it is needed. --> <!-- 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. -->
**AI use** (check one):
- [ ] Yes, AI helped generate or modify code or tests, draft substantive PR text, or create this PR
- [ ] No
<!-- Tool names and prompts are not required. -->
### Related Issues ### Related Issues
<!-- List any related issues, e.g., "Fixes #123" or "Related to #456". --> <!-- List related issues, such as "Fixes #123" or "Related to #456". When prior agreement is required, link the maintainer's agreement on the intended behavior and scope. Otherwise, explain why agreement is not needed, such as the small-change exception or a translation update. For a larger change, link the agreed design and identify this phase. -->
### Type of Change ### Type of Change
- [ ] Bug fix - [ ] Bug fix
@ -12,27 +19,29 @@
- [ ] Other (please describe): - [ ] Other (please describe):
### Checklist ### Checklist
Please review and check all that apply: 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 - [ ] My code follows the project’s coding style
- [ ] I have tested the changes locally - [ ] I have tested the changes locally
- [ ] I have added or updated documentation as needed - [ ] I have added or updated documentation as needed
- [ ] I have added tests that prove my fix/feature works (or explain why not) - [ ] I have added tests that prove my fix/feature works (or explain why not)
- [ ] All existing and new tests pass - [ ] 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 ### How to Test
<!-- Describe the steps to test your changes. Include setup, commands, and expected results. --> <!-- 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. --> <!-- Add screenshots, GIFs, or links to demos if your change includes UI updates or visual changes. -->
### Additional Notes ### Additional Notes
<!-- Anything else the maintainer should know? Potential side effects, breaking changes, or areas of concern? --> <!-- Anything else the maintainer should know? Potential side effects, breaking changes, or areas of concern? Where relevant, explain important tradeoffs, new dependencies or ongoing maintenance costs, and simpler alternatives considered. -->
<!-- <!--
**Tips for Contributors:** **Tips for Contributors:**
- Be concise but thorough. - Be concise but thorough.
- If your PR is large, consider breaking it into smaller PRs. - If your PR is large, consider breaking it into smaller PRs within the agreed design and scope.
- Tag the maintainer if you need a prompt review. - Review timing depends on maintainer availability; please do not tag the maintainer for faster review.
- Avoid force pushing to the branch after opening the PR, as it can complicate the review process. - Avoid force pushing to the branch after opening the PR, as it can complicate the review process.
--> -->

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

@ -79,7 +79,7 @@ jobs:
with: with:
version: ${{ steps.golangci-version.outputs.version }} version: ${{ steps.golangci-version.outputs.version }}
problem-matchers: true problem-matchers: true
args: --timeout 2m args: --timeout 3m
- name: Run go goimports - name: Run go goimports
run: go run golang.org/x/tools/cmd/goimports@latest -w `find . -name '*.go' | grep -v '_gen.go$' | grep -v '.pb.go$'` run: go run golang.org/x/tools/cmd/goimports@latest -w `find . -name '*.go' | grep -v '_gen.go$' | grep -v '.pb.go$'`
@ -262,14 +262,15 @@ jobs:
go-version-file: go.mod go-version-file: go.mod
- uses: msys2/setup-msys2@v2 - uses: msys2/setup-msys2@v2
id: msys2
with: with:
msystem: MINGW64 msystem: UCRT64
install: mingw-w64-x86_64-gcc install: mingw-w64-ucrt-x86_64-gcc
update: false update: false
- name: Add mingw64 to PATH - name: Add MSYS2 UCRT64 to PATH
shell: bash shell: bash
run: echo "C:/msys64/mingw64/bin" >> $GITHUB_PATH run: echo "${{ steps.msys2.outputs.msys2-location }}/ucrt64/bin" >> $GITHUB_PATH
- name: Cache ffmpeg - name: Cache ffmpeg
id: ffmpeg-cache id: ffmpeg-cache
@ -519,13 +520,18 @@ jobs:
docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.docker.outputs.version }} docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.docker.outputs.version }}
push-manifest-dockerhub: push-manifest-dockerhub:
name: Push to Docker Hub name: Push to Docker Hub (${{ matrix.repository }})
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
contents: read contents: read
needs: [build, check-push-enabled] needs: [build, check-push-enabled]
if: needs.check-push-enabled.outputs.is_enabled == 'true' && vars.DOCKER_HUB_REPO != '' if: needs.check-push-enabled.outputs.is_enabled == 'true' && vars.DOCKER_HUB_REPO != ''
continue-on-error: true continue-on-error: true
strategy:
fail-fast: false
matrix:
# Always push to DOCKER_HUB_REPO. The upstream repository also pushes to the navidrome/navidrome org repository.
repository: ${{ fromJSON(github.repository == 'navidrome/navidrome' && format('["{0}","navidrome/navidrome"]', vars.DOCKER_HUB_REPO) || format('["{0}"]', vars.DOCKER_HUB_REPO)) }}
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
@ -541,7 +547,7 @@ jobs:
id: docker id: docker
with: with:
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
hub_repository: ${{ vars.DOCKER_HUB_REPO }} hub_repository: ${{ matrix.repository }}
hub_username: ${{ secrets.DOCKER_HUB_USERNAME }} hub_username: ${{ secrets.DOCKER_HUB_USERNAME }}
hub_password: ${{ secrets.DOCKER_HUB_PASSWORD }} hub_password: ${{ secrets.DOCKER_HUB_PASSWORD }}
@ -558,7 +564,7 @@ jobs:
- name: Inspect image in Docker Hub - name: Inspect image in Docker Hub
run: | run: |
docker buildx imagetools inspect ${{ vars.DOCKER_HUB_REPO }}:${{ steps.docker.outputs.version }} docker buildx imagetools inspect ${{ matrix.repository }}:${{ steps.docker.outputs.version }}
cleanup-digests: cleanup-digests:
name: Cleanup digest artifacts name: Cleanup digest artifacts

View file

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

View file

@ -17,7 +17,7 @@ jobs:
run: | run: |
.github/workflows/update-translations.sh 2> title.tmp .github/workflows/update-translations.sh 2> title.tmp
title=$(cat title.tmp) title=$(cat title.tmp)
echo "::set-output name=title::$title" echo "title=$title" >> "$GITHUB_OUTPUT"
rm title.tmp rm title.tmp
- name: Show changes, if any - name: Show changes, if any
run: | run: |

2
.gitignore vendored
View file

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

View file

@ -11,26 +11,142 @@ linters:
- bodyclose - bodyclose
- containedctx - containedctx
- copyloopvar - copyloopvar
- depguard
- dogsled - dogsled
- durationcheck - durationcheck
- errchkjson
- errorlint - errorlint
- exhaustive
- forbidigo - forbidigo
- ginkgolinter
- gocritic - gocritic
- gocyclo - gocyclo
- godoclint
- goprintffuncname - goprintffuncname
- gosec - gosec
- misspell - misspell
- modernize
- nakedret - nakedret
- nilerr - nilerr
- nolintlint
- perfsprint
- rowserrcheck - rowserrcheck
- unconvert
- whitespace
disable:
- staticcheck - staticcheck
- thelper
- unconvert
- usestdlibvars
- usetesting
- whitespace
settings: 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: errcheck:
exclude-functions: exclude-functions:
- (*github.com/zeebo/xxh3.Hasher).Write - (*github.com/zeebo/xxh3.Hasher).Write
errchkjson:
report-no-exported: true
ginkgolinter:
forbid-focus-container: true
force-expect-to: true
force-succeed: true
force-tonot: true
validate-async-intervals: true
godoclint:
# a doc comment that names another symbol (left behind by a move or a paste) is a bug
default: none
enable:
- start-with-name
options:
start-with-name:
include-unexported: true
gocritic: gocritic:
disable-all: true disable-all: true
enabled-checks: enabled-checks:
@ -41,6 +157,9 @@ linters:
- G401 - G401
- G505 - G505
- G115 - G115
exhaustive:
# third-party enums: listing every value only adds noise; our own enums must be listed in full
ignore-enum-types: ^(reflect\.Kind|go\.senan\.xyz/taglib\.FileFormat)$
forbidigo: forbidigo:
forbid: forbid:
- pattern: 'tx\.Exec$' - pattern: 'tx\.Exec$'
@ -49,9 +168,29 @@ linters:
msg: "use tx.QueryContext(ctx, ...) in migrations to propagate context" msg: "use tx.QueryContext(ctx, ...) in migrations to propagate context"
- pattern: 'tx\.QueryRow$' - pattern: 'tx\.QueryRow$'
msg: "use tx.QueryRowContext(ctx, ...) in migrations to propagate context" 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: govet:
enable: enable:
- nilness - nilness
staticcheck:
dot-import-whitelist:
- github.com/Masterminds/squirrel
thelper:
# Helper() is what fixes failure line numbers; the t/tb/b/f parameter name does not
test:
name: false
benchmark:
name: false
tb:
name: false
fuzz:
name: false
exclusions: exclusions:
rules: rules:
- linters: - linters:
@ -61,9 +200,20 @@ linters:
- path: _test\.go - path: _test\.go
linters: linters:
- containedctx - containedctx
# forbidigo rules are scoped by their msg: "in migrations" or "in tests use"
- path-except: 'db/migrations/' - path-except: 'db/migrations/'
linters: linters:
- forbidigo - 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 generated: lax
presets: presets:
- comments - 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

@ -1,93 +1,72 @@
# Navidrome Contribution Guide # Navidrome Contribution Guide
Navidrome is a streaming service which allows you to enjoy your music collection from anywhere. We'd welcome you to contribute to our open source project and make Navidrome even better. There are some basic guidelines which you need to follow if you like to contribute to Navidrome. Navidrome has one maintainer and limited review capacity. We welcome contributions that fit the project and remain practical to maintain. A smaller number of focused, well-understood contributions is more useful than a large volume of code that needs extensive rework.
- [Asking Support Questions](#asking-support-questions) ## Support and conduct
- [Code of Conduct](#code-of-conduct)
- [Issues](#issues)
- [Pull Requests](#pull-requests)
Use [Discussions → Q&A](https://github.com/navidrome/navidrome/discussions/categories/q-a) for support. Please follow the [Code of Conduct](CODE_OF_CONDUCT.md).
## Asking Support Questions ## Issues and ideas
We have an active [discussion forum](https://github.com/navidrome/navidrome/discussions) where users and developers can ask questions. Please don't use the GitHub issue tracker to ask questions.
## Code of Conduct Anyone may report a suspected bug. Search existing [open and closed issues](https://github.com/navidrome/navidrome/issues?q=is%3Aissue) and [discussions](https://github.com/navidrome/navidrome/discussions), and check the [documentation](https://www.navidrome.org/docs/) and [FAQ](https://www.navidrome.org/docs/faq/) first. Use the [bug report form](https://github.com/navidrome/navidrome/issues/new?template=bug_report.yml) for suspected defects and [Discussions → Ideas](https://github.com/navidrome/navidrome/discussions/categories/ideas) for new features or changes to intended behavior.
Please read the following [Code of Conduct](https://github.com/navidrome/navidrome/blob/master/CODE_OF_CONDUCT.md).
## Issues Describe what happened, what you expected, and why that expectation should hold. Include reproduction steps where possible, with a reference to documentation, an applicable API contract, or a previously working version. If the problem is intermittent, explain what you observed and tried. Remove credentials and private information from logs and configuration.
Found any issue or bug in our codebase? Have a great idea you want to propose or discuss with
the developers? You can help by submitting an [issue](https://github.com/navidrome/navidrome/issues/new/choose)
to the GitHub repository.
**Before opening a new issue, please check if the issue has not been already made by searching A reported problem may involve intended behavior, configuration, or a product decision. An open issue or a label does not establish that a change has been accepted. Report security vulnerabilities [privately through GitHub](https://github.com/navidrome/navidrome/security/advisories/new).
the [issues](https://github.com/navidrome/navidrome/issues)**
## Pull requests ## Agree on the change before implementation
Before submitting a pull request, ensure that you go through the following:
- Open a corresponding issue for the Pull Request, if not existing. The issue can be opened following [these guidelines](#issues)
- Ensure that there is no open or closed Pull Request corresponding to your submission to avoid duplication of effort.
- Setup the [development environment](https://www.navidrome.org/docs/developers/dev-environment/)
- Create a new branch on your forked repo and make the changes in it. Naming conventions for branch are: `<Issue Title>/<Issue Number>`. Example:
```
git checkout -b adding-docs/834 master
```
- The commits should follow a [specific convention](#commit-conventions)
- Ensure that a DCO sign-off for commits is provided via `--signoff` option of git commit
- Provide a link to the issue that will be closed via your Pull request.
### Commit Conventions For code contributions beyond the small exceptions below, explain the problem, intended behavior, and smallest proposed scope in an existing issue or discussion. Wait for an explicit maintainer comment agreeing that the change should be pursued. Keep the discussion in one place. Silence, community support, and previous merged contributions do not replace that agreement.
Each commit message must adhere to the following format:
```
<type>(scope): <description>
[optional body] Small documentation corrections and small, unambiguous fixes that restore established behavior may be submitted directly. Provide evidence of the defect. These exceptions do not cover disputed behavior, new product choices, dependencies, or broader refactoring. If the intended behavior is unclear, discuss it first.
```
This improves the readability of the messages
#### Type For large or cross-cutting changes, agree on the design and a sequence of small, reviewable phases before implementation. Explain why the change belongs in the core, what new complexity or dependencies it introduces, and which simpler alternatives you considered. Consider existing configuration, APIs, plugins, or external tools where appropriate. Splitting a change into PRs does not remove the need to agree on the overall design and scope.
It can be one of the following:
1. **feat**: Addition of a new feature
2. **fix**: Bug fix
3. **sec**: Fixing security issues
4. **docs**: Documentation Changes
5. **style**: Changes to styling
6. **refactor**: Refactoring of code
7. **perf**: Code that affects performance
8. **test**: Updating or improving the current tests
9. **build**: Changes to Build process
10. **revert**: Reverting to a previous commit
11. **chore** : updating grunt tasks etc
If there is a breaking change in your Pull Request, please add `BREAKING CHANGE` in the optional body section ## Review your work before opening a PR
#### Scope 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.
The file or folder where the changes are made. If there are more than one, you can mention any
#### Description 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.
A short description of the issue
#### Issue number Stay involved during review: answer questions, investigate feedback, and revise the work. If you need more time or cannot continue, say so. The maintainer is not committing to finish an abandoned implementation.
The issue fixed by this Pull Request.
The body is optional. It may contain short description of changes made. ## AI Disclosure
Following all the guidelines an ideal commit will look like: AI tools may assist professional and hobbyist contributors. All code contributors must be able to personally understand, review, test, and maintain their changes, including security and performance implications; no diploma, job title, or employment is required. If you cannot assess the code yourself, report the problem instead of submitting AI-generated code. Bug reports, documentation improvements, and translations remain welcome.
```
git commit --signoff -m "feat(themes): New-theme - #834"
```
After committing, push your commits to your forked branch and create a Pull Request from there. AI-assisted work must meet the personal full-diff review and functional testing requirements above before any PR is opened, including drafts or agent-created PRs. You remain responsible for explaining the implementation, addressing feedback, and correcting the code.
The Pull Request Title can be the same as `<type>(scope): <description> - <issue number>`
A demo layout of how the Pull request body can look:
```
Closes <Issue number along with link>
Description (What does the pull request do) 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.
Changes (What changes were made ) 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.
Screenshots or Videos 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.
Related Issues and Pull Requests(if any) ## Keep the result maintainable
``` Prefer existing patterns and the smallest clear solution. Justify new abstractions, dependencies, configuration, and compatibility obligations. Include the documentation and tests needed to understand the behavior and change it safely later.
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
- Check existing [open and closed PRs](https://github.com/navidrome/navidrome/pulls?q=is%3Apr) to avoid duplicate work. If the issue author or another contributor has offered to submit a fix, ask in the issue before you start.
- Use the [development environment instructions](https://www.navidrome.org/docs/developers/dev-environment/). Work on a branch in your fork.
- Complete the [PR template](.github/pull_request_template.md) with the scope agreement or why agreement is not needed, verification evidence, and maintenance implications. Keep each PR focused.
- Follow the [commit conventions and DCO requirements](#commit-conventions-and-dco) below.
Review and merge are discretionary. Proposals may be declined, simplified, split, or deferred. PRs that do not fit Navidrome's direction, the agreed scope, or the maintainer's capacity to maintain them may be closed without detailed code review or prolonged discussion. PRs lacking evidence or left with unresolved questions may also be closed. Agreement to pursue work does not guarantee review or merge. Please do not tag the maintainer, send private messages, or post status requests to obtain faster review.
## Commit conventions and DCO
Use this commit format: `<type>(scope): <description>`, with an optional body.
Allowed types: `feat`, `fix`, `sec`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `revert`, `chore`.
Use a relevant file or folder as the scope and a concise description. Reference the related issue when one exists, and include `BREAKING CHANGE` in the body for breaking changes. Sign off every commit using `git commit --signoff`. These requirements apply equally to AI-assisted work.

View file

@ -18,11 +18,11 @@ endif
SUPPORTED_PLATFORMS ?= linux/amd64,linux/arm64,linux/arm/v5,linux/arm/v6,linux/arm/v7,linux/386,linux/riscv64,darwin/amd64,darwin/arm64,windows/amd64,windows/386 SUPPORTED_PLATFORMS ?= linux/amd64,linux/arm64,linux/arm/v5,linux/arm/v6,linux/arm/v7,linux/386,linux/riscv64,darwin/amd64,darwin/arm64,windows/amd64,windows/386
IMAGE_PLATFORMS ?= $(shell echo $(SUPPORTED_PLATFORMS) | tr ',' '\n' | grep "linux" | grep -v "arm/v5" | tr '\n' ',' | sed 's/,$$//') IMAGE_PLATFORMS ?= $(shell echo $(SUPPORTED_PLATFORMS) | tr ',' '\n' | grep "linux" | grep -v "arm/v5" | tr '\n' ',' | sed 's/,$$//')
PLATFORMS ?= $(SUPPORTED_PLATFORMS) PLATFORMS ?= $(SUPPORTED_PLATFORMS)
DOCKER_TAG ?= deluan/navidrome:develop DOCKER_TAG ?= navidrome/navidrome:develop
GOLANGCI_LINT_VERSION ?= v2.14.0 GOLANGCI_LINT_VERSION ?= v2.14.0
VACUUM_VERSION ?= v0.30.6 VACUUM_VERSION ?= v0.30.6
OAPI_CODEGEN_VERSION ?= v2.8.0 OAPI_CODEGEN_VERSION ?= v2.9.0
OASDIFF_VERSION ?= v1.32.1 OASDIFF_VERSION ?= v1.32.1
API_DIFF_BASE ?= origin/master API_DIFF_BASE ?= origin/master
@ -223,7 +223,7 @@ docker-build: ##@Cross_Compilation Cross-compile for any supported platform (che
--output "./binaries" --target binary . --output "./binaries" --target binary .
.PHONY: docker-build .PHONY: docker-build
docker-image: ##@Cross_Compilation Build Docker image, tagged as `deluan/navidrome:develop`, override with DOCKER_TAG var. Use IMAGE_PLATFORMS to specify target platforms docker-image: ##@Cross_Compilation Build Docker image, tagged as `navidrome/navidrome:develop`, override with DOCKER_TAG var. Use IMAGE_PLATFORMS to specify target platforms
@echo $(IMAGE_PLATFORMS) | grep -q "windows" && echo "ERROR: Windows is not supported for Docker builds" && exit 1 || true @echo $(IMAGE_PLATFORMS) | grep -q "windows" && echo "ERROR: Windows is not supported for Docker builds" && exit 1 || true
@echo $(IMAGE_PLATFORMS) | grep -q "darwin" && echo "ERROR: macOS is not supported for Docker builds" && exit 1 || true @echo $(IMAGE_PLATFORMS) | grep -q "darwin" && echo "ERROR: macOS is not supported for Docker builds" && exit 1 || true
@echo $(IMAGE_PLATFORMS) | grep -q "arm/v5" && echo "ERROR: Linux ARMv5 is not supported for Docker builds" && exit 1 || true @echo $(IMAGE_PLATFORMS) | grep -q "arm/v5" && echo "ERROR: Linux ARMv5 is not supported for Docker builds" && exit 1 || true
@ -354,6 +354,9 @@ check_node_env:
pre-push: lintall testall pre-push: lintall testall
.PHONY: pre-push .PHONY: pre-push
pre-push-go: lint test test-ndpgen test-i18n
.PHONY: pre-push-go
deprecated: deprecated:
@echo "WARNING: This target is deprecated and will be removed in future releases. Use 'make build' instead." @echo "WARNING: This target is deprecated and will be removed in future releases. Use 'make build' instead."
.PHONY: deprecated .PHONY: deprecated

View file

@ -5,7 +5,7 @@
[![Last Release](https://img.shields.io/github/v/release/navidrome/navidrome?logo=github&label=latest&style=flat-square)](https://github.com/navidrome/navidrome/releases) [![Last Release](https://img.shields.io/github/v/release/navidrome/navidrome?logo=github&label=latest&style=flat-square)](https://github.com/navidrome/navidrome/releases)
[![Build](https://img.shields.io/github/actions/workflow/status/navidrome/navidrome/pipeline.yml?branch=master&logo=github&style=flat-square)](https://nightly.link/navidrome/navidrome/workflows/pipeline/master) [![Build](https://img.shields.io/github/actions/workflow/status/navidrome/navidrome/pipeline.yml?branch=master&logo=github&style=flat-square)](https://nightly.link/navidrome/navidrome/workflows/pipeline/master)
[![Downloads](https://img.shields.io/github/downloads/navidrome/navidrome/total?logo=github&style=flat-square)](https://github.com/navidrome/navidrome/releases/latest) [![Downloads](https://img.shields.io/github/downloads/navidrome/navidrome/total?logo=github&style=flat-square)](https://github.com/navidrome/navidrome/releases/latest)
[![Docker Pulls](https://img.shields.io/docker/pulls/deluan/navidrome?logo=docker&label=pulls&style=flat-square)](https://hub.docker.com/r/deluan/navidrome) [![Docker Pulls](https://img.shields.io/endpoint?url=https%3A%2F%2Fwww.navidrome.org%2Fbadges%2Fcontainer-downloads.json&logo=docker&label=pulls&style=flat-square)](https://hub.docker.com/r/navidrome/navidrome)
[![Dev Chat](https://img.shields.io/discord/671335427726114836?logo=discord&label=discord&style=flat-square)](https://discord.gg/xh7j7yF) [![Dev Chat](https://img.shields.io/discord/671335427726114836?logo=discord&label=discord&style=flat-square)](https://discord.gg/xh7j7yF)
[![Subreddit](https://img.shields.io/reddit/subreddit-subscribers/navidrome?logo=reddit&label=/r/navidrome&style=flat-square)](https://www.reddit.com/r/navidrome/) [![Subreddit](https://img.shields.io/reddit/subreddit-subscribers/navidrome?logo=reddit&label=/r/navidrome&style=flat-square)](https://www.reddit.com/r/navidrome/)
[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-v2.0-ff69b4.svg?style=flat-square)](CODE_OF_CONDUCT.md) [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-v2.0-ff69b4.svg?style=flat-square)](CODE_OF_CONDUCT.md)
@ -21,9 +21,11 @@ the `master` branch in order to get a stable set of binaries.
## [Check out our Live Demo!](https://www.navidrome.org/demo/) ## [Check out our Live Demo!](https://www.navidrome.org/demo/)
__Any feedback is welcome!__ If you need/want a new feature, find a bug or think of any way to improve Navidrome, __Any feedback is welcome!__ If you find a bug, please file a [GitHub issue](https://github.com/navidrome/navidrome/issues/new/choose).
please file a [GitHub issue](https://github.com/navidrome/navidrome/issues) or join the discussion in our If you need/want a new feature or think of any way to improve Navidrome, please share it in
[Subreddit](https://www.reddit.com/r/navidrome/). If you want to contribute to the project in any other way [Discussions](https://github.com/navidrome/navidrome/discussions/categories/ideas) or join the discussion in our
[Subreddit](https://www.reddit.com/r/navidrome/). Before contributing code, please read the
[Contribution Guide](CONTRIBUTING.md). If you want to contribute to the project in any other way
([ui/backend dev](https://www.navidrome.org/docs/developers/), ([ui/backend dev](https://www.navidrome.org/docs/developers/),
[translations](https://www.navidrome.org/docs/developers/translations/), [translations](https://www.navidrome.org/docs/developers/translations/),
[themes](https://www.navidrome.org/docs/developers/creating-themes)), please join the chat in our [themes](https://www.navidrome.org/docs/developers/creating-themes)), please join the chat in our
@ -35,11 +37,18 @@ See instructions on the [project's website](https://www.navidrome.org/docs/insta
## Cloud Hosting ## Cloud Hosting
[PikaPods](https://www.pikapods.com) has partnered with us to offer you an Several cloud hosting providers partner with us to offer [officially supported, cloud-hosted solutions](https://www.navidrome.org/docs/installation/managed). If you sign up with any of these providers, a share of the revenue funds the development of Navidrome at no additional cost for you.
[officially supported, cloud-hosted solution](https://www.navidrome.org/docs/installation/managed/#pikapods).
A share of the revenue helps fund the development of Navidrome at no additional cost for you. <a href="https://www.pikapods.com/pods?run=navidrome"><img src="resources/hosting/pikapods.svg" alt="Run on PikaPods" width="200" height="40"></a>
<br>
<a href="https://zenith.hosting/host/navidrome?ref=navidrome"><img src="resources/hosting/zenith.svg" alt="Deploy with Zenith" width="200" height="40"></a>
<br>
<a href="https://store.elfhosted.com/product/navidrome/"><img src="resources/hosting/elfhosted.svg" alt="Deploy on ElfHosted" width="200" height="40"></a>
[![PikaPods](https://www.pikapods.com/static/run-button.svg)](https://www.pikapods.com/pods?run=navidrome)
## Features ## Features

View file

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

View file

@ -20,9 +20,9 @@ var _ = Describe("JWT Authentication", func() {
var ctx context.Context var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context()
httpClient = &fakeHttpClient{} httpClient = &fakeHttpClient{}
client = newClient(httpClient) client = newClient(httpClient)
ctx = context.Background()
}) })
Describe("getJWT", func() { Describe("getJWT", func() {
@ -30,32 +30,32 @@ var _ = Describe("JWT Authentication", func() {
It("successfully fetches and caches a JWT token", func() { It("successfully fetches and caches a JWT token", func() {
testJWT := createTestJWT(5 * time.Minute) testJWT := createTestJWT(5 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
}) })
token, err := client.getJWT(ctx) token, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token).To(Equal(testJWT)) Expect(token).To(Equal(testJWT))
}) })
It("returns the cached token on subsequent calls", func() { It("returns the cached token on subsequent calls", func() {
testJWT := createTestJWT(5 * time.Minute) testJWT := createTestJWT(5 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
}) })
// First call should fetch from API // First call should fetch from API
token1, err := client.getJWT(ctx) token1, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token1).To(Equal(testJWT)) Expect(token1).To(Equal(testJWT))
Expect(httpClient.lastRequest.URL.Path).To(Equal("/login/anonymous")) Expect(httpClient.lastRequest.URL.Path).To(Equal("/login/anonymous"))
// Second call should return cached token without hitting API // Second call should return cached token without hitting API
httpClient.lastRequest = nil // Clear last request to verify no new request is made httpClient.lastRequest = nil // Clear last request to verify no new request is made
token2, err := client.getJWT(ctx) token2, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token2).To(Equal(testJWT)) Expect(token2).To(Equal(testJWT))
Expect(httpClient.lastRequest).To(BeNil()) // No new request made Expect(httpClient.lastRequest).To(BeNil()) // No new request made
}) })
@ -65,17 +65,17 @@ var _ = Describe("JWT Authentication", func() {
testToken, err := jwt.NewBuilder(). testToken, err := jwt.NewBuilder().
Expiration(expectedExpiration). Expiration(expectedExpiration).
Build() Build()
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature()) 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{ 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)))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))),
}) })
token, err := client.getJWT(ctx) token, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token).ToNot(BeEmpty()) Expect(token).ToNot(BeEmpty())
// Verify the token is cached until close to expiration // Verify the token is cached until close to expiration
@ -90,7 +90,7 @@ var _ = Describe("JWT Authentication", func() {
// Create a token that expires in 30 seconds (less than 1-minute buffer) // Create a token that expires in 30 seconds (less than 1-minute buffer)
testJWT := createTestJWT(30 * time.Second) testJWT := createTestJWT(30 * time.Second)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
}) })
@ -103,7 +103,7 @@ var _ = Describe("JWT Authentication", func() {
// Create a token that expired 1 minute ago // Create a token that expired 1 minute ago
testJWT := createTestJWT(-1 * time.Minute) testJWT := createTestJWT(-1 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
}) })
@ -116,12 +116,12 @@ var _ = Describe("JWT Authentication", func() {
// Create a token that expires in 2 minutes (just over the 1-minute buffer) // Create a token that expires in 2 minutes (just over the 1-minute buffer)
testJWT := createTestJWT(2 * time.Minute) testJWT := createTestJWT(2 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
}) })
token, err := client.getJWT(ctx) token, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token).ToNot(BeEmpty()) Expect(token).ToNot(BeEmpty())
}) })
}) })
@ -129,7 +129,7 @@ var _ = Describe("JWT Authentication", func() {
Context("with invalid responses", func() { Context("with invalid responses", func() {
It("handles HTTP error responses", func() { It("handles HTTP error responses", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 500, StatusCode: http.StatusInternalServerError,
Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)),
}) })
@ -140,7 +140,7 @@ var _ = Describe("JWT Authentication", func() {
It("handles malformed JSON responses", func() { It("handles malformed JSON responses", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{invalid json}`)), Body: io.NopCloser(bytes.NewBufferString(`{invalid json}`)),
}) })
@ -151,7 +151,7 @@ var _ = Describe("JWT Authentication", func() {
It("handles responses with empty JWT field", func() { It("handles responses with empty JWT field", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"jwt":""}`)), Body: io.NopCloser(bytes.NewBufferString(`{"jwt":""}`)),
}) })
@ -162,7 +162,7 @@ var _ = Describe("JWT Authentication", func() {
It("handles invalid JWT tokens", func() { It("handles invalid JWT tokens", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"jwt":"not-a-valid-jwt"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"jwt":"not-a-valid-jwt"}`)),
}) })
@ -176,17 +176,17 @@ var _ = Describe("JWT Authentication", func() {
testToken, err := jwt.NewBuilder(). testToken, err := jwt.NewBuilder().
Claim("custom", "value"). Claim("custom", "value").
Build() Build()
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
// Verify token has no expiration // Verify token has no expiration
_, hasExp := testToken.Expiration() _, hasExp := testToken.Expiration()
Expect(hasExp).To(BeFalse()) Expect(hasExp).To(BeFalse())
testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature()) testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ 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)))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))),
}) })
@ -201,12 +201,12 @@ var _ = Describe("JWT Authentication", func() {
// First token expires in 5 minutes // First token expires in 5 minutes
firstJWT := createTestJWT(5 * time.Minute) firstJWT := createTestJWT(5 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, firstJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, firstJWT))),
}) })
token1, err := client.getJWT(ctx) token1, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token1).To(Equal(firstJWT)) Expect(token1).To(Equal(firstJWT))
// Manually expire the cached token // Manually expire the cached token
@ -215,12 +215,12 @@ var _ = Describe("JWT Authentication", func() {
// Second token with different expiration (10 minutes) // Second token with different expiration (10 minutes)
secondJWT := createTestJWT(10 * time.Minute) secondJWT := createTestJWT(10 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, secondJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, secondJWT))),
}) })
token2, err := client.getJWT(ctx) token2, err := client.getJWT(ctx)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(token2).To(Equal(secondJWT)) Expect(token2).To(Equal(secondJWT))
Expect(token2).ToNot(Equal(token1)) Expect(token2).ToNot(Equal(token1))
}) })
@ -280,15 +280,12 @@ var _ = Describe("JWT Authentication", func() {
// createTestJWT creates a valid JWT token for testing purposes // createTestJWT creates a valid JWT token for testing purposes
func createTestJWT(expiresIn time.Duration) string { func createTestJWT(expiresIn time.Duration) string {
GinkgoHelper()
token, err := jwt.NewBuilder(). token, err := jwt.NewBuilder().
Expiration(time.Now().Add(expiresIn)). Expiration(time.Now().Add(expiresIn)).
Build() Build()
if err != nil { Expect(err).ToNot(HaveOccurred())
panic(fmt.Sprintf("failed to create test JWT: %v", err))
}
signed, err := jwt.Sign(token, jwt.WithInsecureNoSignature()) signed, err := jwt.Sign(token, jwt.WithInsecureNoSignature())
if err != nil { Expect(err).ToNot(HaveOccurred())
panic(fmt.Sprintf("failed to sign test JWT: %v", err))
}
return string(signed) return string(signed)
} }

View file

@ -26,11 +26,11 @@ var _ = Describe("client", func() {
Describe("ArtistImages", func() { Describe("ArtistImages", func() {
It("returns artist images from a successful request", func() { It("returns artist images from a successful request", func() {
f, err := os.Open("tests/fixtures/deezer.search.artist.json") f, err := os.Open("tests/fixtures/deezer.search.artist.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: 200}) httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: http.StatusOK})
artists, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20) artists, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(artists).To(HaveLen(17)) Expect(artists).To(HaveLen(17))
Expect(artists[0].Name).To(Equal("Michael Jackson")) Expect(artists[0].Name).To(Equal("Michael Jackson"))
Expect(artists[0].PictureXl).To(Equal("https://cdn-images.dzcdn.net/images/artist/97fae13b2b30e4aec2e8c9e0c7839d92/1000x1000-000000-80-0-0.jpg")) Expect(artists[0].PictureXl).To(Equal("https://cdn-images.dzcdn.net/images/artist/97fae13b2b30e4aec2e8c9e0c7839d92/1000x1000-000000-80-0-0.jpg"))
@ -38,7 +38,7 @@ var _ = Describe("client", func() {
It("fails if artist was not found", func() { It("fails if artist was not found", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)), Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
}) })
@ -49,7 +49,7 @@ var _ = Describe("client", func() {
// Deezer answers 200 with no rate-limit headers when throttling, so this body is the only signal. // Deezer answers 200 with no rate-limit headers when throttling, so this body is the only signal.
It("reports an exhausted quota as a retryable error, not as a missing artist", func() { It("reports an exhausted quota as a retryable error, not as a missing artist", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString( Body: io.NopCloser(bytes.NewBufferString(
`{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)), `{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)),
}) })
@ -64,7 +64,7 @@ var _ = Describe("client", func() {
It("reports a non-quota body error as a plain error", func() { It("reports a non-quota body error as a plain error", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString( Body: io.NopCloser(bytes.NewBufferString(
`{"error":{"type":"Exception","message":"Invalid query","code":100}}`)), `{"error":{"type":"Exception","message":"Invalid query","code":100}}`)),
}) })
@ -80,11 +80,11 @@ var _ = Describe("client", func() {
Describe("TopTracks", func() { Describe("TopTracks", func() {
It("returns top tracks with artist and album info from a successful request", func() { It("returns top tracks with artist and album info from a successful request", func() {
f, err := os.Open("tests/fixtures/deezer.artist.top.json") f, err := os.Open("tests/fixtures/deezer.artist.top.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: 200}) httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: http.StatusOK})
tracks, err := client.getTopTracks(GinkgoT().Context(), 27, 5) tracks, err := client.getTopTracks(GinkgoT().Context(), 27, 5)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(tracks).To(HaveLen(5)) Expect(tracks).To(HaveLen(5))
// Verify first track has all expected fields // Verify first track has all expected fields
@ -104,18 +104,18 @@ var _ = Describe("client", func() {
// Mock the JWT token endpoint with a valid JWT that expires in 5 minutes // Mock the JWT token endpoint with a valid JWT that expires in 5 minutes
testJWT := createTestJWT(5 * time.Minute) testJWT := createTestJWT(5 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))),
}) })
}) })
It("returns artist bio from a successful request", func() { It("returns artist bio from a successful request", func() {
f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json") f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200}) httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
bio, err := client.getArtistBio(GinkgoT().Context(), 27, "en") 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).To(ContainSubstring("Schoolmates Thomas and Guy-Manuel"))
Expect(bio).ToNot(ContainSubstring("<p>")) Expect(bio).ToNot(ContainSubstring("<p>"))
Expect(bio).ToNot(ContainSubstring("</p>")) Expect(bio).ToNot(ContainSubstring("</p>"))
@ -123,21 +123,21 @@ var _ = Describe("client", func() {
It("uses the provided language", func() { It("uses the provided language", func() {
f, err := os.Open("tests/fixtures/deezer.artist.bio.fr.json") f, err := os.Open("tests/fixtures/deezer.artist.bio.fr.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200}) httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
_, err = client.getArtistBio(GinkgoT().Context(), 27, "fr") _, 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")) Expect(httpClient.lastRequest.Header.Get("Accept-Language")).To(Equal("fr"))
}) })
It("includes the JWT token in the request", func() { It("includes the JWT token in the request", func() {
f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json") f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200}) httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
_, err = client.getArtistBio(GinkgoT().Context(), 27, "en") _, 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 // Verify that the Authorization header has the Bearer token format
authHeader := httpClient.lastRequest.Header.Get("Authorization") authHeader := httpClient.lastRequest.Header.Get("Authorization")
Expect(authHeader).To(HavePrefix("Bearer ")) Expect(authHeader).To(HavePrefix("Bearer "))
@ -163,7 +163,7 @@ var _ = Describe("client", func() {
] ]
}` }`
httpClient.mock("https://pipe.deezer.com/api", http.Response{ httpClient.mock("https://pipe.deezer.com/api", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(errorResponse)), Body: io.NopCloser(bytes.NewBufferString(errorResponse)),
}) })
@ -185,7 +185,7 @@ var _ = Describe("client", func() {
} }
}` }`
httpClient.mock("https://pipe.deezer.com/api", http.Response{ httpClient.mock("https://pipe.deezer.com/api", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(emptyBioResponse)), Body: io.NopCloser(bytes.NewBufferString(emptyBioResponse)),
}) })
@ -195,7 +195,7 @@ var _ = Describe("client", func() {
It("handles JWT token fetch failure", func() { It("handles JWT token fetch failure", func() {
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 500, StatusCode: http.StatusInternalServerError,
Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)),
}) })
@ -208,7 +208,7 @@ var _ = Describe("client", func() {
// Create a JWT that expires in 30 seconds (less than the 1-minute buffer) // Create a JWT that expires in 30 seconds (less than the 1-minute buffer)
expiredJWT := createTestJWT(30 * time.Second) expiredJWT := createTestJWT(30 * time.Second)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, expiredJWT))), 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 { if resp, ok := c.responses[u.String()]; ok {
return resp, nil return resp, nil
} }
panic("URL not mocked: " + u.String()) Fail("URL not mocked: " + u.String())
return nil, nil
} }

View file

@ -34,7 +34,7 @@ type deezerAgent struct {
func deezerConstructor(dataStore model.DataStore) agents.Interface { func deezerConstructor(dataStore model.DataStore) agents.Interface {
agent := &deezerAgent{ agent := &deezerAgent{
dataStore: dataStore, dataStore: dataStore,
languages: conf.Server.Deezer.Languages, languages: conf.Server().Deezer.Languages,
} }
httpClient := httpclient.New(consts.DefaultHttpClientTimeOut) httpClient := httpclient.New(consts.DefaultHttpClientTimeOut)
cachedHttpClient := cache.NewHTTPClient(httpClient, consts.DefaultHttpClientTimeOut) cachedHttpClient := cache.NewHTTPClient(httpClient, consts.DefaultHttpClientTimeOut)
@ -192,7 +192,7 @@ func (s *deezerAgent) GetArtistBiography(ctx context.Context, _, name, _ string)
func init() { func init() {
conf.AddHook(func() { conf.AddHook(func() {
if conf.Server.Deezer.Enabled { if conf.Server().Deezer.Enabled {
agents.Register(deezerAgentName, deezerConstructor) agents.Register(deezerAgentName, deezerConstructor)
} }
}) })

View file

@ -3,6 +3,7 @@ package deezer
import ( import (
"testing" "testing"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
@ -15,3 +16,5 @@ func TestDeezer(t *testing.T) {
RegisterFailHandler(Fail) RegisterFailHandler(Fail)
RunSpecs(t, "Deezer Test Suite") RunSpecs(t, "Deezer Test Suite")
} }
var _ = configtest.RestoreAfterEachSpec()

View file

@ -11,9 +11,8 @@ import (
"time" "time"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/model"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
) )
@ -22,15 +21,14 @@ var _ = Describe("deezerAgent", func() {
var ctx context.Context var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
ctx = context.Background() ctx = GinkgoT().Context()
DeferCleanup(configtest.SetupConfig()) conf.Update(func(c *conf.Options) { c.Deezer.Enabled = true })
conf.Server.Deezer.Enabled = true
}) })
Describe("deezerConstructor", func() { Describe("deezerConstructor", func() {
It("uses configured languages", func() { It("uses configured languages", func() {
conf.Server.Deezer.Languages = []string{"pt", "en"} 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"})) Expect(agent.languages).To(Equal([]string{"pt", "en"}))
}) })
}) })
@ -42,7 +40,6 @@ var _ = Describe("deezerAgent", func() {
BeforeEach(func() { BeforeEach(func() {
httpClient = &fakeHttpClient{} httpClient = &fakeHttpClient{}
agent = &deezerAgent{ agent = &deezerAgent{
dataStore: &tests.MockDataStore{},
client: newClient(httpClient), client: newClient(httpClient),
} }
}) })
@ -50,7 +47,7 @@ var _ = Describe("deezerAgent", func() {
It("picks the exact-name match with the most fans when several share the name", func() { It("picks the exact-name match with the most fans when several share the name", func() {
// Deezer RANKING order returns a low-popularity homonym first (see issue #5802) // Deezer RANKING order returns a low-popularity homonym first (see issue #5802)
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[ Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":61045802,"name":"Queen","nb_fan":75}, {"id":61045802,"name":"Queen","nb_fan":75},
{"id":141954732,"name":"Queen","nb_fan":397}, {"id":141954732,"name":"Queen","nb_fan":397},
@ -68,7 +65,7 @@ var _ = Describe("deezerAgent", func() {
It("matches the name case-insensitively", func() { It("matches the name case-insensitively", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[ Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":1,"name":"QUEEN","nb_fan":10}, {"id":1,"name":"QUEEN","nb_fan":10},
{"id":2,"name":"queen","nb_fan":20} {"id":2,"name":"queen","nb_fan":20}
@ -85,7 +82,7 @@ var _ = Describe("deezerAgent", func() {
// lookup reaching that here would record a permanent absence. // lookup reaching that here would record a permanent absence.
It("surfaces an exhausted quota instead of reporting the artist as not found", func() { It("surfaces an exhausted quota instead of reporting the artist as not found", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString( Body: io.NopCloser(bytes.NewBufferString(
`{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)), `{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)),
}) })
@ -99,7 +96,7 @@ var _ = Describe("deezerAgent", func() {
It("returns ErrNotFound when no result matches the name exactly", func() { It("returns ErrNotFound when no result matches the name exactly", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[ Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":1,"name":"Queens of the Stone Age","nb_fan":100} {"id":1,"name":"Queens of the Stone Age","nb_fan":100}
],"total":1}`)), ],"total":1}`)),
@ -118,14 +115,13 @@ var _ = Describe("deezerAgent", func() {
BeforeEach(func() { BeforeEach(func() {
httpClient = &fakeHttpClient{} httpClient = &fakeHttpClient{}
agent = &deezerAgent{ agent = &deezerAgent{
dataStore: &tests.MockDataStore{},
client: newClient(httpClient), client: newClient(httpClient),
} }
}) })
It("returns the real images when the artist has a picture", func() { It("returns the real images when the artist has a picture", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[ Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":412,"name":"Queen","nb_fan":12744378, {"id":412,"name":"Queen","nb_fan":12744378,
"picture_xl":"https://cdn-images.dzcdn.net/images/artist/abc/1000x1000-000000-80-0-0.jpg", "picture_xl":"https://cdn-images.dzcdn.net/images/artist/abc/1000x1000-000000-80-0-0.jpg",
@ -142,7 +138,7 @@ var _ = Describe("deezerAgent", func() {
It("returns ErrNotFound when the artist only has empty-id placeholder pictures", func() { It("returns ErrNotFound when the artist only has empty-id placeholder pictures", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{ httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[ Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":412,"name":"Queen","nb_fan":12744378, {"id":412,"name":"Queen","nb_fan":12744378,
"picture_xl":"https://cdn-images.dzcdn.net/images/artist//1000x1000-000000-80-0-0.jpg", "picture_xl":"https://cdn-images.dzcdn.net/images/artist//1000x1000-000000-80-0-0.jpg",
@ -168,20 +164,19 @@ var _ = Describe("deezerAgent", func() {
// Mock search artist (returns Michael Jackson) // Mock search artist (returns Michael Jackson)
fSearch, _ := os.Open("tests/fixtures/deezer.search.artist.json") fSearch, _ := os.Open("tests/fixtures/deezer.search.artist.json")
httpClient.searchResponse = &http.Response{Body: fSearch, StatusCode: 200} httpClient.searchResponse = &http.Response{Body: fSearch, StatusCode: http.StatusOK}
// Mock JWT token // Mock JWT token
testJWT := createTestJWT(5 * time.Minute) testJWT := createTestJWT(5 * time.Minute)
httpClient.jwtResponse = &http.Response{ httpClient.jwtResponse = &http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))), Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))),
} }
}) })
setupAgent := func(languages []string) { setupAgent := func(languages []string) {
conf.Server.Deezer.Languages = languages conf.Update(func(c *conf.Options) { c.Deezer.Languages = languages })
agent = &deezerAgent{ agent = &deezerAgent{
dataStore: &tests.MockDataStore{},
client: newClient(httpClient), client: newClient(httpClient),
languages: languages, languages: languages,
} }
@ -192,7 +187,7 @@ var _ = Describe("deezerAgent", func() {
// French biography available // French biography available
fFr, _ := os.Open("tests/fixtures/deezer.artist.bio.fr.json") fFr, _ := os.Open("tests/fixtures/deezer.artist.bio.fr.json")
httpClient.bioResponses["fr"] = &http.Response{Body: fFr, StatusCode: 200} httpClient.bioResponses["fr"] = &http.Response{Body: fFr, StatusCode: http.StatusOK}
bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "") bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
@ -207,10 +202,10 @@ var _ = Describe("deezerAgent", func() {
// Japanese returns empty biography // Japanese returns empty biography
fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json") fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: 200} httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: http.StatusOK}
// English returns full biography // English returns full biography
fEn, _ := os.Open("tests/fixtures/deezer.artist.bio.en.json") fEn, _ := os.Open("tests/fixtures/deezer.artist.bio.en.json")
httpClient.bioResponses["en"] = &http.Response{Body: fEn, StatusCode: 200} httpClient.bioResponses["en"] = &http.Response{Body: fEn, StatusCode: http.StatusOK}
bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "") bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
@ -226,9 +221,9 @@ var _ = Describe("deezerAgent", func() {
// Both languages return empty biography // Both languages return empty biography
fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json") fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: 200} httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: http.StatusOK}
fXx, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json") fXx, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
httpClient.bioResponses["xx"] = &http.Response{Body: fXx, StatusCode: 200} httpClient.bioResponses["xx"] = &http.Response{Body: fXx, StatusCode: http.StatusOK}
_, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "") _, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
@ -261,7 +256,7 @@ func (c *langAwareHttpClient) Do(req *http.Request) (*http.Response, error) {
return c.searchResponse, nil return c.searchResponse, nil
} }
return &http.Response{ return &http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)), Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
}, nil }, nil
} }
@ -272,7 +267,7 @@ func (c *langAwareHttpClient) Do(req *http.Request) (*http.Response, error) {
return c.jwtResponse, nil return c.jwtResponse, nil
} }
return &http.Response{ return &http.Response{
StatusCode: 500, StatusCode: http.StatusInternalServerError,
Body: io.NopCloser(bytes.NewBufferString(`{"error":"no mock"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":"no mock"}`)),
}, nil }, nil
} }
@ -287,10 +282,11 @@ func (c *langAwareHttpClient) Do(req *http.Request) (*http.Response, error) {
} }
// Return empty bio by default // Return empty bio by default
return &http.Response{ return &http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":{"artist":{"bio":{"full":""}}}}`)), Body: io.NopCloser(bytes.NewBufferString(`{"data":{"artist":{"bio":{"full":""}}}}`)),
}, nil }, 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() { It("parses the artist search result correctly ", func() {
var resp SearchArtistResults var resp SearchArtistResults
body, err := os.ReadFile("tests/fixtures/deezer.search.artist.json") body, err := os.ReadFile("tests/fixtures/deezer.search.artist.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
err = json.Unmarshal(body, &resp) err = json.Unmarshal(body, &resp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(resp.Data).To(HaveLen(17)) Expect(resp.Data).To(HaveLen(17))
michael := resp.Data[0] michael := resp.Data[0]
@ -29,7 +29,7 @@ var _ = Describe("Responses", func() {
var errorResp errorResponse var errorResp errorResponse
body := []byte(`{"error":{"type":"MissingParameterException","message":"Missing parameters: q","code":501}}`) body := []byte(`{"error":{"type":"MissingParameterException","message":"Missing parameters: q","code":501}}`)
err := json.Unmarshal(body, &errorResp) err := json.Unmarshal(body, &errorResp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(errorResp.Error.Code).To(Equal(501)) Expect(errorResp.Error.Code).To(Equal(501))
Expect(errorResp.Error.Message).To(Equal("Missing parameters: q")) Expect(errorResp.Error.Message).To(Equal("Missing parameters: q"))
@ -40,9 +40,9 @@ var _ = Describe("Responses", func() {
It("parses the related artists response correctly", func() { It("parses the related artists response correctly", func() {
var resp RelatedArtists var resp RelatedArtists
body, err := os.ReadFile("tests/fixtures/deezer.artist.related.json") body, err := os.ReadFile("tests/fixtures/deezer.artist.related.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
err = json.Unmarshal(body, &resp) err = json.Unmarshal(body, &resp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(resp.Data).To(HaveLen(20)) Expect(resp.Data).To(HaveLen(20))
justice := resp.Data[0] justice := resp.Data[0]
@ -55,9 +55,9 @@ var _ = Describe("Responses", func() {
It("parses the top tracks response correctly", func() { It("parses the top tracks response correctly", func() {
var resp TopTracks var resp TopTracks
body, err := os.ReadFile("tests/fixtures/deezer.artist.top.json") body, err := os.ReadFile("tests/fixtures/deezer.artist.top.json")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
err = json.Unmarshal(body, &resp) err = json.Unmarshal(body, &resp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(resp.Data).To(HaveLen(5)) Expect(resp.Data).To(HaveLen(5))
track := resp.Data[0] track := resp.Data[0]

View file

@ -20,13 +20,13 @@ func (t testFileInfo) BirthTime() time.Time {
if ts := times.Get(t.FileInfo); ts.HasBirthTime() { if ts := times.Get(t.FileInfo); ts.HasBirthTime() {
return ts.BirthTime() return ts.BirthTime()
} }
return t.FileInfo.ModTime() return t.ModTime()
} }
var _ = Describe("Extractor", func() { var _ = Describe("Extractor", func() {
toP := func(name, sortName, mbid string) model.Participant { toP := func(name, sortName, mbid string) model.Participant {
return model.Participant{ return model.Participant{
Artist: model.Artist{Name: name, SortArtistName: sortName, MbzArtistID: mbid}, Name: name, SortArtistName: sortName, MbzArtistID: mbid,
} }
} }
@ -90,7 +90,7 @@ var _ = Describe("Extractor", func() {
info.FileInfo = testFileInfo{FileInfo: fileInfo} info.FileInfo = testFileInfo{FileInfo: fileInfo}
metadata := metadata.New(path, info) metadata := metadata.New(path, info)
return new(metadata.ToMediaFile(1, "folderID")) return new(metadata.ToMediaFile(model.Library{ID: 1}, "folderID"))
} }
BeforeEach(func() { BeforeEach(func() {
@ -156,7 +156,7 @@ var _ = Describe("Extractor", func() {
mf := parseTestFile("tests/fixtures/" + file) mf := parseTestFile("tests/fixtures/" + file)
lyrics, err := mf.StructuredLyrics() lyrics, err := mf.StructuredLyrics()
Expect(err).To(Not(HaveOccurred())) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(2)) Expect(lyrics).To(HaveLen(2))
unspec := makeLyrics("xxx", "unspecified") unspec := makeLyrics("xxx", "unspecified")
@ -250,7 +250,7 @@ var _ = Describe("Extractor", func() {
// WMA has no Arranger role // WMA has no Arranger role
if role == model.RoleArranger { if role == model.RoleArranger {
Expect(actual).To(HaveLen(0)) Expect(actual).To(BeEmpty())
continue 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 // https://picard-docs.musicbrainz.org/downloads/MusicBrainz_Picard_Tag_Map.html
var tiplMapping = map[string]string{ var tiplMapping = map[string]string{
"arranger": "arranger", "arranger": "arranger",

View file

@ -78,7 +78,7 @@ var _ = Describe("Extractor", func() {
// Test OGG // Test OGG
m = mds["tests/fixtures/test.ogg"] m = mds["tests/fixtures/test.ogg"]
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(m.Tags).To(HaveKeyWithValue("fbpm", []string{"141.7"})) Expect(m.Tags).To(HaveKeyWithValue("fbpm", []string{"141.7"}))
// TagLib 1.12 returns 18, previous versions return 39. // TagLib 1.12 returns 18, previous versions return 39.

View file

@ -49,15 +49,16 @@ type lastfmAgent struct {
getInfoMutex sync.Mutex 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 { func lastFMConstructor(ds model.DataStore) *lastfmAgent {
if !conf.Server.LastFM.Enabled || conf.Server.LastFM.ApiKey == "" || conf.Server.LastFM.Secret == "" {
return nil
}
l := &lastfmAgent{ l := &lastfmAgent{
ds: ds, ds: ds,
languages: conf.Server.LastFM.Languages, languages: conf.Server().LastFM.Languages,
apiKey: conf.Server.LastFM.ApiKey, apiKey: conf.Server().LastFM.ApiKey,
secret: conf.Server.LastFM.Secret, secret: conf.Server().LastFM.Secret,
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty}, sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
} }
hc := httpclient.New(consts.DefaultHttpClientTimeOut) hc := httpclient.New(consts.DefaultHttpClientTimeOut)
@ -242,8 +243,8 @@ var (
artistOpenGraphQuery = cascadia.MustCompile(`html > head > meta[property="og:image"]`) artistOpenGraphQuery = cascadia.MustCompile(`html > head > meta[property="og:image"]`)
artistIgnoredImage = "2a96cbd8b46e442fc41c2b86b821562f" // Last.fm artist placeholder image name artistIgnoredImage = "2a96cbd8b46e442fc41c2b86b821562f" // Last.fm artist placeholder image name
// Not a RetryLaterError on purpose: parking the agent would also stall its API-backed // errNoArtistPage is not a RetryLaterError on purpose: parking the agent would also stall its
// methods, which the page block does not affect. // API-backed methods, which the page block does not affect.
errNoArtistPage = errors.New("no artist image in Last.fm page") errNoArtistPage = errors.New("no artist image in Last.fm page")
) )
@ -354,7 +355,7 @@ func (l *lastfmAgent) callTrackGetSimilar(ctx context.Context, name, artist stri
} }
func (l *lastfmAgent) getArtistForScrobble(track *model.MediaFile, role model.Role, displayName string) string { func (l *lastfmAgent) getArtistForScrobble(track *model.MediaFile, role model.Role, displayName string) string {
if conf.Server.LastFM.ScrobbleFirstArtistOnly && len(track.Participants[role]) > 0 { if conf.Server().LastFM.ScrobbleFirstArtistOnly && len(track.Participants[role]) > 0 {
return track.Participants[role][0].Name return track.Participants[role][0].Name
} }
return displayName return displayName
@ -376,7 +377,7 @@ func (l *lastfmAgent) NowPlaying(ctx context.Context, userId string, track *mode
albumArtist: l.getArtistForScrobble(track, model.RoleAlbumArtist, track.AlbumArtist), albumArtist: l.getArtistForScrobble(track, model.RoleAlbumArtist, track.AlbumArtist),
}) })
if err != nil { 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 errors.Join(err, scrobbler.ErrUnrecoverable)
} }
return nil return nil
@ -388,10 +389,11 @@ func (l *lastfmAgent) Scrobble(ctx context.Context, userId string, s scrobbler.S
return errors.Join(err, scrobbler.ErrNotAuthorized) 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) log.Debug(ctx, "Skipping Last.fm scrobble for short song", "track", s.Title, "duration", s.Duration)
return nil return nil
} }
err = l.client.scrobble(ctx, sk, ScrobbleInfo{ err = l.client.scrobble(ctx, sk, ScrobbleInfo{
artist: l.getArtistForScrobble(&s.MediaFile, model.RoleArtist, s.Artist), artist: l.getArtistForScrobble(&s.MediaFile, model.RoleArtist, s.Artist),
track: s.Title, track: s.Title,
@ -430,22 +432,16 @@ func (l *lastfmAgent) PlaybackReport(context.Context, scrobbler.PlaybackSession)
func init() { func init() {
conf.AddHook(func() { conf.AddHook(func() {
agents.Register(lastFMAgentName, func(ds model.DataStore) agents.Interface { 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) if !lastFMEnabled() {
// See https://go.dev/doc/faq#nil_error
a := lastFMConstructor(ds)
if a != nil {
return a
}
return nil return nil
}
return lastFMConstructor(ds)
}) })
scrobbler.Register(lastFMAgentName, func(ds model.DataStore) scrobbler.Scrobbler { 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) if !lastFMEnabled() {
// See https://go.dev/doc/faq#nil_error
a := lastFMConstructor(ds)
if a != nil {
return a
}
return nil return nil
}
return lastFMConstructor(ds)
}) })
}) })
} }

View file

@ -12,10 +12,11 @@ import (
"time" "time"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/scrobbler" "github.com/navidrome/navidrome/core/scrobbler"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -30,41 +31,39 @@ var _ = Describe("lastfmAgent", func() {
var ds model.DataStore var ds model.DataStore
var ctx context.Context var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
ds = &tests.MockDataStore{} ctx = GinkgoT().Context()
ctx = context.Background() ds = persistence.New(db.Db())
DeferCleanup(configtest.SetupConfig()) conf.Update(func(c *conf.Options) {
conf.Server.LastFM.Enabled = true c.LastFM.Enabled = true
conf.Server.LastFM.ApiKey = "123" c.LastFM.ApiKey = "123"
conf.Server.LastFM.Secret = "secret" c.LastFM.Secret = "secret"
})
}) })
Describe("lastFMConstructor", func() { Describe("lastFMConstructor", func() {
When("Agent is properly configured", func() { When("Agent is properly configured", func() {
It("uses configured api key and languages", func() { It("uses configured api key and languages", func() {
conf.Server.LastFM.Languages = []string{"pt", "en"} conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"pt", "en"} })
agent := lastFMConstructor(ds) agent := lastFMConstructor(ds)
Expect(agent.apiKey).To(Equal("123")) Expect(agent.apiKey).To(Equal("123"))
Expect(agent.secret).To(Equal("secret")) Expect(agent.secret).To(Equal("secret"))
Expect(agent.languages).To(Equal([]string{"pt", "en"})) Expect(agent.languages).To(Equal([]string{"pt", "en"}))
}) })
}) })
When("Agent is disabled", func() {
It("returns nil", func() {
conf.Server.LastFM.Enabled = false
Expect(lastFMConstructor(ds)).To(BeNil())
})
})
When("ApiKey is empty", func() {
It("returns nil", func() {
conf.Server.LastFM.ApiKey = ""
Expect(lastFMConstructor(ds)).To(BeNil())
})
})
When("Secret is empty", func() {
It("returns nil", func() {
conf.Server.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() { Describe("GetArtistBiography", func() {
@ -79,7 +78,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns the biography", func() { It("returns the biography", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 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(agent.GetArtistBiography(ctx, "123", "U2", "")).To(Equal("U2 é uma das mais importantes bandas de rock de todos os tempos. Formada em 1976 em Dublin, composta por Bono (vocalista e guitarrista), The Edge (guitarrista, pianista e backing vocal), Adam Clayton (baixista), Larry Mullen, Jr. (baterista e percussionista).\n\nDesde a década de 80, U2 é uma das bandas mais populares no mundo. Seus shows são únicos e um verdadeiro festival de efeitos especiais, além de serem um dos que mais arrecadam anualmente."))
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("U2")) Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("U2"))
@ -94,7 +93,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns an error if Last.fm call returns an error", func() { It("returns an error if Last.fm call returns an error", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
_, err := agent.GetArtistBiography(ctx, "123", "U2", "") _, err := agent.GetArtistBiography(ctx, "123", "U2", "")
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -104,7 +103,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() { It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
_, err := agent.GetArtistBiography(ctx, "123", "U2", "") _, err := agent.GetArtistBiography(ctx, "123", "U2", "")
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue()) Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
@ -121,13 +120,13 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns content in first language when available (1 API call)", func() { It("returns content in first language when available (1 API call)", func() {
conf.Server.LastFM.Languages = []string{"pt", "en"} conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"pt", "en"} })
agent = lastFMConstructor(ds) agent = lastFMConstructor(ds)
agent.client = newClient("API_KEY", "SECRET", httpClient) agent.client = newClient("API_KEY", "SECRET", httpClient)
// Portuguese biography available // Portuguese biography available
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
httpClient.responses["pt"] = http.Response{Body: f, StatusCode: 200} httpClient.responses["pt"] = http.Response{Body: f, StatusCode: http.StatusOK}
bio, err := agent.GetArtistBiography(ctx, "123", "U2", "") bio, err := agent.GetArtistBiography(ctx, "123", "U2", "")
@ -138,16 +137,16 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("falls back to second language when first returns empty (2 API calls)", func() { It("falls back to second language when first returns empty (2 API calls)", func() {
conf.Server.LastFM.Languages = []string{"ja", "en"} conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "en"} })
agent = lastFMConstructor(ds) agent = lastFMConstructor(ds)
agent.client = newClient("API_KEY", "SECRET", httpClient) agent.client = newClient("API_KEY", "SECRET", httpClient)
// Japanese returns empty/ignored biography (actual Last.fm response with just "Read more" link) // Japanese returns empty/ignored biography (actual Last.fm response with just "Read more" link)
fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json") fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200} httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: http.StatusOK}
// English returns full biography // English returns full biography
fEn, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.en.json") fEn, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.en.json")
httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: 200} httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: http.StatusOK}
bio, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "") bio, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "")
@ -159,16 +158,16 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns ErrNotFound when all languages return empty", func() { It("returns ErrNotFound when all languages return empty", func() {
conf.Server.LastFM.Languages = []string{"ja", "xx"} conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "xx"} })
agent = lastFMConstructor(ds) agent = lastFMConstructor(ds)
agent.client = newClient("API_KEY", "SECRET", httpClient) agent.client = newClient("API_KEY", "SECRET", httpClient)
// Both languages return empty/ignored biography (using actual Last.fm response format) // Both languages return empty/ignored biography (using actual Last.fm response format)
fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json") fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200} httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: http.StatusOK}
// Second language also returns empty // Second language also returns empty
fXx, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json") fXx, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: 200} httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: http.StatusOK}
_, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "") _, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "")
@ -186,16 +185,16 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("falls back to second language when first returns empty description (2 API calls)", func() { It("falls back to second language when first returns empty description (2 API calls)", func() {
conf.Server.LastFM.Languages = []string{"ja", "en"} conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "en"} })
agent = lastFMConstructor(ds) agent = lastFMConstructor(ds)
agent.client = newClient("API_KEY", "SECRET", httpClient) agent.client = newClient("API_KEY", "SECRET", httpClient)
// Japanese returns album without wiki/description (actual Last.fm response) // Japanese returns album without wiki/description (actual Last.fm response)
fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json") fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200} httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: http.StatusOK}
// English returns album with description // English returns album with description
fEn, _ := os.Open("tests/fixtures/lastfm.album.getinfo.en.json") fEn, _ := os.Open("tests/fixtures/lastfm.album.getinfo.en.json")
httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: 200} httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: http.StatusOK}
albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "") albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "")
@ -208,15 +207,15 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns album without description when all languages return empty", func() { It("returns album without description when all languages return empty", func() {
conf.Server.LastFM.Languages = []string{"ja", "xx"} conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "xx"} })
agent = lastFMConstructor(ds) agent = lastFMConstructor(ds)
agent.client = newClient("API_KEY", "SECRET", httpClient) agent.client = newClient("API_KEY", "SECRET", httpClient)
// Both languages return album without description // Both languages return album without description
fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json") fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200} httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: http.StatusOK}
fXx, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json") fXx, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: 200} httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: http.StatusOK}
albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "") albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "")
@ -240,7 +239,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns similar artists", func() { It("returns similar artists", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
Expect(agent.GetSimilarArtists(ctx, "123", "U2", "", 2)).To(Equal([]agents.Artist{ Expect(agent.GetSimilarArtists(ctx, "123", "U2", "", 2)).To(Equal([]agents.Artist{
{Name: "Passengers", MBID: "e110c11f-1c94-4471-a350-c38f46b29389"}, {Name: "Passengers", MBID: "e110c11f-1c94-4471-a350-c38f46b29389"},
{Name: "INXS", MBID: "481bf5f9-2e7c-4c44-b08a-05b32bc7c00d"}, {Name: "INXS", MBID: "481bf5f9-2e7c-4c44-b08a-05b32bc7c00d"},
@ -258,7 +257,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns an error if Last.fm call returns an error", func() { It("returns an error if Last.fm call returns an error", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
_, err := agent.GetSimilarArtists(ctx, "123", "U2", "", 2) _, err := agent.GetSimilarArtists(ctx, "123", "U2", "", 2)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -278,7 +277,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns top songs", func() { It("returns top songs", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json") f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
Expect(agent.GetArtistTopSongs(ctx, "123", "U2", "", 2)).To(Equal([]agents.Song{ Expect(agent.GetArtistTopSongs(ctx, "123", "U2", "", 2)).To(Equal([]agents.Song{
{Name: "Beautiful Day", MBID: "f7f264d0-a89b-4682-9cd7-a4e7c37637af"}, {Name: "Beautiful Day", MBID: "f7f264d0-a89b-4682-9cd7-a4e7c37637af"},
{Name: "With or Without You", MBID: "6b9a509f-6907-4a6e-9345-2f12da09ba4b"}, {Name: "With or Without You", MBID: "6b9a509f-6907-4a6e-9345-2f12da09ba4b"},
@ -296,7 +295,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns an error if Last.fm call returns an error", func() { It("returns an error if Last.fm call returns an error", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
_, err := agent.GetArtistTopSongs(ctx, "123", "U2", "", 2) _, err := agent.GetArtistTopSongs(ctx, "123", "U2", "", 2)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -316,7 +315,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns similar songs", func() { It("returns similar songs", func() {
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json") f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 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{ Expect(agent.GetSimilarSongsByTrack(ctx, "123", "Just Can't Get Enough", "Depeche Mode", "", 5)).To(Equal([]agents.Song{
{Name: "Dreaming of Me", MBID: "027b553e-7c74-3ed4-a95e-1d4fea51f174", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"}}}, {Name: "Dreaming of Me", MBID: "027b553e-7c74-3ed4-a95e-1d4fea51f174", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"}}},
{Name: "Everything Counts", MBID: "5a5a3ca4-bdb8-4641-a674-9b54b9b319a6", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"}}}, {Name: "Everything Counts", MBID: "5a5a3ca4-bdb8-4641-a674-9b54b9b319a6", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"}}},
@ -331,7 +330,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrNotFound when no similar songs found", func() { It("returns ErrNotFound when no similar songs found", func() {
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json") f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := agent.GetSimilarSongsByTrack(ctx, "123", "UnknownTrack", "UnknownArtist", "", 3) _, err := agent.GetSimilarSongsByTrack(ctx, "123", "UnknownTrack", "UnknownArtist", "", 3)
Expect(err).To(MatchError(agents.ErrNotFound)) Expect(err).To(MatchError(agents.ErrNotFound))
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -345,7 +344,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns an error if Last.fm call returns an error", func() { It("returns an error if Last.fm call returns an error", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
_, err := agent.GetSimilarSongsByTrack(ctx, "123", "Believe", "Cher", "", 3) _, err := agent.GetSimilarSongsByTrack(ctx, "123", "Believe", "Cher", "", 3)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -357,7 +356,8 @@ var _ = Describe("lastfmAgent", func() {
var httpClient *tests.FakeHttpClient var httpClient *tests.FakeHttpClient
var track *model.MediaFile var track *model.MediaFile
BeforeEach(func() { 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{} httpClient = &tests.FakeHttpClient{}
client := newClient("API_KEY", "SECRET", httpClient) client := newClient("API_KEY", "SECRET", httpClient)
agent = lastFMConstructor(ds) agent = lastFMConstructor(ds)
@ -373,12 +373,12 @@ var _ = Describe("lastfmAgent", func() {
MbzRecordingID: "mbz-123", MbzRecordingID: "mbz-123",
Participants: map[model.Role]model.ParticipantList{ Participants: map[model.Role]model.ParticipantList{
model.RoleArtist: []model.Participant{ model.RoleArtist: []model.Participant{
{Artist: model.Artist{ID: "ar-1", Name: "First Artist"}}, {ID: "ar-1", Name: "First Artist"},
{Artist: model.Artist{ID: "ar-2", Name: "Second Artist"}}, {ID: "ar-2", Name: "Second Artist"},
}, },
model.RoleAlbumArtist: []model.Participant{ model.RoleAlbumArtist: []model.Participant{
{Artist: model.Artist{ID: "ar-1", Name: "First Album Artist"}}, {ID: "ar-1", Name: "First Album Artist"},
{Artist: model.Artist{ID: "ar-2", Name: "Second Album Artist"}}, {ID: "ar-2", Name: "Second Album Artist"},
}, },
}, },
} }
@ -386,7 +386,7 @@ var _ = Describe("lastfmAgent", func() {
Describe("NowPlaying", func() { Describe("NowPlaying", func() {
It("calls Last.fm with correct params", func() { It("calls Last.fm with correct params", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
err := agent.NowPlaying(ctx, "user-1", track, 0) err := agent.NowPlaying(ctx, "user-1", track, 0)
@ -412,11 +412,11 @@ var _ = Describe("lastfmAgent", func() {
When("ScrobbleFirstArtistOnly is true", func() { When("ScrobbleFirstArtistOnly is true", func() {
BeforeEach(func() { BeforeEach(func() {
conf.Server.LastFM.ScrobbleFirstArtistOnly = true conf.Update(func(c *conf.Options) { c.LastFM.ScrobbleFirstArtistOnly = true })
}) })
It("uses only the first artist", 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) err := agent.NowPlaying(ctx, "user-1", track, 0)
@ -432,7 +432,7 @@ var _ = Describe("lastfmAgent", func() {
Describe("scrobble", func() { Describe("scrobble", func() {
It("calls Last.fm with correct params", func() { It("calls Last.fm with correct params", func() {
ts := time.Now() ts := time.Now()
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 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}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: ts})
@ -454,12 +454,12 @@ var _ = Describe("lastfmAgent", func() {
When("ScrobbleFirstArtistOnly is true", func() { When("ScrobbleFirstArtistOnly is true", func() {
BeforeEach(func() { BeforeEach(func() {
conf.Server.LastFM.ScrobbleFirstArtistOnly = true conf.Update(func(c *conf.Options) { c.LastFM.ScrobbleFirstArtistOnly = true })
}) })
It("uses only the first artist", func() { It("uses only the first artist", func() {
ts := time.Now() ts := time.Now()
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 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}) 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() { It("skips songs at the 30-second minimum", func() {
track.Duration = 29 track.Duration = 30
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: time.Now()}) 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()) 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() { It("returns ErrNotAuthorized if user is not linked", func() {
err := agent.Scrobble(ctx, "user-2", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-2", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
Expect(err).To(MatchError(scrobbler.ErrNotAuthorized)) Expect(err).To(MatchError(scrobbler.ErrNotAuthorized))
@ -489,7 +529,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrRetryLater on error 11", func() { It("returns ErrRetryLater on error 11", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":11,"message":"Service Offline - This service is temporarily offline. Try again later."}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":11,"message":"Service Offline - This service is temporarily offline. Try again later."}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -499,7 +539,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrRetryLater on error 16", func() { It("returns ErrRetryLater on error 16", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":16,"message":"There was a temporary error processing your request. Please try again"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":16,"message":"There was a temporary error processing your request. Please try again"}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -509,7 +549,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() { It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -519,7 +559,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrRetryLater on http errors", func() { It("returns ErrRetryLater on http errors", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`internal server error`)), Body: io.NopCloser(bytes.NewBufferString(`internal server error`)),
StatusCode: 500, StatusCode: http.StatusInternalServerError,
} }
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -529,7 +569,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns ErrUnrecoverable on other errors", func() { It("returns ErrUnrecoverable on other errors", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":8,"message":"Operation failed - Something else went wrong"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":8,"message":"Operation failed - Something else went wrong"}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -550,7 +590,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns the biography", func() { It("returns the biography", func() {
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 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{ Expect(agent.GetAlbumInfo(ctx, "Believe", "Cher", "03c91c40-49a6-44a7-90e7-a700edf97a62")).To(Equal(&agents.AlbumInfo{
Name: "Believe", Name: "Believe",
MBID: "03c91c40-49a6-44a7-90e7-a700edf97a62", MBID: "03c91c40-49a6-44a7-90e7-a700edf97a62",
@ -566,7 +606,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns empty images if no images are available", func() { It("returns empty images if no images are available", func() {
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty_urls.json") f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty_urls.json")
httpClient.Res = http.Response{Body: f, StatusCode: 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{ Expect(agent.GetAlbumInfo(ctx, "The Definitive Less Damage And More Joy", "The Jesus and Mary Chain", "")).To(Equal(&agents.AlbumInfo{
Name: "The Definitive Less Damage And More Joy", Name: "The Definitive Less Damage And More Joy",
URL: "https://www.last.fm/music/The+Jesus+and+Mary+Chain/The+Definitive+Less+Damage+And+More+Joy", URL: "https://www.last.fm/music/The+Jesus+and+Mary+Chain/The+Definitive+Less+Damage+And+More+Joy",
@ -584,7 +624,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns an error if Last.fm call returns an error", func() { It("returns an error if Last.fm call returns an error", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
_, err := agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234") _, err := agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234")
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -592,7 +632,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns an error when Last.fm returns an error 6 (album not found)", func() { It("returns an error when Last.fm returns an error 6 (album not found)", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: http.StatusOK}
_, err := agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234") _, err := agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234")
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
// A definitive not-found must satisfy the sentinel, or the artwork worker retries it. // A definitive not-found must satisfy the sentinel, or the artwork worker retries it.
@ -618,10 +658,10 @@ var _ = Describe("lastfmAgent", func() {
It("returns the artist image from the page", func() { It("returns the artist image from the page", func() {
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
apiClient.Res = http.Response{Body: fApi, StatusCode: 200} apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.html") fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.html")
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200} httpClient.Res = http.Response{Body: fScraper, StatusCode: http.StatusOK}
images, err := agent.GetArtistImages(ctx, "123", "U2", "") images, err := agent.GetArtistImages(ctx, "123", "U2", "")
Expect(err).ToNot(HaveOccurred()) 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() { 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", "") _, err := agent.GetArtistImages(ctx, "123", "Nonexistent Artist", "")
// Not a fault: runs of missing artists must not trip the worker's circuit breaker. // Not a fault: runs of missing artists must not trip the worker's circuit breaker.
Expect(errors.Is(err, agents.ErrNotFound)).To(BeTrue()) Expect(errors.Is(err, agents.ErrNotFound)).To(BeTrue())
@ -638,10 +678,10 @@ var _ = Describe("lastfmAgent", func() {
It("returns empty list if image is the ignored default image", func() { It("returns empty list if image is the ignored default image", func() {
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
apiClient.Res = http.Response{Body: fApi, StatusCode: 200} apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.ignored.html") fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.ignored.html")
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200} httpClient.Res = http.Response{Body: fScraper, StatusCode: http.StatusOK}
images, err := agent.GetArtistImages(ctx, "123", "U2", "") images, err := agent.GetArtistImages(ctx, "123", "U2", "")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -650,10 +690,10 @@ var _ = Describe("lastfmAgent", func() {
It("errors when the page has no meta tags", func() { It("errors when the page has no meta tags", func() {
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
apiClient.Res = http.Response{Body: fApi, StatusCode: 200} apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.no_meta.html") fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.no_meta.html")
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200} httpClient.Res = http.Response{Body: fScraper, StatusCode: http.StatusOK}
_, err := agent.GetArtistImages(ctx, "123", "U2", "") _, err := agent.GetArtistImages(ctx, "123", "U2", "")
Expect(err).To(MatchError(errNoArtistPage)) Expect(err).To(MatchError(errNoArtistPage))
@ -661,10 +701,10 @@ var _ = Describe("lastfmAgent", func() {
It("errors when Last.fm serves a bot challenge page", func() { It("errors when Last.fm serves a bot challenge page", func() {
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
apiClient.Res = http.Response{Body: fApi, StatusCode: 200} apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.challenge.html") fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.challenge.html")
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200} httpClient.Res = http.Response{Body: fScraper, StatusCode: http.StatusOK}
images, err := agent.GetArtistImages(ctx, "123", "U2", "") images, err := agent.GetArtistImages(ctx, "123", "U2", "")
Expect(err).To(MatchError(errNoArtistPage)) 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() { It("does not park the agent: the failure is not a retry-later", func() {
// A RetryLaterError would cool down the agent's API-backed methods too. // A RetryLaterError would cool down the agent's API-backed methods too.
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
apiClient.Res = http.Response{Body: fApi, StatusCode: 200} apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.challenge.html") fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.challenge.html")
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200} httpClient.Res = http.Response{Body: fScraper, StatusCode: http.StatusOK}
_, err := agent.GetArtistImages(ctx, "123", "U2", "") _, err := agent.GetArtistImages(ctx, "123", "U2", "")
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeFalse()) Expect(errors.Is(err, agents.ErrRetryLater)).To(BeFalse())
@ -692,7 +732,7 @@ var _ = Describe("lastfmAgent", func() {
It("returns error if scraper call fails", func() { It("returns error if scraper call fails", func() {
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
apiClient.Res = http.Response{Body: fApi, StatusCode: 200} apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
httpClient.Err = errors.New("scraper error") httpClient.Err = errors.New("scraper error")
_, err := agent.GetArtistImages(ctx, "123", "U2", "") _, 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 default empty response if no specific response is configured
return &http.Response{ return &http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{}`)), Body: io.NopCloser(bytes.NewBufferString(`{}`)),
}, nil }, nil
} }

View file

@ -37,8 +37,8 @@ type Router struct {
func NewRouter(ds model.DataStore) *Router { func NewRouter(ds model.DataStore) *Router {
r := &Router{ r := &Router{
ds: ds, ds: ds,
apiKey: conf.Server.LastFM.ApiKey, apiKey: conf.Server().LastFM.ApiKey,
secret: conf.Server.LastFM.Secret, secret: conf.Server().LastFM.Secret,
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty}, sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
} }
r.Handler = r.routes() r.Handler = r.routes()
@ -122,7 +122,7 @@ func (s *Router) callback(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusBadRequest) 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 return
} }

View file

@ -10,8 +10,10 @@ import (
"github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -19,8 +21,7 @@ import (
var _ = Describe("auth_router", func() { var _ = Describe("auth_router", func() {
var ( var (
ds *tests.MockDataStore ds model.DataStore
userProps *tests.MockedUserPropsRepo
httpClient *tests.FakeHttpClient httpClient *tests.FakeHttpClient
router *Router router *Router
) )
@ -31,10 +32,10 @@ var _ = Describe("auth_router", func() {
) )
BeforeEach(func() { BeforeEach(func() {
userProps = &tests.MockedUserPropsRepo{} ctx := GinkgoT().Context()
ds = &tests.MockDataStore{ ds = persistence.New(db.Db())
MockedProperty: &tests.MockedPropertyRepo{}, for _, id := range []string{victimID, attackerID} {
MockedUserProps: userProps, Expect(ds.User().Put(ctx, &model.User{ID: id, UserName: id})).To(Succeed())
} }
auth.Init(ds) auth.Init(ds)
@ -50,14 +51,14 @@ var _ = Describe("auth_router", func() {
}) })
storedSessionKey := func(userID string) string { storedSessionKey := func(userID string) string {
key, _ := userProps.Get(GinkgoT().Context(), userID, sessionKeyProperty) key, _ := ds.UserProps().Get(GinkgoT().Context(), userID, sessionKeyProperty)
return key return key
} }
stubGetSessionOK := func(sessionKey string) { stubGetSessionOK := func(sessionKey string) {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"session":{"name":"Navidrome","key":"` + sessionKey + `","subscriber":0}}`)), Body: io.NopCloser(bytes.NewBufferString(`{"session":{"name":"Navidrome","key":"` + sessionKey + `","subscriber":0}}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
} }
@ -74,7 +75,7 @@ var _ = Describe("auth_router", func() {
var body map[string]any var body map[string]any
Expect(json.Unmarshal(rec.Body.Bytes(), &body)).To(Succeed()) Expect(json.Unmarshal(rec.Body.Bytes(), &body)).To(Succeed())
Expect(body["apiKey"]).To(Equal("API_KEY")) Expect(body["apiKey"]).To(Equal("API_KEY"))
Expect(body["status"]).To(Equal(false)) Expect(body["status"]).To(BeFalse())
token, ok := body["linkToken"].(string) token, ok := body["linkToken"].(string)
Expect(ok).To(BeTrue()) Expect(ok).To(BeTrue())
Expect(token).ToNot(BeEmpty()) Expect(token).ToNot(BeEmpty())

View file

@ -182,7 +182,14 @@ func (c *client) scrobble(ctx context.Context, sessionKey string, info ScrobbleI
params.Add("album", info.album) params.Add("album", info.album)
params.Add("trackNumber", strconv.Itoa(info.trackNumber)) params.Add("trackNumber", strconv.Itoa(info.trackNumber))
params.Add("mbid", info.mbid) params.Add("mbid", info.mbid)
// 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)) 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("albumArtist", info.albumArtist)
params.Add("sk", sessionKey) params.Add("sk", sessionKey)
resp, err := c.makeRequest(ctx, http.MethodPost, params, true) 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 var response Response
jsonErr := decoder.Decode(&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) return nil, fmt.Errorf("last.fm http status: (%d)", resp.StatusCode)
} }
if jsonErr != nil { if jsonErr != nil {

View file

@ -19,8 +19,10 @@ import (
var _ = Describe("client", func() { var _ = Describe("client", func() {
var httpClient *tests.FakeHttpClient var httpClient *tests.FakeHttpClient
var client *client var client *client
var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context()
httpClient = &tests.FakeHttpClient{} httpClient = &tests.FakeHttpClient{}
client = newClient("API_KEY", "SECRET", httpClient) client = newClient("API_KEY", "SECRET", httpClient)
}) })
@ -28,19 +30,19 @@ var _ = Describe("client", func() {
Describe("albumGetInfo", func() { Describe("albumGetInfo", func() {
It("returns an album on successful response", func() { It("returns an album on successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
album, err := client.albumGetInfo(context.Background(), "Believe", "U2", "mbid-1234", "pt") album, err := client.albumGetInfo(ctx, "Believe", "U2", "mbid-1234", "pt")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(album.Name).To(Equal("Believe")) Expect(album.Name).To(Equal("Believe"))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?album=Believe&api_key=API_KEY&artist=U2&format=json&lang=pt&mbid=mbid-1234&method=album.getInfo")) Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?album=Believe&api_key=API_KEY&artist=U2&format=json&lang=pt&mbid=mbid-1234&method=album.getInfo"))
}) })
It("does not double-encode plus signs", func() { It("does not double-encode plus signs", func() {
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 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(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("Florence + the Machine")) Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("Florence + the Machine"))
}) })
@ -49,19 +51,19 @@ var _ = Describe("client", func() {
Describe("artistGetInfo", func() { Describe("artistGetInfo", func() {
It("returns an artist for a successful response", func() { It("returns an artist for a successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
artist, err := client.artistGetInfo(context.Background(), "U2", "pt") artist, err := client.artistGetInfo(ctx, "U2", "pt")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(artist.Name).To(Equal("U2")) Expect(artist.Name).To(Equal("U2"))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&lang=pt&method=artist.getInfo")) Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&lang=pt&method=artist.getInfo"))
}) })
It("double-encodes plus signs in the artist name", func() { It("double-encodes plus signs in the artist name", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
httpClient.Res = http.Response{Body: f, StatusCode: 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(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("Florence %2B the Machine")) 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() { It("fails if Last.fm returns an http status != 200", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Internal Server Error`)), Body: io.NopCloser(bytes.NewBufferString(`Internal Server Error`)),
StatusCode: 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)")) Expect(err).To(MatchError("last.fm http status: (500)"))
}) })
It("fails if Last.fm returns an http status != 200", func() { It("fails if Last.fm returns an http status != 200", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":3,"message":"Invalid Method - No method with that name in this package"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":3,"message":"Invalid Method - No method with that name in this package"}`)),
StatusCode: 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"})) 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() { It("fails if Last.fm returns an error", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":6,"message":"The artist you supplied could not be found"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":6,"message":"The artist you supplied could not be found"}`)),
StatusCode: 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"})) Expect(err).To(MatchError(&lastFMError{Code: 6, Message: "The artist you supplied could not be found"}))
}) })
It("fails if HttpClient.Do() returns error", func() { It("fails if HttpClient.Do() returns error", func() {
httpClient.Err = errors.New("generic error") 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")) Expect(err).To(MatchError("generic error"))
}) })
It("fails if returned body is not a valid JSON", func() { It("fails if returned body is not a valid JSON", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`<xml>NOT_VALID_JSON</xml>`)), Body: io.NopCloser(bytes.NewBufferString(`<xml>NOT_VALID_JSON</xml>`)),
StatusCode: 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")) Expect(err).To(MatchError("invalid character '<' looking for beginning of value"))
}) })
@ -118,19 +120,19 @@ var _ = Describe("client", func() {
Describe("artistGetSimilar", func() { Describe("artistGetSimilar", func() {
It("returns an artist for a successful response", func() { It("returns an artist for a successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
similar, err := client.artistGetSimilar(context.Background(), "U2", 2) similar, err := client.artistGetSimilar(ctx, "U2", 2)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(similar.Artists)).To(Equal(2)) 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")) Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&limit=2&method=artist.getSimilar"))
}) })
It("double-encodes plus signs in the artist name", func() { It("double-encodes plus signs in the artist name", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json") f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 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(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("%2B44")) Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("%2B44"))
}) })
@ -139,19 +141,19 @@ var _ = Describe("client", func() {
Describe("artistGetTopTracks", func() { Describe("artistGetTopTracks", func() {
It("returns top tracks for a successful response", func() { It("returns top tracks for a successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json") f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
top, err := client.artistGetTopTracks(context.Background(), "U2", 2) top, err := client.artistGetTopTracks(ctx, "U2", 2)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(top.Track)).To(Equal(2)) 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")) Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&limit=2&method=artist.getTopTracks"))
}) })
It("double-encodes plus signs in the artist name", func() { It("double-encodes plus signs in the artist name", func() {
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json") f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
httpClient.Res = http.Response{Body: f, StatusCode: 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(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("C%2BC Music Factory")) Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("C%2BC Music Factory"))
}) })
@ -160,11 +162,11 @@ var _ = Describe("client", func() {
Describe("trackGetSimilar", func() { Describe("trackGetSimilar", func() {
It("returns similar tracks for a successful response", func() { It("returns similar tracks for a successful response", func() {
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json") f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
similar, err := client.trackGetSimilar(context.Background(), "Just Can't Get Enough", "Depeche Mode", 5) similar, err := client.trackGetSimilar(ctx, "Just Can't Get Enough", "Depeche Mode", 5)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(similar.Track)).To(Equal(5)) Expect(similar.Track).To(HaveLen(5))
Expect(similar.Track[0].Name).To(Equal("Dreaming of Me")) Expect(similar.Track[0].Name).To(Equal("Dreaming of Me"))
Expect(similar.Track[0].Artist.Name).To(Equal("Depeche Mode")) Expect(similar.Track[0].Artist.Name).To(Equal("Depeche Mode"))
Expect(similar.Track[0].Match).To(Equal(1.0)) Expect(similar.Track[0].Match).To(Equal(1.0))
@ -173,9 +175,9 @@ var _ = Describe("client", func() {
It("double-encodes plus signs in the track and artist names", func() { It("double-encodes plus signs in the track and artist names", func() {
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json") f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
httpClient.Res = http.Response{Body: f, StatusCode: 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()) Expect(err).ToNot(HaveOccurred())
query := httpClient.SavedRequest.URL.Query() query := httpClient.SavedRequest.URL.Query()
Expect(query.Get("track")).To(Equal("1%2B1")) 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() { It("returns empty list when no similar tracks found", func() {
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json") f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
similar, err := client.trackGetSimilar(context.Background(), "UnknownTrack", "UnknownArtist", 3) similar, err := client.trackGetSimilar(ctx, "UnknownTrack", "UnknownArtist", 3)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(similar.Track).To(BeEmpty()) Expect(similar.Track).To(BeEmpty())
}) })
}) })
@ -196,10 +198,10 @@ var _ = Describe("client", func() {
It("returns a token when the request is successful", func() { It("returns a token when the request is successful", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"token":"TOKEN"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"token":"TOKEN"}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
Expect(client.GetToken(context.Background())).To(Equal("TOKEN")) Expect(client.GetToken(ctx)).To(Equal("TOKEN"))
queryParams := httpClient.SavedRequest.URL.Query() queryParams := httpClient.SavedRequest.URL.Query()
Expect(queryParams.Get("method")).To(Equal("auth.getToken")) Expect(queryParams.Get("method")).To(Equal("auth.getToken"))
Expect(queryParams.Get("format")).To(Equal("json")) 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() { It("returns a session key when the request is successful", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"session":{"name":"Navidrome","key":"SESSION_KEY","subscriber":0}}`)), Body: io.NopCloser(bytes.NewBufferString(`{"session":{"name":"Navidrome","key":"SESSION_KEY","subscriber":0}}`)),
StatusCode: 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() queryParams := httpClient.SavedRequest.URL.Query()
Expect(queryParams.Get("method")).To(Equal("auth.getSession")) Expect(queryParams.Get("method")).To(Equal("auth.getSession"))
Expect(queryParams.Get("format")).To(Equal("json")) Expect(queryParams.Get("format")).To(Equal("json"))
@ -229,7 +231,7 @@ var _ = Describe("client", func() {
It("sends parameters in request body for POST", func() { It("sends parameters in request body for POST", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"scrobbles":{"scrobble":{"ignoredMessage":{"code":"0"}},"@attr":{"accepted":1}}}`)), Body: io.NopCloser(bytes.NewBufferString(`{"scrobbles":{"scrobble":{"ignoredMessage":{"code":"0"}},"@attr":{"accepted":1}}}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
info := ScrobbleInfo{ info := ScrobbleInfo{
@ -240,8 +242,8 @@ var _ = Describe("client", func() {
duration: 276, duration: 276,
albumArtist: "U2", albumArtist: "U2",
} }
err := client.scrobble(context.Background(), "SESSION_KEY", info) err := client.scrobble(ctx, "SESSION_KEY", info)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
req := httpClient.SavedRequest req := httpClient.SavedRequest
Expect(req.Method).To(Equal(http.MethodPost)) Expect(req.Method).To(Equal(http.MethodPost))
@ -263,7 +265,7 @@ var _ = Describe("client", func() {
It("sends parameters in request body for POST", func() { It("sends parameters in request body for POST", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"nowplaying":{"ignoredMessage":{"code":"0"}}}`)), Body: io.NopCloser(bytes.NewBufferString(`{"nowplaying":{"ignoredMessage":{"code":"0"}}}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
info := ScrobbleInfo{ info := ScrobbleInfo{
@ -274,8 +276,8 @@ var _ = Describe("client", func() {
duration: 276, duration: 276,
albumArtist: "U2", albumArtist: "U2",
} }
err := client.updateNowPlaying(context.Background(), "SESSION_KEY", info) err := client.updateNowPlaying(ctx, "SESSION_KEY", info)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
req := httpClient.SavedRequest req := httpClient.SavedRequest
Expect(req.Method).To(Equal(http.MethodPost)) Expect(req.Method).To(Equal(http.MethodPost))

View file

@ -3,7 +3,9 @@ package lastfm
import ( import (
"testing" "testing"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -12,6 +14,10 @@ import (
func TestLastFM(t *testing.T) { func TestLastFM(t *testing.T) {
tests.Init(t, false) tests.Init(t, false)
log.SetLevel(log.LevelFatal) log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail) RegisterFailHandler(Fail)
RunSpecs(t, "LastFM Test Suite") 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 var resp Response
body, _ := os.ReadFile("tests/fixtures/lastfm.artist.getinfo.json") body, _ := os.ReadFile("tests/fixtures/lastfm.artist.getinfo.json")
err := json.Unmarshal(body, &resp) err := json.Unmarshal(body, &resp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(resp.Artist.Name).To(Equal("U2")) Expect(resp.Artist.Name).To(Equal("U2"))
Expect(resp.Artist.MBID).To(Equal("a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432")) Expect(resp.Artist.MBID).To(Equal("a3cb23fc-acd3-4ce0-8f36-1e5aa6a18432"))
@ -28,7 +28,7 @@ var _ = Describe("LastFM responses", func() {
var resp Response var resp Response
body, _ := os.ReadFile("tests/fixtures/lastfm.artist.getsimilar.json") body, _ := os.ReadFile("tests/fixtures/lastfm.artist.getsimilar.json")
err := json.Unmarshal(body, &resp) err := json.Unmarshal(body, &resp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(resp.SimilarArtists.Artists).To(HaveLen(2)) Expect(resp.SimilarArtists.Artists).To(HaveLen(2))
Expect(resp.SimilarArtists.Artists[0].Name).To(Equal("Passengers")) Expect(resp.SimilarArtists.Artists[0].Name).To(Equal("Passengers"))
@ -41,7 +41,7 @@ var _ = Describe("LastFM responses", func() {
var resp Response var resp Response
body, _ := os.ReadFile("tests/fixtures/lastfm.artist.gettoptracks.json") body, _ := os.ReadFile("tests/fixtures/lastfm.artist.gettoptracks.json")
err := json.Unmarshal(body, &resp) err := json.Unmarshal(body, &resp)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(resp.TopTracks.Track).To(HaveLen(2)) Expect(resp.TopTracks.Track).To(HaveLen(2))
Expect(resp.TopTracks.Track[0].Name).To(Equal("Beautiful Day")) Expect(resp.TopTracks.Track[0].Name).To(Equal("Beautiful Day"))
@ -56,7 +56,7 @@ var _ = Describe("LastFM responses", func() {
var error Response var error Response
body := []byte(`{"error":3,"message":"Invalid Method - No method with that name in this package"}`) body := []byte(`{"error":3,"message":"Invalid Method - No method with that name in this package"}`)
err := json.Unmarshal(body, &error) err := json.Unmarshal(body, &error)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(error.Error).To(Equal(3)) Expect(error.Error).To(Equal(3))
Expect(error.Message).To(Equal("Invalid Method - No method with that name in this package")) Expect(error.Message).To(Equal("Invalid Method - No method with that name in this package"))

View file

@ -31,7 +31,7 @@ func listenBrainzConstructor(ds model.DataStore) *listenBrainzAgent {
l := &listenBrainzAgent{ l := &listenBrainzAgent{
ds: ds, ds: ds,
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty}, sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
baseURL: conf.Server.ListenBrainz.BaseURL, baseURL: conf.Server().ListenBrainz.BaseURL,
} }
hc := httpclient.New(consts.DefaultHttpClientTimeOut) hc := httpclient.New(consts.DefaultHttpClientTimeOut)
chc := cache.NewHTTPClient(hc, consts.DefaultHttpClientTimeOut) chc := cache.NewHTTPClient(hc, consts.DefaultHttpClientTimeOut)
@ -80,7 +80,7 @@ func (l *listenBrainzAgent) NowPlaying(ctx context.Context, userId string, track
li := l.formatListen(track) li := l.formatListen(track)
err = l.client.updateNowPlaying(ctx, sk, li) err = l.client.updateNowPlaying(ctx, sk, li)
if err != nil { 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 errors.Join(err, scrobbler.ErrUnrecoverable)
} }
return nil return nil
@ -228,29 +228,30 @@ func (l *listenBrainzAgent) PlaybackReport(context.Context, scrobbler.PlaybackSe
} }
func init() { func init() {
conf.AddHook(func() { conf.AddHook(register)
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
})
agents.Register(listenBrainzAgentName, func(ds model.DataStore) agents.Interface { func register() {
// This is a workaround for the fact that a (Interface)(nil) is not the same as a (*listenBrainzAgent)(nil) scrobbler.Register(listenBrainzAgentName, newScrobbler)
// See https://go.dev/doc/faq#nil_error agents.Register(listenBrainzAgentName, newAgent)
a := listenBrainzConstructor(ds) }
if a != nil {
return a func listenBrainzEnabled() bool {
} return conf.Server().ListenBrainz.Enabled
}
func newScrobbler(ds model.DataStore) scrobbler.Scrobbler {
if !listenBrainzEnabled() {
return nil return nil
})
} }
}) return listenBrainzConstructor(ds)
}
func newAgent(ds model.DataStore) agents.Interface {
if !listenBrainzEnabled() {
return nil
}
return listenBrainzConstructor(ds)
} }
var ( var (

View file

@ -8,12 +8,16 @@ import (
"io" "io"
"net/http" "net/http"
"os" "os"
"reflect"
"time" "time"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/scrobbler" "github.com/navidrome/navidrome/core/scrobbler"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -28,9 +32,10 @@ var _ = Describe("listenBrainzAgent", func() {
var track *model.MediaFile var track *model.MediaFile
BeforeEach(func() { BeforeEach(func() {
ds = &tests.MockDataStore{} ctx = GinkgoT().Context()
ctx = context.Background() ds = persistence.New(db.Db())
_ = 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{} httpClient = &tests.FakeHttpClient{}
agent = listenBrainzConstructor(ds) agent = listenBrainzConstructor(ds)
agent.client = newClient("http://localhost:8080", httpClient) agent.client = newClient("http://localhost:8080", httpClient)
@ -46,8 +51,8 @@ var _ = Describe("listenBrainzAgent", func() {
Duration: 142.2, Duration: 142.2,
Participants: map[model.Role]model.ParticipantList{ Participants: map[model.Role]model.ParticipantList{
model.RoleArtist: []model.Participant{ model.RoleArtist: []model.Participant{
{Artist: model.Artist{ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"}}, {ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"},
{Artist: model.Artist{ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"}}, {ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"},
}, },
}, },
} }
@ -80,7 +85,7 @@ var _ = Describe("listenBrainzAgent", func() {
Describe("NowPlaying", func() { Describe("NowPlaying", func() {
It("updates NowPlaying successfully", func() { It("updates NowPlaying successfully", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: http.StatusOK}
err := agent.NowPlaying(ctx, "user-1", track, 0) err := agent.NowPlaying(ctx, "user-1", track, 0)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -100,14 +105,14 @@ var _ = Describe("listenBrainzAgent", func() {
}) })
It("sends a Scrobble successfully", func() { It("sends a Scrobble successfully", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: http.StatusOK}
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
}) })
It("sets the Timestamp properly", func() { It("sets the Timestamp properly", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: http.StatusOK}
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -128,7 +133,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns ErrRetryLater on error 503", func() { It("returns ErrRetryLater on error 503", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 503, "error": "Cannot submit listens to queue, please try again later."}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 503, "error": "Cannot submit listens to queue, please try again later."}`)),
StatusCode: 503, StatusCode: http.StatusServiceUnavailable,
} }
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
@ -138,7 +143,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns ErrRetryLater on error 500", func() { It("returns ErrRetryLater on error 500", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 500, "error": "Something went wrong. Please try again."}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 500, "error": "Something went wrong. Please try again."}`)),
StatusCode: 500, StatusCode: http.StatusInternalServerError,
} }
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
@ -148,7 +153,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns ErrRetryLater on http errors", func() { It("returns ErrRetryLater on http errors", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad Gateway`)), Body: io.NopCloser(bytes.NewBufferString(`Bad Gateway`)),
StatusCode: 500, StatusCode: http.StatusInternalServerError,
} }
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
@ -158,7 +163,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns ErrUnrecoverable on other errors", func() { It("returns ErrUnrecoverable on other errors", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400, "error": "BadRequest: Invalid JSON document submitted."}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 400, "error": "BadRequest: Invalid JSON document submitted."}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
err := agent.Scrobble(ctx, "user-1", sc) 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() { It("keeps a 429 scrobble for retry and carries the delay", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
StatusCode: 429, StatusCode: http.StatusTooManyRequests,
Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}}, Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}},
Body: io.NopCloser(bytes.NewBufferString(`{"code":429,"error":"rate limited"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code":429,"error":"rate limited"}`)),
} }
@ -191,7 +196,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns artist url when MBID present", func() { It("returns artist url when MBID present", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json") f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json")
httpClient.Res = http.Response{Body: f, StatusCode: 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(agent.GetArtistURL(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")).To(Equal("http://projectmili.com/"))
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
Expect(httpClient.SavedRequest.URL.Query().Get("artist_mbids")).To(Equal("d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")) Expect(httpClient.SavedRequest.URL.Query().Get("artist_mbids")).To(Equal("d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56"))
@ -199,7 +204,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns error when url not present", func() { It("returns error when url not present", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json") f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973") _, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973")
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
@ -217,7 +222,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns error when ListenBrainz returns an error", func() { It("returns error when ListenBrainz returns an error", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
_, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973") _, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973")
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
@ -247,7 +252,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns an error on listenbrainz error", func() { It("returns an error on listenbrainz error", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
_, err := agent.GetArtistTopSongs(ctx, "", "", "1", 1) _, err := agent.GetArtistTopSongs(ctx, "", "", "1", 1)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
@ -257,7 +262,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns all tracks when asked", func() { It("returns all tracks when asked", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json") f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 2) data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]agents.Song{ Expect(data).To(Equal([]agents.Song{
@ -284,7 +289,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns only one track when prompted", func() { It("returns only one track when prompted", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json") f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1) data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]agents.Song{ Expect(data).To(Equal([]agents.Song{
@ -310,7 +315,7 @@ var _ = Describe("listenBrainzAgent", func() {
"release_mbid": "rel-1", "release_mbid": "rel-1",
"length": 200000 "length": 200000
}]` }]`
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: http.StatusOK}
data, err := agent.GetArtistTopSongs(ctx, "", "", "mbid-drake", 1) data, err := agent.GetArtistTopSongs(ctx, "", "", "mbid-drake", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(HaveLen(1)) Expect(data).To(HaveLen(1))
@ -322,7 +327,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("leaves Artists nil when the top song carries no name or MBIDs", func() { It("leaves Artists nil when the top song carries no name or MBIDs", func() {
body := `[{"recording_name": "Anon", "recording_mbid": "rec-1", "artist_name": "", "artist_mbids": []}]` body := `[{"recording_name": "Anon", "recording_mbid": "rec-1", "artist_name": "", "artist_mbids": []}]`
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: 200} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: http.StatusOK}
data, err := agent.GetArtistTopSongs(ctx, "", "", "x", 1) data, err := agent.GetArtistTopSongs(ctx, "", "", "x", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(HaveLen(1)) Expect(data).To(HaveLen(1))
@ -354,7 +359,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns an error on listenbrainz error", func() { It("returns an error on listenbrainz error", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)), Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
_, err := agent.GetSimilarArtists(ctx, "", "", "1", 1) _, err := agent.GetSimilarArtists(ctx, "", "", "1", 1)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
@ -364,7 +369,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns all data on call", func() { It("returns all data on call", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 2) resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -378,7 +383,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns subset of data on call", func() { It("returns subset of data on call", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 1) resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -414,7 +419,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns an error on listenbrainz error", func() { It("returns an error on listenbrainz error", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)), Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
StatusCode: 400, StatusCode: http.StatusBadRequest,
} }
_, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", "1", 1) _, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", "1", 1)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
@ -424,7 +429,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns all data on call", func() { It("returns all data on call", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 2) resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -456,7 +461,7 @@ var _ = Describe("listenBrainzAgent", func() {
It("returns subset of data on call", func() { It("returns subset of data on call", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 1) resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 1)
Expect(err).ToNot(HaveOccurred()) 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

@ -39,7 +39,7 @@ func NewRouter(ds model.DataStore) *Router {
} }
r.Handler = r.routes() r.Handler = r.routes()
hc := httpclient.New(consts.DefaultHttpClientTimeOut) hc := httpclient.New(consts.DefaultHttpClientTimeOut)
r.client = newClient(conf.Server.ListenBrainz.BaseURL, hc) r.client = newClient(conf.Server().ListenBrainz.BaseURL, hc)
return r return r
} }

View file

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

View file

@ -64,7 +64,7 @@ type listenBrainzResponse struct {
} }
type listenBrainzRequest struct { type listenBrainzRequest struct {
ApiKey string //nolint:gosec ApiKey string
Body listenBrainzRequestBody 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) { 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) uri, err := c.path(endpoint)
if err != nil { if err != nil {
return nil, err 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") req.Header.Add("Content-Type", "application/json; charset=UTF-8")
if r.ApiKey != "" { 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) 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 var response listenBrainzResponse
jsonErr := decoder.Decode(&response) 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) return nil, fmt.Errorf("ListenBrainz: HTTP Error, Status: (%d)", resp.StatusCode)
} }
if jsonErr != nil { 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 // 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() defer resp.Body.Close()
if resp.StatusCode == http.StatusTooManyRequests { if resp.StatusCode == http.StatusTooManyRequests {
return nil, retryLaterErr(resp.Header) return nil, retryLaterErr(resp.Header)
@ -315,7 +318,7 @@ func (c *client) getSimilarArtists(ctx context.Context, mbid string, limit int)
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-artists/json", nil) req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-artists/json", nil)
req.Header.Add("Content-Type", "application/json; charset=UTF-8") req.Header.Add("Content-Type", "application/json; charset=UTF-8")
req.URL.RawQuery = url.Values{ req.URL.RawQuery = url.Values{
"artist_mbids": []string{mbid}, "algorithm": []string{conf.Server.ListenBrainz.ArtistAlgorithm}, "artist_mbids": []string{mbid}, "algorithm": []string{conf.Server().ListenBrainz.ArtistAlgorithm},
}.Encode() }.Encode()
log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL) log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL)
@ -354,7 +357,7 @@ func (c *client) getSimilarRecordings(ctx context.Context, mbid string, limit in
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-recordings/json", nil) req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-recordings/json", nil)
req.Header.Add("Content-Type", "application/json; charset=UTF-8") req.Header.Add("Content-Type", "application/json; charset=UTF-8")
req.URL.RawQuery = url.Values{ req.URL.RawQuery = url.Values{
"recording_mbids": []string{mbid}, "algorithm": []string{conf.Server.ListenBrainz.TrackAlgorithm}, "recording_mbids": []string{mbid}, "algorithm": []string{conf.Server().ListenBrainz.TrackAlgorithm},
}.Encode() }.Encode()
log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL) log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL)

View file

@ -13,7 +13,6 @@ import (
"time" "time"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
@ -23,7 +22,9 @@ import (
var _ = Describe("client", func() { var _ = Describe("client", func() {
var httpClient *tests.FakeHttpClient var httpClient *tests.FakeHttpClient
var client *client var client *client
var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context()
httpClient = &tests.FakeHttpClient{} httpClient = &tests.FakeHttpClient{}
client = newClient("BASE_URL/", httpClient) client = newClient("BASE_URL/", httpClient)
}) })
@ -47,12 +48,12 @@ var _ = Describe("client", func() {
BeforeEach(func() { BeforeEach(func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token valid.", "user_name": "ListenBrainzUser", "valid": true}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token valid.", "user_name": "ListenBrainzUser", "valid": true}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
}) })
It("formats the request properly", func() { It("formats the request properly", func() {
_, err := client.validateToken(context.Background(), "LB-TOKEN") _, err := client.validateToken(ctx, "LB-TOKEN")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/validate-token")) Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/validate-token"))
@ -61,9 +62,9 @@ var _ = Describe("client", func() {
}) })
It("parses and returns the response", 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(err).ToNot(HaveOccurred())
Expect(res.Valid).To(Equal(true)) Expect(res.Valid).To(BeTrue())
Expect(res.UserName).To(Equal("ListenBrainzUser")) Expect(res.UserName).To(Equal("ListenBrainzUser"))
}) })
}) })
@ -73,7 +74,7 @@ var _ = Describe("client", func() {
BeforeEach(func() { BeforeEach(func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)),
StatusCode: 200, StatusCode: http.StatusOK,
} }
li = listenInfo{ li = listenInfo{
TrackMetadata: trackMetadata{ TrackMetadata: trackMetadata{
@ -94,7 +95,7 @@ var _ = Describe("client", func() {
Describe("updateNowPlaying", func() { Describe("updateNowPlaying", func() {
It("formats the request properly", 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.Method).To(Equal(http.MethodPost))
Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens")) Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens"))
Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN")) Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
@ -112,7 +113,7 @@ var _ = Describe("client", func() {
}) })
It("formats the request properly", 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.Method).To(Equal(http.MethodPost))
Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens")) Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens"))
Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN")) Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
@ -130,9 +131,9 @@ var _ = Describe("client", func() {
It("handles a malformed request with status code", func() { It("handles a malformed request with status code", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)),
StatusCode: 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(err.Error()).To(Equal("ListenBrainz error(400): artist mbid 1 is not valid."))
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=1")) Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=1"))
@ -142,9 +143,9 @@ var _ = Describe("client", func() {
It("handles a malformed request without meaningful body", func() { It("handles a malformed request without meaningful body", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(``)), Body: io.NopCloser(bytes.NewBufferString(``)),
StatusCode: 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(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (501)"))
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=1")) Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=1"))
@ -153,8 +154,8 @@ var _ = Describe("client", func() {
It("It returns not found when the artist has no official homepage", func() { It("It returns not found when the artist has no official homepage", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json") f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
_, err := client.getArtistUrl(context.Background(), "7c2cc610-f998-43ef-a08f-dae3344b8973") _, err := client.getArtistUrl(ctx, "7c2cc610-f998-43ef-a08f-dae3344b8973")
Expect(err.Error()).To(Equal("listenbrainz: not found")) Expect(err.Error()).To(Equal("listenbrainz: not found"))
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=7c2cc610-f998-43ef-a08f-dae3344b8973")) Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=7c2cc610-f998-43ef-a08f-dae3344b8973"))
@ -163,8 +164,8 @@ var _ = Describe("client", func() {
It("It returns data when the artist has a homepage", func() { It("It returns data when the artist has a homepage", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json") f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
url, err := client.getArtistUrl(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56") url, err := client.getArtistUrl(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(url).To(Equal("http://projectmili.com/")) Expect(url).To(Equal("http://projectmili.com/"))
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
@ -179,9 +180,9 @@ var _ = Describe("client", func() {
It("handles a malformed request with status code", func() { It("handles a malformed request with status code", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)),
StatusCode: 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(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.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1")) Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1"))
@ -191,9 +192,9 @@ var _ = Describe("client", func() {
It("handles a malformed request without standard body", func() { It("handles a malformed request without standard body", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(``)), Body: io.NopCloser(bytes.NewBufferString(``)),
StatusCode: 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(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (500)"))
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1")) Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1"))
@ -202,8 +203,8 @@ var _ = Describe("client", func() {
It("It returns all tracks when given the opportunity", func() { It("It returns all tracks when given the opportunity", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json") f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
data, err := client.getArtistTopSongs(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 5) data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 5)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]trackInfo{ Expect(data).To(Equal([]trackInfo{
{ {
@ -232,8 +233,8 @@ var _ = Describe("client", func() {
It("It returns a subset of tracks when allowed", func() { It("It returns a subset of tracks when allowed", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json") f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
data, err := client.getArtistTopSongs(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1) data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]trackInfo{ Expect(data).To(Equal([]trackInfo{
{ {
@ -257,7 +258,6 @@ var _ = Describe("client", func() {
BeforeEach(func() { BeforeEach(func() {
algorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30" algorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30"
DeferCleanup(configtest.SetupConfig())
}) })
getUrl := func(mbid string) string { getUrl := func(mbid string) string {
@ -269,9 +269,9 @@ var _ = Describe("client", func() {
It("handles a malformed request with status code", func() { It("handles a malformed request with status code", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)), Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
StatusCode: 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(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)"))
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl("1"))) Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl("1")))
@ -280,8 +280,8 @@ var _ = Describe("client", func() {
It("handles real data properly", func() { It("handles real data properly", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := client.getSimilarArtists(context.Background(), mbid, 2) resp, err := client.getSimilarArtists(ctx, mbid, 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid))) Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
@ -294,8 +294,8 @@ var _ = Describe("client", func() {
It("truncates data when requested", func() { It("truncates data when requested", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := client.getSimilarArtists(context.Background(), "db92a151-1ac2-438b-bc43-b82e149ddd50", 1) resp, err := client.getSimilarArtists(ctx, "db92a151-1ac2-438b-bc43-b82e149ddd50", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid))) Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
@ -307,11 +307,11 @@ var _ = Describe("client", func() {
It("fetches a different endpoint when algorithm changes", func() { It("fetches a different endpoint when algorithm changes", func() {
algorithm = "session_based_days_1825_session_300_contribution_3_threshold_10_limit_100_filter_True_skip_30" algorithm = "session_based_days_1825_session_300_contribution_3_threshold_10_limit_100_filter_True_skip_30"
conf.Server.ListenBrainz.ArtistAlgorithm = algorithm conf.Update(func(c *conf.Options) { c.ListenBrainz.ArtistAlgorithm = algorithm })
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := client.getSimilarArtists(context.Background(), mbid, 2) resp, err := client.getSimilarArtists(ctx, mbid, 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid))) Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
@ -328,7 +328,6 @@ var _ = Describe("client", func() {
BeforeEach(func() { BeforeEach(func() {
algorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30" algorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30"
DeferCleanup(configtest.SetupConfig())
}) })
getUrl := func(mbid string) string { getUrl := func(mbid string) string {
@ -340,9 +339,9 @@ var _ = Describe("client", func() {
It("handles a malformed request with status code", func() { It("handles a malformed request with status code", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)), Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
StatusCode: 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(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)"))
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl("1"))) Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl("1")))
@ -351,8 +350,8 @@ var _ = Describe("client", func() {
It("handles real data properly", func() { It("handles real data properly", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := client.getSimilarRecordings(context.Background(), mbid, 2) resp, err := client.getSimilarRecordings(ctx, mbid, 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid))) Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
@ -379,8 +378,8 @@ var _ = Describe("client", func() {
It("truncates data when requested", func() { It("truncates data when requested", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := client.getSimilarRecordings(context.Background(), mbid, 1) resp, err := client.getSimilarRecordings(ctx, mbid, 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid))) Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
@ -399,9 +398,9 @@ var _ = Describe("client", func() {
It("properly sorts by score and truncates duplicates", func() { It("properly sorts by score and truncates duplicates", func() {
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings-real-out-of-order.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings-real-out-of-order.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
// There are actually 5 items. The dedup should happen FIRST // 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(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid))) Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
@ -444,11 +443,11 @@ var _ = Describe("client", func() {
It("uses a different algorithm when configured", func() { It("uses a different algorithm when configured", func() {
algorithm = "session_based_days_180_session_300_contribution_5_threshold_15_limit_50_skip_30" algorithm = "session_based_days_180_session_300_contribution_5_threshold_15_limit_50_skip_30"
conf.Server.ListenBrainz.TrackAlgorithm = algorithm conf.Update(func(c *conf.Options) { c.ListenBrainz.TrackAlgorithm = algorithm })
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json") f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
httpClient.Res = http.Response{Body: f, StatusCode: 200} httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
resp, err := client.getSimilarRecordings(context.Background(), mbid, 1) resp, err := client.getSimilarRecordings(ctx, mbid, 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet)) Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid))) Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
@ -469,11 +468,11 @@ var _ = Describe("client", func() {
Describe("rate limiting", func() { Describe("rate limiting", func() {
It("returns RetryLaterError with the header delay on 429", func() { It("returns RetryLaterError with the header delay on 429", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
StatusCode: 429, StatusCode: http.StatusTooManyRequests,
Header: http.Header{"X-Ratelimit-Reset-In": []string{"3"}}, Header: http.Header{"X-Ratelimit-Reset-In": []string{"3"}},
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)), Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)),
} }
_, err := client.validateToken(context.Background(), "token") _, err := client.validateToken(ctx, "token")
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue()) Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
retry, ok := errors.AsType[*agents.RetryLaterError](err) retry, ok := errors.AsType[*agents.RetryLaterError](err)
Expect(ok).To(BeTrue()) Expect(ok).To(BeTrue())
@ -482,10 +481,10 @@ var _ = Describe("client", func() {
It("returns RetryLaterError with zero delay when no header is present", func() { It("returns RetryLaterError with zero delay when no header is present", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
StatusCode: 429, StatusCode: http.StatusTooManyRequests,
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)), 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()) Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
retry, _ := errors.AsType[*agents.RetryLaterError](err) retry, _ := errors.AsType[*agents.RetryLaterError](err)
Expect(retry.RetryIn).To(BeZero()) Expect(retry.RetryIn).To(BeZero())
@ -494,11 +493,11 @@ var _ = Describe("client", func() {
DescribeTable("caps absurd header values at one hour", DescribeTable("caps absurd header values at one hour",
func(header string) { func(header string) {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
StatusCode: 429, StatusCode: http.StatusTooManyRequests,
Header: http.Header{"X-Ratelimit-Reset-In": []string{header}}, Header: http.Header{"X-Ratelimit-Reset-In": []string{header}},
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)), Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
} }
_, err := client.validateToken(context.Background(), "token") _, err := client.validateToken(ctx, "token")
retry, _ := errors.AsType[*agents.RetryLaterError](err) retry, _ := errors.AsType[*agents.RetryLaterError](err)
Expect(retry.RetryIn).To(Equal(time.Hour)) Expect(retry.RetryIn).To(Equal(time.Hour))
}, },
@ -510,11 +509,11 @@ var _ = Describe("client", func() {
It("maps a body-level 429 sent with a non-429 status", func() { It("maps a body-level 429 sent with a non-429 status", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
StatusCode: 200, StatusCode: http.StatusOK,
Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}}, Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}},
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)), Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)),
} }
_, err := client.validateToken(context.Background(), "token") _, err := client.validateToken(ctx, "token")
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue()) Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
retry, ok := errors.AsType[*agents.RetryLaterError](err) retry, ok := errors.AsType[*agents.RetryLaterError](err)
Expect(ok).To(BeTrue()) Expect(ok).To(BeTrue())
@ -523,11 +522,11 @@ var _ = Describe("client", func() {
It("returns RetryLaterError on a 429 from makeGenericRequest", func() { It("returns RetryLaterError on a 429 from makeGenericRequest", func() {
httpClient.Res = http.Response{ httpClient.Res = http.Response{
StatusCode: 429, StatusCode: http.StatusTooManyRequests,
Header: http.Header{"X-Ratelimit-Reset-In": []string{"5"}}, Header: http.Header{"X-Ratelimit-Reset-In": []string{"5"}},
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)), Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
} }
_, err := client.getArtistUrl(context.Background(), "1") _, err := client.getArtistUrl(ctx, "1")
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue()) Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
retry, ok := errors.AsType[*agents.RetryLaterError](err) retry, ok := errors.AsType[*agents.RetryLaterError](err)
Expect(ok).To(BeTrue()) Expect(ok).To(BeTrue())

View file

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

View file

@ -36,6 +36,15 @@ rules:
- sharing - sharing
- radio - radio
- admin - 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: nd-operation-stability-level-required:
description: Every operation declares its stability level, which the breaking-change gate relies on. description: Every operation declares its stability level, which the breaking-change gate relies on.
severity: error severity: error

View file

@ -3,7 +3,7 @@
"info": { "info": {
"title": "Navidrome API", "title": "Navidrome API",
"version": "1.0.0", "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": { "license": {
"name": "GPL-3.0", "name": "GPL-3.0",
"url": "https://www.gnu.org/licenses/gpl-3.0.html" "url": "https://www.gnu.org/licenses/gpl-3.0.html"
@ -18,6 +18,10 @@
{ {
"name": "server", "name": "server",
"description": "Server discovery and the published OpenAPI document." "description": "Server discovery and the published OpenAPI document."
},
{
"name": "auth",
"description": "Grants and login methods."
} }
], ],
"paths": { "paths": {
@ -29,8 +33,9 @@
"tags": [ "tags": [
"server" "server"
], ],
"security": [],
"summary": "Describe the server", "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": { "responses": {
"200": { "200": {
"description": "Server description.", "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": { "/openapi.json": {
"get": { "get": {
"operationId": "getOpenAPISpecJSON", "operationId": "getOpenAPISpecJSON",
@ -56,6 +96,7 @@
"tags": [ "tags": [
"server" "server"
], ],
"security": [],
"summary": "Get the OpenAPI document (JSON)", "summary": "Get the OpenAPI document (JSON)",
"description": "The bundled OpenAPI document of the running server version. Supports ETag revalidation.", "description": "The bundled OpenAPI document of the running server version. Supports ETag revalidation.",
"responses": { "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": { "/openapi.yaml": {
"get": { "get": {
"operationId": "getOpenAPISpecYAML", "operationId": "getOpenAPISpecYAML",
@ -89,6 +180,7 @@
"tags": [ "tags": [
"server" "server"
], ],
"security": [],
"summary": "Get the OpenAPI document (YAML)", "summary": "Get the OpenAPI document (YAML)",
"description": "The bundled OpenAPI document of the running server version. Supports ETag revalidation.", "description": "The bundled OpenAPI document of the running server version. Supports ETag revalidation.",
"responses": { "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": { "components": {
@ -120,8 +467,7 @@
"bearerAuth": { "bearerAuth": {
"type": "http", "type": "http",
"scheme": "bearer", "scheme": "bearer",
"bearerFormat": "JWT", "description": "Grant secret from a login method (`POST /auth/login`, `POST /auth/setup`). Opaque. The required scope is in each operation's `x-scope`."
"description": "Short-lived access token minted from a device grant. Not yet applied to any operation."
} }
}, },
"schemas": { "schemas": {
@ -153,16 +499,22 @@
"description": "True until the first admin user has been created." "description": "True until the first admin user has been created."
}, },
"loginMethods": { "loginMethods": {
"type": "array", "$ref": "#/components/schemas/LoginMethods"
"description": "Login methods this server accepts. New methods may be added; clients ignore values they do not recognise.",
"items": {
"type": "string",
"enum": [
"password"
]
} }
} }
},
"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": { "Problem": {
"type": "object", "type": "object",
@ -187,7 +539,7 @@
}, },
"detail": { "detail": {
"type": "string", "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": { "code": {
"type": "string", "type": "string",
@ -196,12 +548,21 @@
"validation", "validation",
"unauthorized", "unauthorized",
"forbidden", "forbidden",
"insufficient_scope",
"not_found", "not_found",
"method_not_allowed", "method_not_allowed",
"setup_complete",
"password_managed_externally",
"payload_too_large",
"rate_limited",
"unavailable", "unavailable",
"internal" "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": { "errors": {
"type": "array", "type": "array",
"description": "Per-field failures. Present only when `code` is `validation`.", "description": "Per-field failures. Present only when `code` is `validation`.",
@ -228,6 +589,327 @@
"description": "Why the value was rejected." "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": { "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": { "NotModified": {
"description": "Not modified.", "description": "Not modified.",
"headers": { "headers": {
@ -248,14 +945,127 @@
"$ref": "#/components/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": { "headers": {
"WWWAuthenticate": {
"description": "RFC 6750 Bearer challenge, for example `Bearer error=\"insufficient_scope\", scope=\"read\"`.",
"schema": {
"type": "string"
}
},
"ETag": { "ETag": {
"description": "Entity tag for `If-None-Match` revalidation.", "description": "Entity tag for `If-None-Match` revalidation.",
"schema": { "schema": {
"type": "string" "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 version: 1.0.0
description: | description: |
Navidrome API v1. Spec-first, additive within v1. Clients discover implemented 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 Enums are open: new values may be added to any enum within v1. Clients must
accept values they do not recognise instead of failing. 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 `HEAD` is accepted wherever `GET` is. A `405` response lists the allowed methods
in its `Allow` header. 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: license:
name: GPL-3.0 name: GPL-3.0
url: https://www.gnu.org/licenses/gpl-3.0.html url: https://www.gnu.org/licenses/gpl-3.0.html
@ -23,6 +27,8 @@ servers:
tags: tags:
- name: server - name: server
description: Server discovery and the published OpenAPI document. description: Server discovery and the published OpenAPI document.
- name: auth
description: Grants and login methods.
paths: paths:
/server: /server:
get: get:
@ -30,11 +36,11 @@ paths:
x-module: core x-module: core
x-stability-level: alpha x-stability-level: alpha
tags: [server] tags: [server]
security: []
summary: Describe the server summary: Describe the server
description: | description: |
Returns the public server description. No authentication required. Returns the public server description. No authentication required.
Authenticated requests will additionally receive the implemented capability modules Capability modules are listed by `GET /capabilities`.
once authentication is available.
responses: responses:
'200': '200':
description: Server description. description: Server description.
@ -44,12 +50,30 @@ paths:
$ref: '#/components/schemas/ServerInfo' $ref: '#/components/schemas/ServerInfo'
'500': '500':
$ref: '#/components/responses/InternalError' $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: /openapi.json:
get: get:
operationId: getOpenAPISpecJSON operationId: getOpenAPISpecJSON
x-module: core x-module: core
x-stability-level: alpha x-stability-level: alpha
tags: [server] tags: [server]
security: []
summary: Get the OpenAPI document (JSON) summary: Get the OpenAPI document (JSON)
description: The bundled OpenAPI document of the running server version. Supports ETag revalidation. description: The bundled OpenAPI document of the running server version. Supports ETag revalidation.
responses: responses:
@ -65,12 +89,41 @@ paths:
description: OpenAPI 3.0 document. description: OpenAPI 3.0 document.
'304': '304':
$ref: '#/components/responses/NotModified' $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: /openapi.yaml:
get: get:
operationId: getOpenAPISpecYAML operationId: getOpenAPISpecYAML
x-module: core x-module: core
x-stability-level: alpha x-stability-level: alpha
tags: [server] tags: [server]
security: []
summary: Get the OpenAPI document (YAML) summary: Get the OpenAPI document (YAML)
description: The bundled OpenAPI document of the running server version. Supports ETag revalidation. description: The bundled OpenAPI document of the running server version. Supports ETag revalidation.
responses: responses:
@ -86,13 +139,171 @@ paths:
description: OpenAPI 3.0 document. description: OpenAPI 3.0 document.
'304': '304':
$ref: '#/components/responses/NotModified' $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: components:
securitySchemes: securitySchemes:
bearerAuth: bearerAuth:
type: http type: http
scheme: bearer scheme: bearer
bearerFormat: JWT description: "Grant secret from a login method (`POST /auth/login`, `POST /auth/setup`). Opaque. The required scope is in each operation's `x-scope`."
description: Short-lived access token minted from a device grant. Not yet applied to any operation.
schemas: schemas:
ServerInfo: ServerInfo:
type: object type: object
@ -117,12 +328,19 @@ components:
type: boolean type: boolean
description: True until the first admin user has been created. description: True until the first admin user has been created.
loginMethods: loginMethods:
type: array $ref: '#/components/schemas/LoginMethods'
description: Login methods this server accepts. New methods may be added; clients ignore values they do not recognise. LoginMethods:
items: type: object
type: string description: |
enum: Login methods this server accepts, keyed by method. A missing key means the method is not offered.
- password 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: Problem:
type: object type: object
description: RFC 9457 problem details, returned for every 4xx and 5xx response. description: RFC 9457 problem details, returned for every 4xx and 5xx response.
@ -145,7 +363,7 @@ components:
description: HTTP status code of this response. description: HTTP status code of this response.
detail: detail:
type: string 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: code:
type: string type: string
description: Machine-readable error code, and the value clients switch on. New codes may be added. description: Machine-readable error code, and the value clients switch on. New codes may be added.
@ -153,10 +371,18 @@ components:
- validation - validation
- unauthorized - unauthorized
- forbidden - forbidden
- insufficient_scope
- not_found - not_found
- method_not_allowed - method_not_allowed
- setup_complete
- password_managed_externally
- payload_too_large
- rate_limited
- unavailable - unavailable
- internal - 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: errors:
type: array type: array
description: Per-field failures. Present only when `code` is `validation`. description: Per-field failures. Present only when `code` is `validation`.
@ -175,6 +401,250 @@ components:
message: message:
type: string type: string
description: Why the value was rejected. 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: responses:
InternalError: InternalError:
description: Unexpected server failure. Details are in the server log. description: Unexpected server failure. Details are in the server log.
@ -182,13 +652,96 @@ components:
application/problem+json: application/problem+json:
schema: schema:
$ref: '#/components/schemas/Problem' $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: NotModified:
description: Not modified. description: Not modified.
headers: headers:
ETag: ETag:
$ref: '#/components/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: 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: ETag:
description: Entity tag for `If-None-Match` revalidation. description: Entity tag for `If-None-Match` revalidation.
schema: schema:
type: string 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. description: The caller is authenticated but not allowed to do this.
headers:
WWW-Authenticate:
$ref: ../headers/WWWAuthenticate.yaml
content: content:
application/problem+json: application/problem+json:
schema: 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. description: Missing, invalid, or expired credentials.
headers:
WWW-Authenticate:
$ref: ../headers/WWWAuthenticate.yaml
content: content:
application/problem+json: application/problem+json:
schema: 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. description: HTTP status code of this response.
detail: detail:
type: string 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: code:
type: string type: string
description: Machine-readable error code, and the value clients switch on. New codes may be added. description: Machine-readable error code, and the value clients switch on. New codes may be added.
@ -24,10 +24,18 @@ properties:
- validation - validation
- unauthorized - unauthorized
- forbidden - forbidden
- insufficient_scope
- not_found - not_found
- method_not_allowed - method_not_allowed
- setup_complete
- password_managed_externally
- payload_too_large
- rate_limited
- unavailable - unavailable
- internal - 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: errors:
type: array type: array
description: Per-field failures. Present only when `code` is `validation`. 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 type: boolean
description: True until the first admin user has been created. description: True until the first admin user has been created.
loginMethods: loginMethods:
type: array $ref: ./LoginMethods.yaml
description: Login methods this server accepts. New methods may be added; clients ignore values they do not recognise.
items:
type: string
enum: [password]

View file

@ -4,7 +4,7 @@ info:
version: 1.0.0 version: 1.0.0
description: | description: |
Navidrome API v1. Spec-first, additive within v1. Clients discover implemented 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 Enums are open: new values may be added to any enum within v1. Clients must
accept values they do not recognise instead of failing. 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 `HEAD` is accepted wherever `GET` is. A `405` response lists the allowed methods
in its `Allow` header. 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: license:
name: GPL-3.0 name: GPL-3.0
url: https://www.gnu.org/licenses/gpl-3.0.html url: https://www.gnu.org/licenses/gpl-3.0.html
@ -23,17 +27,32 @@ servers:
tags: tags:
- name: server - name: server
description: Server discovery and the published OpenAPI document. description: Server discovery and the published OpenAPI document.
- name: auth
description: Grants and login methods.
paths: paths:
/server: /server:
$ref: ./paths/server.yaml $ref: ./paths/server.yaml
/capabilities:
$ref: ./paths/capabilities.yaml
/openapi.json: /openapi.json:
$ref: ./paths/openapi.yaml#/json $ref: ./paths/openapi.yaml#/json
/openapi.yaml: /openapi.yaml:
$ref: ./paths/openapi.yaml#/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: components:
securitySchemes: securitySchemes:
bearerAuth: bearerAuth:
type: http type: http
scheme: bearer scheme: bearer
bearerFormat: JWT description: "Grant secret from a login method (`POST /auth/login`, `POST /auth/setup`). Opaque. The required scope is in each operation's `x-scope`."
description: Short-lived access token minted from a device grant. Not yet applied to any operation.

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

View file

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

View file

@ -342,7 +342,7 @@ func selectedKinds(kinds, sources []string, all bool) ([]model.Kind, error) {
return artwork.ReprocessKinds, nil return artwork.ReprocessKinds, nil
} }
if len(kinds) == 0 { if len(kinds) == 0 {
return nil, 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 parseAll(kinds, func(s string) (model.Kind, error) {
return parseArtworkKind(s, artwork.ReprocessKinds) return parseArtworkKind(s, artwork.ReprocessKinds)
@ -416,7 +416,7 @@ func needsImageAgents(kinds []model.Kind) bool {
// configuredAgents names the agents in priority order; one absent from it can never supply an image. // configuredAgents names the agents in priority order; one absent from it can never supply an image.
func configuredAgents() []string { func configuredAgents() []string {
var names []string var names []string
for name := range strings.SplitSeq(conf.Server.Agents, ",") { for name := range strings.SplitSeq(conf.Server().Agents, ",") {
if name = strings.TrimSpace(name); name != "" { if name = strings.TrimSpace(name); name != "" {
names = append(names, name) names = append(names, name)
} }
@ -428,7 +428,7 @@ func promptConfirm(in io.Reader, verb string) confirmFunc {
return func(out io.Writer, total, external int64) bool { return func(out io.Writer, total, external int64) bool {
var cost string var cost string
if external > 0 { if external > 0 {
cost = fmt.Sprintf(" %s", externalLookupLine(external)) cost = " " + externalLookupLine(external)
} }
fmt.Fprintf(out, "\nThis will %s %d items.%s Continue? [y/N] ", verb, total, cost) fmt.Fprintf(out, "\nThis will %s %d items.%s Continue? [y/N] ", verb, total, cost)
var answer string var answer string
@ -559,7 +559,7 @@ func cancelSelection(kinds, priorities []string, all bool) ([]model.Kind, []int,
return nil, nil, nil return nil, nil, nil
} }
if len(kinds) == 0 && len(priorities) == 0 { if len(kinds) == 0 && len(priorities) == 0 {
return nil, nil, 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. // RefreshableKinds, not ReprocessKinds: media files are queued, so --kind must reach them.
outKinds, err := parseAll(kinds, func(s string) (model.Kind, error) { outKinds, err := parseAll(kinds, func(s string) (model.Kind, error) {
@ -811,13 +811,13 @@ func explainResult(source string, steps []artwork.TraceStep) string {
func explainConfig(kind model.Kind) (name, value string) { func explainConfig(kind model.Kind) (name, value string) {
switch kind { switch kind {
case model.KindArtistArtwork: case model.KindArtistArtwork:
return "ArtistArtPriority", conf.Server.ArtistArtPriority return "ArtistArtPriority", conf.Server().ArtistArtPriority
case model.KindAlbumArtwork: case model.KindAlbumArtwork:
return "CoverArtPriority", conf.Server.CoverArtPriority return "CoverArtPriority", conf.Server().CoverArtPriority
case model.KindDiscArtwork: case model.KindDiscArtwork:
return "DiscArtPriority", conf.Server.DiscArtPriority return "DiscArtPriority", conf.Server().DiscArtPriority
case model.KindMediaFileArtwork: case model.KindMediaFileArtwork:
return "EnableMediaFileCoverArt", strconv.FormatBool(conf.Server.EnableMediaFileCoverArt) return "EnableMediaFileCoverArt", strconv.FormatBool(conf.Server().EnableMediaFileCoverArt)
} }
return "", "" return "", ""
} }
@ -1002,7 +1002,7 @@ func runExplain(ctx context.Context, args []string) {
if kind == model.KindArtistArtwork || kind == model.KindAlbumArtwork { if kind == model.KindArtistArtwork || kind == model.KindAlbumArtwork {
mgr := loadPluginAgents(ctx, explainLive) mgr := loadPluginAgents(ctx, explainLive)
defer func() { _ = mgr.Stop() }() defer func() { _ = mgr.Stop() }()
rep.agents = explainAgents(conf.Server.Agents, availableImageAgents(ds, mgr, kind)) rep.agents = explainAgents(conf.Server().Agents, availableImageAgents(ds, mgr, kind))
} }
switch { switch {
case rep.walked: case rep.walked:

View file

@ -8,11 +8,12 @@ import (
"time" "time"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core/artwork"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model" "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/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
) )
@ -55,13 +56,13 @@ var _ = Describe("parseArtworkKind", func() {
}) })
var _ = Describe("resolveArtworkTargets", func() { var _ = Describe("resolveArtworkTargets", func() {
var ds *tests.MockDataStore var ds model.DataStore
ctx := context.Background() var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
artists := tests.CreateMockArtistRepo() ctx = GinkgoT().Context()
artists.SetData(model.Artists{{ID: "artist1"}}) ds = persistence.New(db.Db())
ds = &tests.MockDataStore{MockedArtist: artists} persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "artist1", Name: "artist1"})
}) })
It("accepts the explicit <kind> <id> leader shared by every id", func() { It("accepts the explicit <kind> <id> leader shared by every id", func() {
@ -226,8 +227,7 @@ var _ = Describe("formatExplain", func() {
var rep explainReport var rep explainReport
BeforeEach(func() { BeforeEach(func() {
DeferCleanup(configtest.SetupConfig()) conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external, artist.*" })
conf.Server.ArtistArtPriority = "external, artist.*"
rep = explainReport{ rep = explainReport{
kind: model.KindArtistArtwork, kind: model.KindArtistArtwork,
id: "ar-1", id: "ar-1",
@ -289,7 +289,7 @@ var _ = Describe("formatExplain", func() {
}) })
It("says a kind that does not walk a chain has no chain, without an empty table", func() { It("says a kind that does not walk a chain has no chain, without an empty table", func() {
conf.Server.CoverArtPriority = "cover.*, embedded" conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*, embedded" })
rep.kind = model.KindPlaylistArtwork rep.kind = model.KindPlaylistArtwork
rep.steps = nil rep.steps = nil
rep.agents = "" rep.agents = ""
@ -305,7 +305,7 @@ var _ = Describe("formatExplain", func() {
}) })
It("says disc artwork keeps no state instead of reporting it as unresolved state", func() { It("says disc artwork keeps no state instead of reporting it as unresolved state", func() {
conf.Server.DiscArtPriority = "cover.jpg, embedded" conf.Update(func(c *conf.Options) { c.DiscArtPriority = "cover.jpg, embedded" })
rep = explainReport{ rep = explainReport{
kind: model.KindDiscArtwork, id: "al-1:2", name: "OK Computer (disc 2)", kind: model.KindDiscArtwork, id: "al-1:2", name: "OK Computer (disc 2)",
steps: []artwork.TraceStep{{Candidate: "cover.jpg", Outcome: "hit", Detail: "/music/cover.jpg"}}, steps: []artwork.TraceStep{{Candidate: "cover.jpg", Outcome: "hit", Detail: "/music/cover.jpg"}},
@ -387,7 +387,7 @@ var _ = Describe("formatExplain", func() {
}) })
It("reports the setting that governs media file artwork", func() { It("reports the setting that governs media file artwork", func() {
conf.Server.EnableMediaFileCoverArt = false conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false })
rep = explainReport{ rep = explainReport{
kind: model.KindMediaFileArtwork, id: "mf-1", name: "Airbag", kind: model.KindMediaFileArtwork, id: "mf-1", name: "Airbag",
walked: true, walked: true,
@ -406,9 +406,10 @@ var _ = Describe("formatExplain", func() {
var _ = Describe("explainConfig", func() { var _ = Describe("explainConfig", func() {
BeforeEach(func() { BeforeEach(func() {
DeferCleanup(configtest.SetupConfig()) conf.Update(func(c *conf.Options) {
conf.Server.DiscArtPriority = "cover.jpg" c.DiscArtPriority = "cover.jpg"
conf.Server.EnableMediaFileCoverArt = true c.EnableMediaFileCoverArt = true
})
}) })
DescribeTable("names the setting that decides where a kind's artwork comes from", DescribeTable("names the setting that decides where a kind's artwork comes from",
@ -425,9 +426,9 @@ var _ = Describe("explainConfig", func() {
var _ = Describe("artwork refresh command", func() { var _ = Describe("artwork refresh command", func() {
It("requires at least one argument", func() { It("requires at least one argument", func() {
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{})).To(HaveOccurred()) Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{})).ToNot(Succeed())
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"id1"})).ToNot(HaveOccurred()) Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"id1"})).To(Succeed())
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"ar", "id1"})).ToNot(HaveOccurred()) Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"ar", "id1"})).To(Succeed())
}) })
}) })
@ -475,7 +476,10 @@ var _ = Describe("artwork reprocess selection", func() {
}) })
var _ = Describe("explain/reprocess source round trip", 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 reads back the Source line explain printed, as an operator would copy it.
storedSource := func(out string) string { storedSource := func(out string) string {
@ -490,8 +494,8 @@ var _ = Describe("explain/reprocess source round trip", func() {
} }
It("names the absent state as reprocess --source accepts it", func() { It("names the absent state as reprocess --source accepts it", func() {
ds := &tests.MockDataStore{} ds := persistence.New(db.Db())
art := ds.Artwork().(*tests.MockArtworkRepo) art := ds.Artwork()
Expect(art.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: model.KindArtistArtwork.Prefix(), Expect(art.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: model.KindArtistArtwork.Prefix(),
ItemID: "ar-1", ImageType: model.ImageTypePrimary})).To(Succeed()) ItemID: "ar-1", ImageType: model.ImageTypePrimary})).To(Succeed())
@ -562,12 +566,12 @@ var _ = Describe("confirmUnlessYes", func() {
}) })
var _ = Describe("reprocessArtwork", func() { var _ = Describe("reprocessArtwork", func() {
var ds *tests.MockDataStore var ds model.DataStore
var art *tests.MockArtworkRepo var art model.ArtworkRepository
var queue *tests.MockArtworkQueueRepo var queue model.ArtworkQueueRepository
var out strings.Builder var out strings.Builder
var imageAgents artwork.ImageAgentCount var imageAgents artwork.ImageAgentCount
ctx := context.Background() var ctx context.Context
kinds := []model.Kind{model.KindArtistArtwork, model.KindAlbumArtwork} kinds := []model.Kind{model.KindArtistArtwork, model.KindAlbumArtwork}
accept := func(io.Writer, int64, int64) bool { return true } accept := func(io.Writer, int64, int64) bool { return true }
decline := func(io.Writer, int64, int64) bool { return false } decline := func(io.Writer, int64, int64) bool { return false }
@ -578,14 +582,16 @@ var _ = Describe("reprocessArtwork", func() {
} }
BeforeEach(func() { BeforeEach(func() {
DeferCleanup(configtest.SetupConfig()) ctx = GinkgoT().Context()
conf.Server.CoverArtPriority = "cover.*, external" conf.Update(func(c *conf.Options) {
conf.Server.ArtistArtPriority = "artist.*, external" c.CoverArtPriority = "cover.*, external"
conf.Server.EnableM3UExternalAlbumArt = false c.ArtistArtPriority = "artist.*, external"
c.EnableM3UExternalAlbumArt = false
})
imageAgents = artwork.ImageAgentCount{Artist: 1, Album: 1} imageAgents = artwork.ImageAgentCount{Artist: 1, Album: 1}
ds = &tests.MockDataStore{} ds = persistence.New(db.Db())
art = ds.Artwork().(*tests.MockArtworkRepo) art = ds.Artwork()
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo) queue = ds.ArtworkQueue()
out.Reset() out.Reset()
put(model.KindArtistArtwork, "ar-1", "external:deezer") put(model.KindArtistArtwork, "ar-1", "external:deezer")
put(model.KindArtistArtwork, "ar-2", "") put(model.KindArtistArtwork, "ar-2", "")
@ -714,7 +720,7 @@ var _ = Describe("reprocessArtwork", func() {
}) })
It("says so when the selection needs no external lookup", func() { It("says so when the selection needs no external lookup", func() {
conf.Server.CoverArtPriority = "cover.*" conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*" })
put(model.KindPlaylistArtwork, "pl-1", "playlist") put(model.KindPlaylistArtwork, "pl-1", "playlist")
Expect(reprocessArtwork(ctx, ds, []model.Kind{model.KindPlaylistArtwork}, nil, imageAgents, true, accept, &out)).To(Succeed()) Expect(reprocessArtwork(ctx, ds, []model.Kind{model.KindPlaylistArtwork}, nil, imageAgents, true, accept, &out)).To(Succeed())
@ -723,8 +729,10 @@ var _ = Describe("reprocessArtwork", func() {
}) })
It("counts playlists as external cost when the m3u image fetch is enabled", func() { It("counts playlists as external cost when the m3u image fetch is enabled", func() {
conf.Server.CoverArtPriority = "cover.*" conf.Update(func(c *conf.Options) {
conf.Server.EnableM3UExternalAlbumArt = true c.CoverArtPriority = "cover.*"
c.EnableM3UExternalAlbumArt = true
})
put(model.KindPlaylistArtwork, "pl-1", "playlist") put(model.KindPlaylistArtwork, "pl-1", "playlist")
var external int64 var external int64
capture := func(_ io.Writer, _, e int64) bool { external = e; return false } capture := func(_ io.Writer, _, e int64) bool { external = e; return false }
@ -803,21 +811,22 @@ var _ = Describe("reprocessArtwork", func() {
var _ = Describe("artwork status command", func() { var _ = Describe("artwork status command", func() {
It("takes no arguments", func() { It("takes no arguments", func() {
Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{})).ToNot(HaveOccurred()) Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{})).To(Succeed())
Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{"x"})).To(HaveOccurred()) Expect(artworkStatusCmd.Args(artworkStatusCmd, []string{"x"})).ToNot(Succeed())
}) })
}) })
var _ = Describe("collectStatus", func() { var _ = Describe("collectStatus", func() {
var ds *tests.MockDataStore var ds model.DataStore
var art *tests.MockArtworkRepo var art model.ArtworkRepository
var queue *tests.MockArtworkQueueRepo var queue model.ArtworkQueueRepository
ctx := context.Background() var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
ds = &tests.MockDataStore{} ctx = GinkgoT().Context()
art = ds.Artwork().(*tests.MockArtworkRepo) ds = persistence.New(db.Db())
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo) art = ds.Artwork()
queue = ds.ArtworkQueue()
put := func(kind model.Kind, id, source, hash string, attempted time.Time) { put := func(kind model.Kind, id, source, hash string, attempted time.Time) {
Expect(art.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: kind.Prefix(), ItemID: id, Expect(art.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: kind.Prefix(), ItemID: id,
ImageType: model.ImageTypePrimary, Source: source, Hash: hash, AttemptedAt: attempted})).To(Succeed()) ImageType: model.ImageTypePrimary, Source: source, Hash: hash, AttemptedAt: attempted})).To(Succeed())
@ -963,18 +972,20 @@ var _ = Describe("formatStatus", func() {
}) })
var _ = Describe("refreshItems", func() { var _ = Describe("refreshItems", func() {
var ds *tests.MockDataStore var ds model.DataStore
var queue *tests.MockArtworkQueueRepo var queue model.ArtworkQueueRepository
var art *tests.MockArtworkRepo var art model.ArtworkRepository
var out strings.Builder var out strings.Builder
ctx := context.Background() var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
albums := tests.CreateMockAlbumRepo() ctx = GinkgoT().Context()
albums.SetData(model.Albums{{ID: "al-1"}, {ID: "al-3"}}) ds = persistence.New(db.Db())
ds = &tests.MockDataStore{MockedAlbum: albums} for _, id := range []string{"al-1", "al-3"} {
art = ds.Artwork().(*tests.MockArtworkRepo) Expect(ds.Album().Put(ctx, &model.Album{ID: id, Name: id, LibraryID: model.DefaultLibraryID})).To(Succeed())
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo) }
art = ds.Artwork()
queue = ds.ArtworkQueue()
out.Reset() out.Reset()
}) })
@ -1012,10 +1023,11 @@ var _ = Describe("refreshItems", func() {
var _ = Describe("needsImageAgents", func() { var _ = Describe("needsImageAgents", func() {
BeforeEach(func() { BeforeEach(func() {
DeferCleanup(configtest.SetupConfig()) conf.Update(func(c *conf.Options) {
conf.Server.CoverArtPriority = "cover.*, external" c.CoverArtPriority = "cover.*, external"
conf.Server.ArtistArtPriority = "artist.*, external" c.ArtistArtPriority = "artist.*, external"
conf.Server.EnableM3UExternalAlbumArt = false c.EnableM3UExternalAlbumArt = false
})
}) })
It("is false for a selection no agent can serve", func() { It("is false for a selection no agent can serve", func() {
@ -1033,24 +1045,25 @@ var _ = Describe("needsImageAgents", func() {
}) })
It("is false once the chains no longer reach an agent", func() { It("is false once the chains no longer reach an agent", func() {
conf.Server.CoverArtPriority = "cover.*" conf.Update(func(c *conf.Options) {
conf.Server.ArtistArtPriority = "artist.*" c.CoverArtPriority = "cover.*"
c.ArtistArtPriority = "artist.*"
})
Expect(needsImageAgents(artwork.ReprocessKinds)).To(BeFalse()) Expect(needsImageAgents(artwork.ReprocessKinds)).To(BeFalse())
}) })
}) })
var _ = Describe("configuredAgents", func() { var _ = Describe("configuredAgents", func() {
BeforeEach(func() { DeferCleanup(configtest.SetupConfig()) })
It("splits and trims the configured list", func() { It("splits and trims the configured list", func() {
conf.Server.Agents = "lastfm, spotify ,deezer" conf.Update(func(c *conf.Options) { c.Agents = "lastfm, spotify ,deezer" })
Expect(configuredAgents()).To(Equal([]string{"lastfm", "spotify", "deezer"})) Expect(configuredAgents()).To(Equal([]string{"lastfm", "spotify", "deezer"}))
}) })
// An empty name would match no plugin, but it also must not make the list look non-empty: // An empty name would match no plugin, but it also must not make the list look non-empty:
// LoadPlugins treats an empty list as "load nothing". // LoadPlugins treats an empty list as "load nothing".
It("drops empty entries rather than passing a name nothing can match", func() { It("drops empty entries rather than passing a name nothing can match", func() {
conf.Server.Agents = " , ," conf.Update(func(c *conf.Options) { c.Agents = " , ," })
Expect(configuredAgents()).To(BeEmpty()) Expect(configuredAgents()).To(BeEmpty())
}) })
}) })
@ -1136,16 +1149,17 @@ var _ = Describe("artwork cancel selection", func() {
}) })
var _ = Describe("cancelArtwork", func() { var _ = Describe("cancelArtwork", func() {
var ds *tests.MockDataStore var ds model.DataStore
var queue *tests.MockArtworkQueueRepo var queue model.ArtworkQueueRepository
var out strings.Builder var out strings.Builder
ctx := context.Background() var ctx context.Context
accept := func(io.Writer, int64, int64) bool { return true } accept := func(io.Writer, int64, int64) bool { return true }
decline := func(io.Writer, int64, int64) bool { return false } decline := func(io.Writer, int64, int64) bool { return false }
BeforeEach(func() { BeforeEach(func() {
ds = &tests.MockDataStore{} ctx = GinkgoT().Context()
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo) ds = persistence.New(db.Db())
queue = ds.ArtworkQueue()
out.Reset() out.Reset()
Expect(queue.Enqueue(ctx, Expect(queue.Enqueue(ctx,
model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar-1", ImageType: model.ImageTypePrimary, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar-1", ImageType: model.ImageTypePrimary,
@ -1200,7 +1214,18 @@ var _ = Describe("cancelArtwork", func() {
}) })
It("reports a queue read failure instead of reporting nothing to cancel", 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"))) 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

@ -15,6 +15,7 @@ var (
backupCount int backupCount int
backupDir string backupDir string
force bool force bool
integrityCheck bool
restorePath string restorePath string
) )
@ -31,6 +32,7 @@ func init() {
restoreCommand.Flags().StringVarP(&restorePath, "backup-file", "b", "", "file name of the backup database to restore (resolved against the backup directory unless it is an absolute path)") restoreCommand.Flags().StringVarP(&restorePath, "backup-file", "b", "", "file name of the backup database to restore (resolved against the backup directory unless it is an absolute path)")
restoreCommand.Flags().BoolVarP(&force, "force", "f", false, "bypass restore warning") restoreCommand.Flags().BoolVarP(&force, "force", "f", false, "bypass restore warning")
restoreCommand.Flags().BoolVarP(&integrityCheck, "integrity-check", "i", false, "check the backup file with a full integrity check before restoring. Finds more kinds of damage, but takes longer")
_ = restoreCommand.MarkFlagRequired("backup-file") _ = restoreCommand.MarkFlagRequired("backup-file")
backupRoot.AddCommand(restoreCommand) backupRoot.AddCommand(restoreCommand)
} }
@ -73,7 +75,7 @@ var (
func runBackup(ctx context.Context) { func runBackup(ctx context.Context) {
if backupDir != "" { if backupDir != "" {
conf.Server.Backup.Path = conf.NewDir(backupDir) conf.Update(func(c *conf.Options) { c.Backup.Path = conf.NewDir(backupDir) })
} }
requireExistingDB() requireExistingDB()
@ -81,7 +83,7 @@ func runBackup(ctx context.Context) {
start := time.Now() start := time.Now()
path, err := db.Backup(ctx) path, err := db.Backup(ctx)
if err != nil { if err != nil {
log.Fatal("Error backing up database", "backupPath", conf.Server.Backup.Path, err) log.Fatal("Error backing up database", "backupPath", conf.Server().Backup.Path, err)
} }
elapsed := time.Since(start) elapsed := time.Since(start)
@ -89,15 +91,16 @@ func runBackup(ctx context.Context) {
} }
func runPrune(ctx context.Context) { func runPrune(ctx context.Context) {
conf.Update(func(c *conf.Options) {
if backupDir != "" { if backupDir != "" {
conf.Server.Backup.Path = conf.NewDir(backupDir) c.Backup.Path = conf.NewDir(backupDir)
} }
if backupCount != -1 { if backupCount != -1 {
conf.Server.Backup.Count = backupCount c.Backup.Count = backupCount
} }
})
if conf.Server.Backup.Count == 0 && !force && !confirmYES("Warning: pruning ALL backups") { if conf.Server().Backup.Count == 0 && !force && !confirmYES("Warning: pruning ALL backups") {
log.Warn("Prune cancelled") log.Warn("Prune cancelled")
return return
} }
@ -107,7 +110,7 @@ func runPrune(ctx context.Context) {
start := time.Now() start := time.Now()
count, err := db.Prune(ctx) count, err := db.Prune(ctx)
if err != nil { if err != nil {
log.Fatal("Error pruning database", "backupPath", conf.Server.Backup.Path, err) log.Fatal("Error pruning database", "backupPath", conf.Server().Backup.Path, err)
} }
elapsed := time.Since(start) elapsed := time.Since(start)
@ -122,9 +125,9 @@ func runRestore(ctx context.Context) {
// `backup create` writes to. Without this, the value was treated as relative // `backup create` writes to. Without this, the value was treated as relative
// to the working directory, where the file does not exist. // to the working directory, where the file does not exist.
if !filepath.IsAbs(restorePath) { if !filepath.IsAbs(restorePath) {
backupPath, err := conf.Server.Backup.Path.Path() backupPath, err := conf.Server().Backup.Path.Path()
if err != nil { if err != nil {
log.Fatal("Backup directory not available", "backupPath", conf.Server.Backup.Path, err) log.Fatal("Backup directory not available", "backupPath", conf.Server().Backup.Path, err)
return return
} }
restorePath = filepath.Join(backupPath, restorePath) restorePath = filepath.Join(backupPath, restorePath)
@ -136,7 +139,7 @@ func runRestore(ctx context.Context) {
} }
start := time.Now() start := time.Now()
err := db.Restore(ctx, restorePath) err := db.Restore(ctx, restorePath, integrityCheck)
if err != nil { if err != nil {
log.Fatal("Error restoring database", "backupFile", restorePath, err) log.Fatal("Error restoring database", "backupFile", restorePath, err)
} }

View file

@ -3,7 +3,9 @@ package cmd
import ( import (
"testing" "testing"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -12,6 +14,10 @@ import (
func TestCmd(t *testing.T) { func TestCmd(t *testing.T) {
tests.Init(t, false) tests.Init(t, false)
log.SetLevel(log.LevelFatal) log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail) RegisterFailHandler(Fail)
RunSpecs(t, "Cmd Suite") 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 // 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. // search table so IsFTSCorruptionOnly matches, plus a parent/child pair for FK checks.
BeforeEach(func() { BeforeEach(func() {
ctx = context.Background() ctx = GinkgoT().Context()
dbPath = filepath.Join(GinkgoT().TempDir(), "doctor.db") dbPath = filepath.Join(GinkgoT().TempDir(), "doctor.db")
reopen = func() { reopen = func() {
var err error var err error

View file

@ -1,13 +1,17 @@
package cmd package cmd
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"path/filepath"
"strings" "strings"
"github.com/navidrome/navidrome/core" "github.com/navidrome/navidrome/core"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
"github.com/pelletier/go-toml/v2" "github.com/pelletier/go-toml/v2"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
@ -28,7 +32,7 @@ var inspectCmd = &cobra.Command{
Long: "Show file tags as seen by Navidrome", Long: "Show file tags as seen by Navidrome",
Args: cobra.MinimumNArgs(1), Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
runInspector(args) runInspector(cmd.Context(), args)
}, },
} }
@ -46,27 +50,33 @@ func prettyMarshal(v any) ([]byte, error) {
out := v.([]core.InspectOutput) out := v.([]core.InspectOutput)
var res strings.Builder var res strings.Builder
for i := range out { for i := range out {
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) 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) 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 return []byte(res.String()), nil
} }
func runInspector(args []string) { func runInspector(ctx context.Context, args []string) {
marshal := marshalers[format] marshal := marshalers[format]
if marshal == nil { if marshal == nil {
log.Fatal("Invalid format", "format", format) log.Fatal("Invalid format", "format", format)
} }
libs := loadLibraries(ctx)
matcher := model.NewLibraryMatcher(libs)
var out []core.InspectOutput var out []core.InspectOutput
for _, filePath := range args { for _, filePath := range args {
if !model.IsAudioFile(filePath) { if !model.IsAudioFile(filePath) {
log.Warn("Not an audio file", "file", filePath) log.Warn("Not an audio file", "file", filePath)
continue continue
} }
output, err := core.Inspect(filePath, 1, "") lib, ok := libraryForFile(matcher, filePath)
if !ok && len(libs) > 0 {
log.Warn("File is not in any library, using the global PID config", "file", filePath)
}
output, err := core.Inspect(filePath, lib, "")
if err != nil { if err != nil {
log.Warn("Unable to process file", "file", filePath, "error", err) log.Warn("Unable to process file", "file", filePath, "error", err)
continue continue
@ -77,3 +87,33 @@ func runInspector(args []string) {
data, _ := marshal(out) data, _ := marshal(out)
fmt.Println(string(data)) fmt.Println(string(data))
} }
// loadLibraries reads the libraries, so each file gets its library's PID config. It never creates a DB.
func loadLibraries(ctx context.Context) model.Libraries {
if dbFile, ok := existingDBFile(); !ok {
log.Warn(ctx, "No database found, using the global PID config", "path", dbFile)
return nil
}
defer db.Init(ctx)()
libs, err := persistence.New(db.Db()).Library().GetAll(ctx)
if err != nil {
log.Warn(ctx, "Could not load libraries, using the global PID config", err)
return nil
}
for i := range libs {
if absPath, err := filepath.Abs(libs[i].Path); err == nil {
libs[i].Path = absPath
}
}
return libs
}
// libraryForFile falls back to the default library with no overrides, which uses the global PID config.
func libraryForFile(matcher *model.LibraryMatcher, filePath string) (model.Library, bool) {
if absPath, err := filepath.Abs(filePath); err == nil {
if lib, ok := matcher.FindLibrary(absPath); ok {
return lib, true
}
}
return model.Library{ID: model.DefaultLibraryID}, false
}

57
cmd/inspect_test.go Normal file
View file

@ -0,0 +1,57 @@
package cmd
import (
"os"
"path/filepath"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/model"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("inspect", func() {
Describe("libraryForFile", func() {
var matcher *model.LibraryMatcher
var root string
BeforeEach(func() {
root = GinkgoT().TempDir()
cwd, err := os.Getwd()
Expect(err).ToNot(HaveOccurred())
matcher = model.NewLibraryMatcher(model.Libraries{
{ID: 1, Path: filepath.Join(root, "music")},
{ID: 2, Path: filepath.Join(cwd, "loose"), PIDAlbum: "folder"},
})
})
It("returns the library that contains an absolute path", func() {
lib, ok := libraryForFile(matcher, filepath.Join(root, "music", "album", "track.mp3"))
Expect(ok).To(BeTrue())
Expect(lib.ID).To(Equal(1))
})
It("resolves a relative path against the working directory", func() {
lib, ok := libraryForFile(matcher, filepath.Join("loose", "track.mp3"))
Expect(ok).To(BeTrue())
Expect(lib.PIDAlbum).To(Equal("folder"))
})
It("falls back to the default library without overrides", func() {
lib, ok := libraryForFile(matcher, filepath.Join(root, "elsewhere", "track.mp3"))
Expect(ok).To(BeFalse())
Expect(lib).To(Equal(model.Library{ID: model.DefaultLibraryID}))
})
})
Describe("loadLibraries", func() {
It("does not create a database when there is none", func() {
dbFile := filepath.Join(GinkgoT().TempDir(), "navidrome.db")
conf.Update(func(c *conf.Options) { c.DbPath = dbFile + "?_journal_mode=WAL" })
Expect(loadLibraries(GinkgoT().Context())).To(BeNil())
Expect(dbFile).ToNot(BeAnExistingFile())
})
})
})

View file

@ -94,7 +94,10 @@ func writeMissingList(w io.Writer, format string, mfs model.MediaFileCursor) err
if err != nil { if err != nil {
return err 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) _, _ = fmt.Fprintf(bw, "%s%s", sep, j)
sep = "," sep = ","
} }

View file

@ -247,7 +247,10 @@ func runList(ctx context.Context) {
display[idx].Public = playlist.Public 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) fmt.Printf("%s\n", j)
} }
} }

View file

@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/csv" "encoding/csv"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@ -307,7 +308,7 @@ func formatPluginList(list model.Plugins, format string) (string, error) {
_ = w.Write([]string{"id", "name", "version", "enabled", "last error"}) _ = w.Write([]string{"id", "name", "version", "enabled", "last error"})
for _, p := range list { for _, p := range list {
name, version := manifestSummary(p) name, version := manifestSummary(p)
_ = w.Write([]string{p.ID, name, version, fmt.Sprintf("%t", p.Enabled), p.LastError}) _ = w.Write([]string{p.ID, name, version, strconv.FormatBool(p.Enabled), p.LastError})
} }
w.Flush() w.Flush()
return sb.String(), w.Error() return sb.String(), w.Error()
@ -343,7 +344,7 @@ func runPluginList(ctx context.Context) {
// requirePluginsEnabled gates DB/manager-backed commands; off-disk .ndp // requirePluginsEnabled gates DB/manager-backed commands; off-disk .ndp
// inspection deliberately skips this so it works without a configured server. // inspection deliberately skips this so it works without a configured server.
func requirePluginsEnabled(ctx context.Context) { func requirePluginsEnabled(ctx context.Context) {
if !conf.Server.Plugins.Enabled { if !conf.Server().Plugins.Enabled {
log.Fatal(ctx, "Plugin system is disabled (set Plugins.Enabled to use this command)") log.Fatal(ctx, "Plugin system is disabled (set Plugins.Enabled to use this command)")
} }
} }
@ -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 { func applyPluginEdit(ctx context.Context, mgr pluginManager, cur *model.Plugin, opts pluginEditOptions) error {
if opts.config == nil && opts.users == nil && opts.allUsers == nil && if opts.config == nil && opts.users == nil && opts.allUsers == nil &&
opts.libraries == nil && opts.allLibraries == nil && opts.writeAccess == nil { opts.libraries == nil && opts.allLibraries == nil && opts.writeAccess == nil {
return 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 id := cur.ID
if opts.config != nil { if opts.config != nil {
@ -499,18 +500,18 @@ func usersToJSON(value string) (string, error) {
} }
if strings.HasPrefix(strings.TrimSpace(value), "[") { if strings.HasPrefix(strings.TrimSpace(value), "[") {
if !json.Valid([]byte(value)) { if !json.Valid([]byte(value)) {
return "", fmt.Errorf("invalid JSON in --users") return "", errors.New("invalid JSON in --users")
} }
return value, nil return value, nil
} }
var names []string var names []string
for _, u := range strings.Split(value, ",") { for u := range strings.SplitSeq(value, ",") {
if u = strings.TrimSpace(u); u != "" { if u = strings.TrimSpace(u); u != "" {
names = append(names, u) names = append(names, u)
} }
} }
b, _ := json.Marshal(names) b, err := json.Marshal(names)
return string(b), nil return string(b), err
} }
// librariesToJSON accepts either a JSON array (starts with '[') or a // 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 strings.HasPrefix(strings.TrimSpace(value), "[") {
if !json.Valid([]byte(value)) { if !json.Valid([]byte(value)) {
return "", fmt.Errorf("invalid JSON in --libraries") return "", errors.New("invalid JSON in --libraries")
} }
return value, nil return value, nil
} }
ids := []int{} ids := []int{}
for _, l := range strings.Split(value, ",") { for l := range strings.SplitSeq(value, ",") {
if l = strings.TrimSpace(l); l != "" { if l = strings.TrimSpace(l); l != "" {
id, err := strconv.Atoi(l) id, err := strconv.Atoi(l)
if err != nil { if err != nil {
@ -535,8 +536,8 @@ func librariesToJSON(value string) (string, error) {
ids = append(ids, id) ids = append(ids, id)
} }
} }
b, _ := json.Marshal(ids) b, err := json.Marshal(ids)
return string(b), nil return string(b), err
} }
var pluginRescanCmd = &cobra.Command{ var pluginRescanCmd = &cobra.Command{

View file

@ -65,16 +65,21 @@ var _ = Describe("formatPluginList", func() {
}) })
var _ = Describe("enable/disable plugin", func() { var _ = Describe("enable/disable plugin", func() {
var ctx context.Context
BeforeEach(func() {
ctx = GinkgoT().Context()
})
It("calls EnablePlugin on the manager", func() { It("calls EnablePlugin on the manager", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
err := enablePlugin(context.Background(), mgr, "alpha") err := enablePlugin(ctx, mgr, "alpha")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(mgr.EnablePluginCalls).To(Equal([]string{"alpha"})) Expect(mgr.EnablePluginCalls).To(Equal([]string{"alpha"}))
}) })
It("calls DisablePlugin on the manager", func() { It("calls DisablePlugin on the manager", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
err := disablePlugin(context.Background(), mgr, "beta") err := disablePlugin(ctx, mgr, "beta")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(mgr.DisablePluginCalls).To(Equal([]string{"beta"})) Expect(mgr.DisablePluginCalls).To(Equal([]string{"beta"}))
}) })
@ -82,14 +87,16 @@ var _ = Describe("enable/disable plugin", func() {
var _ = Describe("applyPluginEdit", func() { var _ = Describe("applyPluginEdit", func() {
var cur *model.Plugin var cur *model.Plugin
var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context()
cur = &model.Plugin{ID: "alpha", Users: `["bob"]`, Libraries: `[1,2]`, AllowWriteAccess: true} cur = &model.Plugin{ID: "alpha", Users: `["bob"]`, Libraries: `[1,2]`, AllowWriteAccess: true}
}) })
It("validates then updates config when config is provided", func() { It("validates then updates config when config is provided", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
cfg := `{"key":"val"}` 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(err).ToNot(HaveOccurred())
Expect(mgr.ValidatePluginConfigCalls).To(HaveLen(1)) Expect(mgr.ValidatePluginConfigCalls).To(HaveLen(1))
Expect(mgr.ValidatePluginConfigCalls[0].ConfigJSON).To(Equal(cfg)) Expect(mgr.ValidatePluginConfigCalls[0].ConfigJSON).To(Equal(cfg))
@ -100,7 +107,7 @@ var _ = Describe("applyPluginEdit", func() {
It("updates users with allUsers flag", func() { It("updates users with allUsers flag", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
all := true all := true
err := applyPluginEdit(context.Background(), mgr, cur, err := applyPluginEdit(ctx, mgr, cur,
pluginEditOptions{allUsers: &all}) pluginEditOptions{allUsers: &all})
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(mgr.UpdatePluginUsersCalls).To(HaveLen(1)) Expect(mgr.UpdatePluginUsersCalls).To(HaveLen(1))
@ -111,7 +118,7 @@ var _ = Describe("applyPluginEdit", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
all := true all := true
wr := true wr := true
err := applyPluginEdit(context.Background(), mgr, cur, err := applyPluginEdit(ctx, mgr, cur,
pluginEditOptions{allLibraries: &all, writeAccess: &wr}) pluginEditOptions{allLibraries: &all, writeAccess: &wr})
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(mgr.UpdatePluginLibrariesCalls).To(HaveLen(1)) 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() { It("preserves existing fields when only the write-access flag changes", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
no := false no := false
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{writeAccess: &no}) err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{writeAccess: &no})
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(mgr.UpdatePluginLibrariesCalls).To(HaveLen(1)) Expect(mgr.UpdatePluginLibrariesCalls).To(HaveLen(1))
Expect(mgr.UpdatePluginLibrariesCalls[0].LibrariesJSON).To(Equal(`[1,2]`)) // not wiped 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() { It("preserves existing users when only the all-users flag changes", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
all := true all := true
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{allUsers: &all}) err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{allUsers: &all})
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["bob"]`)) // not wiped 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() { It("parses a comma-separated users value into a JSON array", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
users := "alice, bob" 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(err).ToNot(HaveOccurred())
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["alice","bob"]`)) 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() { It("passes a JSON-array users value through unchanged", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
users := `["alice","bob"]` 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(err).ToNot(HaveOccurred())
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["alice","bob"]`)) 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() { It("rejects a malformed JSON-array users value", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
users := `["alice"` users := `["alice"`
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{users: &users}) err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{users: &users})
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(mgr.UpdatePluginUsersCalls).To(BeEmpty()) 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() { It("parses a comma-separated libraries value into a JSON array of ints", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
libs := "1, 2" 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(err).ToNot(HaveOccurred())
Expect(mgr.UpdatePluginLibrariesCalls[0].LibrariesJSON).To(Equal(`[1,2]`)) 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() { It("rejects a non-integer library ID", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
libs := "1,abc" 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(err).To(HaveOccurred())
Expect(mgr.UpdatePluginLibrariesCalls).To(BeEmpty()) Expect(mgr.UpdatePluginLibrariesCalls).To(BeEmpty())
}) })
@ -181,7 +188,7 @@ var _ = Describe("applyPluginEdit", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
cur.AllUsers = true cur.AllUsers = true
users := "alice" users := "alice"
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{users: &users}) err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{users: &users})
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["alice"]`)) Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["alice"]`))
Expect(mgr.UpdatePluginUsersCalls[0].AllUsers).To(BeFalse()) Expect(mgr.UpdatePluginUsersCalls[0].AllUsers).To(BeFalse())
@ -191,7 +198,7 @@ var _ = Describe("applyPluginEdit", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
cur.AllLibraries = true cur.AllLibraries = true
libs := "1" libs := "1"
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{libraries: &libs}) err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{libraries: &libs})
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(mgr.UpdatePluginLibrariesCalls[0].LibrariesJSON).To(Equal(`[1]`)) Expect(mgr.UpdatePluginLibrariesCalls[0].LibrariesJSON).To(Equal(`[1]`))
Expect(mgr.UpdatePluginLibrariesCalls[0].AllLibraries).To(BeFalse()) 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() { It("does nothing and errors when no fields are set", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{}) err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{})
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
}) })
It("aborts the config update when validation fails", func() { It("aborts the config update when validation fails", func() {
mgr := &tests.MockPluginManager{ValidateError: errors.New("bad config")} mgr := &tests.MockPluginManager{ValidateError: errors.New("bad config")}
cfg := `{"key":"val"}` 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(err).To(HaveOccurred())
Expect(mgr.ValidatePluginConfigCalls).To(HaveLen(1)) Expect(mgr.ValidatePluginConfigCalls).To(HaveLen(1))
Expect(mgr.UpdatePluginConfigCalls).To(BeEmpty()) Expect(mgr.UpdatePluginConfigCalls).To(BeEmpty())
@ -353,7 +360,7 @@ var _ = Describe("formatManifestInfo enriched text", func() {
var _ = Describe("rescanPlugins", func() { var _ = Describe("rescanPlugins", func() {
It("calls RescanPlugins on the manager", func() { It("calls RescanPlugins on the manager", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
err := rescanPlugins(context.Background(), mgr) err := rescanPlugins(GinkgoT().Context(), mgr)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(mgr.RescanPluginsCalls).To(Equal(1)) Expect(mgr.RescanPluginsCalls).To(Equal(1))
}) })

View file

@ -44,7 +44,9 @@ Complete documentation is available at https://www.navidrome.org/docs`,
preRun() preRun()
}, },
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
runNavidrome(cmd.Context()) if err := runNavidrome(cmd.Context()); err != nil {
log.Fatal("Fatal error in Navidrome. Aborting", err)
}
}, },
PostRun: func(cmd *cobra.Command, args []string) { PostRun: func(cmd *cobra.Command, args []string) {
postRun() postRun()
@ -76,12 +78,12 @@ func postRun() {
} }
// runNavidrome is the main entry point for the Navidrome server. It starts all the services and blocks. // runNavidrome is the main entry point for the Navidrome server. It starts all the services and blocks.
// If any of the services returns an error, it will log it and exit. If the process receives a signal to exit, // If any of the services returns an error, it stops the others and returns that error, so the caller can
// it will cancel the context and exit gracefully. // exit with a non-zero code. If the context is cancelled (a signal or a service stop), it returns nil.
func runNavidrome(ctx context.Context) { func runNavidrome(parentCtx context.Context) error {
defer db.Init(ctx)() defer db.Init(parentCtx)()
g, ctx := errgroup.WithContext(ctx) g, ctx := errgroup.WithContext(parentCtx)
g.Go(startServer(ctx)) g.Go(startServer(ctx))
g.Go(startSignaller(ctx)) g.Go(startSignaller(ctx))
g.Go(startScheduler(ctx)) g.Go(startScheduler(ctx))
@ -95,16 +97,18 @@ func runNavidrome(ctx context.Context) {
g.Go(startArtworkWorker(ctx, artworkWorker)) g.Go(startArtworkWorker(ctx, artworkWorker))
g.Go(scheduleArtworkHousekeeping(ctx, artworkWorker)) g.Go(scheduleArtworkHousekeeping(ctx, artworkWorker))
g.Go(runInitialScan(ctx)) g.Go(runInitialScan(ctx))
if conf.Server.Scanner.Enabled { if conf.Server().Scanner.Enabled {
g.Go(startScanWatcher(ctx)) g.Go(startScanWatcher(ctx))
g.Go(schedulePeriodicScan(ctx)) g.Go(schedulePeriodicScan(ctx))
} else { } else {
log.Warn(ctx, "Automatic Scanning is DISABLED") log.Warn(ctx, "Automatic Scanning is DISABLED")
} }
if err := g.Wait(); err != nil { // Errors caused by a normal shutdown are not failures
log.Error("Fatal error in Navidrome. Aborting", err) if err := g.Wait(); err != nil && parentCtx.Err() == nil {
return err
} }
return nil
} }
// mainContext returns a context that is cancelled when the process receives a signal to exit. // mainContext returns a context that is cancelled when the process receives a signal to exit.
@ -124,31 +128,31 @@ func startServer(ctx context.Context) func() error {
a.MountRouter("Native API", consts.URLPathNativeAPI, CreateNativeAPIRouter(ctx)) a.MountRouter("Native API", consts.URLPathNativeAPI, CreateNativeAPIRouter(ctx))
a.MountRouter("Subsonic API", consts.URLPathSubsonicAPI, CreateSubsonicAPIRouter(ctx)) a.MountRouter("Subsonic API", consts.URLPathSubsonicAPI, CreateSubsonicAPIRouter(ctx))
a.MountRouter("Public Endpoints", consts.URLPathPublic, CreatePublicRouter()) a.MountRouter("Public Endpoints", consts.URLPathPublic, CreatePublicRouter())
if conf.Server.LastFM.Enabled { if conf.Server().LastFM.Enabled {
a.MountRouter("LastFM Auth", consts.URLPathNativeAPI+"/lastfm", CreateLastFMRouter()) a.MountRouter("LastFM Auth", consts.URLPathNativeAPI+"/lastfm", CreateLastFMRouter())
} }
if conf.Server.ListenBrainz.Enabled { if conf.Server().ListenBrainz.Enabled {
a.MountRouter("ListenBrainz Auth", consts.URLPathNativeAPI+"/listenbrainz", CreateListenBrainzRouter()) a.MountRouter("ListenBrainz Auth", consts.URLPathNativeAPI+"/listenbrainz", CreateListenBrainzRouter())
} }
if conf.Server.Jellyfin.Enabled { if conf.Server().Jellyfin.Enabled {
a.MountRouter("Jellyfin API", consts.URLPathJellyfinAPI, CreateJellyfinAPIRouter(ctx)) a.MountRouter("Jellyfin API", consts.URLPathJellyfinAPI, CreateJellyfinAPIRouter(ctx))
} }
if conf.Server.DevAPIv1 { if conf.Server().DevAPIv1 {
a.MountRouter("API v1", consts.URLPathAPIv1, CreateAPIv1Router(ctx)) a.MountRouter("API v1", consts.URLPathAPIv1, CreateAPIv1Router(ctx))
} }
if conf.Server.Prometheus.Enabled { if conf.Server().Prometheus.Enabled {
p := CreatePrometheus() p := CreatePrometheus()
// blocking call because takes <100ms but useful if fails // blocking call because takes <100ms but useful if fails
p.WriteInitialMetrics(ctx) p.WriteInitialMetrics(ctx)
a.MountRouter("Prometheus metrics", conf.Server.Prometheus.MetricsPath, p.GetHandler()) a.MountRouter("Prometheus metrics", conf.Server().Prometheus.MetricsPath, p.GetHandler())
} }
if conf.Server.DevEnableProfiler { if conf.Server().DevEnableProfiler {
a.MountRouter("Profiling", "/debug", profilerHandler()) a.MountRouter("Profiling", "/debug", profilerHandler())
} }
if strings.HasPrefix(conf.Server.UILoginBackgroundURL, "/") { if strings.HasPrefix(conf.Server().UILoginBackgroundURL, "/") {
a.MountRouter("Background images", conf.Server.UILoginBackgroundURL, backgrounds.NewHandler()) a.MountRouter("Background images", conf.Server().UILoginBackgroundURL, backgrounds.NewHandler())
} }
return a.Run(ctx, conf.Server.Address, conf.Server.Port, conf.Server.TLSCert, conf.Server.TLSKey) return a.Run(ctx, conf.Server().Address, conf.Server().Port, conf.Server().TLSCert, conf.Server().TLSKey)
} }
} }
@ -156,14 +160,14 @@ func startServer(ctx context.Context) func() error {
// name from the raw request path, so the BasePath has to come off first. // name from the raw request path, so the BasePath has to come off first.
func profilerHandler() http.Handler { func profilerHandler() http.Handler {
// A trailing or root slash would make StripPrefix drop the leading slash chi needs. // A trailing or root slash would make StripPrefix drop the leading slash chi needs.
basePath := strings.TrimRight(conf.Server.BasePath, "/") basePath := strings.TrimRight(conf.Server().BasePath, "/")
return http.StripPrefix(basePath, middleware.Profiler()) return http.StripPrefix(basePath, middleware.Profiler())
} }
// schedulePeriodicScan schedules a periodic scan of the music library, if configured. // schedulePeriodicScan schedules a periodic scan of the music library, if configured.
func schedulePeriodicScan(ctx context.Context) func() error { func schedulePeriodicScan(ctx context.Context) func() error {
return func() error { return func() error {
schedule := conf.Server.Scanner.Schedule schedule := conf.Server().Scanner.Schedule
if schedule == "" { if schedule == "" {
log.Info(ctx, "Periodic scan is DISABLED") log.Info(ctx, "Periodic scan is DISABLED")
return nil return nil
@ -186,16 +190,20 @@ func schedulePeriodicScan(ctx context.Context) func() error {
} }
} }
func pidHashChanged(ds model.DataStore) (bool, error) { // librariesWithChangedPID returns the names of the libraries whose effective PID config differs from
pidAlbum, err := ds.Property().DefaultGet(context.Background(), consts.PIDAlbumKey, "") // the one used by their last finished scan
func librariesWithChangedPID(ctx context.Context, ds model.DataStore) ([]string, error) {
libs, err := ds.Library().GetAll(ctx)
if err != nil { if err != nil {
return false, err return nil, err
} }
pidTrack, err := ds.Property().DefaultGet(context.Background(), consts.PIDTrackKey, "") var names []string
if err != nil { for _, lib := range libs {
return false, err if lib.PIDChanged() {
names = append(names, lib.Name)
} }
return !strings.EqualFold(pidAlbum, conf.Server.PID.Album) || !strings.EqualFold(pidTrack, conf.Server.PID.Track), nil }
return names, nil
} }
// runInitialScan runs an initial scan of the music library if needed. // runInitialScan runs an initial scan of the music library if needed.
@ -210,12 +218,12 @@ func runInitialScan(ctx context.Context) func() error {
if err != nil { if err != nil {
return err return err
} }
pidHasChanged, err := pidHashChanged(ds) pidChangedLibs, err := librariesWithChangedPID(ctx, ds)
if err != nil { if err != nil {
return err return err
} }
scanOnStartup := conf.Server.Scanner.Enabled && conf.Server.Scanner.ScanOnStartup scanOnStartup := conf.Server().Scanner.Enabled && conf.Server().Scanner.ScanOnStartup
scanNeeded := scanOnStartup || inProgress || fullScanRequired == "1" || pidHasChanged scanNeeded := scanOnStartup || inProgress || fullScanRequired == "1" || len(pidChangedLibs) > 0
time.Sleep(2 * time.Second) // Wait 2 seconds before the initial scan time.Sleep(2 * time.Second) // Wait 2 seconds before the initial scan
if scanNeeded { if scanNeeded {
s := CreateScanner(ctx) s := CreateScanner(ctx)
@ -223,9 +231,9 @@ func runInitialScan(ctx context.Context) func() error {
case fullScanRequired == "1": case fullScanRequired == "1":
log.Warn(ctx, "Full scan required after migration") log.Warn(ctx, "Full scan required after migration")
_ = ds.Property().Delete(ctx, consts.FullScanAfterMigrationFlagKey) _ = ds.Property().Delete(ctx, consts.FullScanAfterMigrationFlagKey)
case pidHasChanged: case len(pidChangedLibs) > 0:
log.Warn(ctx, "PID config changed, performing full scan") // Includes never-scanned libraries. The scanner rescans in full only the ones that need it
fullScanRequired = "1" log.Warn(ctx, "Libraries with a new or changed PID config, scanning", "libraries", pidChangedLibs)
case inProgress: case inProgress:
log.Warn(ctx, "Resuming interrupted scan") log.Warn(ctx, "Resuming interrupted scan")
default: default:
@ -247,7 +255,7 @@ func runInitialScan(ctx context.Context) func() error {
func startScanWatcher(ctx context.Context) func() error { func startScanWatcher(ctx context.Context) func() error {
return func() error { return func() error {
if conf.Server.Scanner.WatcherWait == 0 { if conf.Server().Scanner.WatcherWait == 0 {
log.Debug("Folder watcher is DISABLED") log.Debug("Folder watcher is DISABLED")
return nil return nil
} }
@ -262,7 +270,7 @@ func startScanWatcher(ctx context.Context) func() error {
func schedulePeriodicBackup(ctx context.Context) func() error { func schedulePeriodicBackup(ctx context.Context) func() error {
return func() error { return func() error {
schedule := conf.Server.Backup.Schedule schedule := conf.Server().Backup.Schedule
if schedule == "" { if schedule == "" {
log.Info(ctx, "Periodic backup is DISABLED") log.Info(ctx, "Periodic backup is DISABLED")
return nil return nil
@ -297,7 +305,7 @@ func schedulePeriodicBackup(ctx context.Context) func() error {
func scheduleDBAnalyzer(ctx context.Context) func() error { func scheduleDBAnalyzer(ctx context.Context) func() error {
return func() error { return func() error {
if !conf.Server.EnableScheduledDBAnalyze { if !conf.Server().EnableScheduledDBAnalyze {
log.Info(ctx, "Scheduled DB analysis is DISABLED") log.Info(ctx, "Scheduled DB analysis is DISABLED")
return nil return nil
} }
@ -331,13 +339,13 @@ func startScheduler(ctx context.Context) func() error {
// startInsightsCollector starts the Navidrome Insight Collector, if configured. // startInsightsCollector starts the Navidrome Insight Collector, if configured.
func startInsightsCollector(ctx context.Context) func() error { func startInsightsCollector(ctx context.Context) func() error {
return func() error { return func() error {
if !conf.Server.EnableInsightsCollector { if !conf.Server().EnableInsightsCollector {
log.Info(ctx, "Insight Collector is DISABLED") log.Info(ctx, "Insight Collector is DISABLED")
return nil return nil
} }
log.Info(ctx, "Starting Insight Collector") log.Info(ctx, "Starting Insight Collector")
select { select {
case <-time.After(conf.Server.DevInsightsInitialDelay): case <-time.After(conf.Server().DevInsightsInitialDelay):
case <-ctx.Done(): case <-ctx.Done():
return nil return nil
} }
@ -350,7 +358,7 @@ func startInsightsCollector(ctx context.Context) func() error {
// startJellyfinDiscovery never returns an error: a discovery failure must not stop the server. // startJellyfinDiscovery never returns an error: a discovery failure must not stop the server.
func startJellyfinDiscovery(ctx context.Context) func() error { func startJellyfinDiscovery(ctx context.Context) func() error {
return func() error { return func() error {
if !conf.Server.Jellyfin.Enabled || !conf.Server.Jellyfin.AutoDiscovery { if !conf.Server().Jellyfin.Enabled || !conf.Server().Jellyfin.AutoDiscovery {
log.Debug("Jellyfin auto-discovery is DISABLED") log.Debug("Jellyfin auto-discovery is DISABLED")
return nil return nil
} }
@ -363,7 +371,7 @@ func startJellyfinDiscovery(ctx context.Context) func() error {
// It is responsible for the Jukebox functionality // It is responsible for the Jukebox functionality
func startPlaybackServer(ctx context.Context) func() error { func startPlaybackServer(ctx context.Context) func() error {
return func() error { return func() error {
if !conf.Server.Jukebox.Enabled { if !conf.Server().Jukebox.Enabled {
log.Debug("Jukebox is DISABLED") log.Debug("Jukebox is DISABLED")
return nil return nil
} }
@ -431,7 +439,7 @@ func scheduleArtworkHousekeeping(ctx context.Context, worker *artwork.Worker) fu
func startPluginManager(ctx context.Context) func() error { func startPluginManager(ctx context.Context) func() error {
return func() error { return func() error {
manager := GetPluginManager(ctx) manager := GetPluginManager(ctx)
if !conf.Server.Plugins.Enabled { if !conf.Server().Plugins.Enabled {
log.Debug("Plugin system is DISABLED") log.Debug("Plugin system is DISABLED")
return nil return nil
} }
@ -441,6 +449,7 @@ func startPluginManager(ctx context.Context) func() error {
} }
// TODO: Implement some struct tags to map flags to viper // TODO: Implement some struct tags to map flags to viper
func init() { func init() {
cobra.OnInitialize(func() { cobra.OnInitialize(func() {
conf.InitConfig(cfgFile, true) conf.InitConfig(cfgFile, true)

View file

@ -1,6 +1,8 @@
package cmd package cmd
import ( import (
"context"
"errors"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"path" "path"
@ -8,7 +10,10 @@ import (
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
) )
@ -19,17 +24,13 @@ var _ = Describe("profilerHandler", func() {
// Mirrors how server.MountRouter mounts the handler. // Mirrors how server.MountRouter mounts the handler.
mount := func() http.Handler { mount := func() http.Handler {
router := chi.NewRouter() router := chi.NewRouter()
router.Mount(path.Join(conf.Server.BasePath, "/debug"), profilerHandler()) router.Mount(path.Join(conf.Server().BasePath, "/debug"), profilerHandler())
return router return router
} }
BeforeEach(func() {
DeferCleanup(configtest.SetupConfig())
})
DescribeTable("serves a named profile", DescribeTable("serves a named profile",
func(basePath string) { func(basePath string) {
conf.Server.BasePath = basePath conf.Update(func(c *conf.Options) { c.BasePath = basePath })
w := httptest.NewRecorder() w := httptest.NewRecorder()
target := path.Join(basePath, "/debug/pprof/nd-profiler-test") + "?debug=1" target := path.Join(basePath, "/debug/pprof/nd-profiler-test") + "?debug=1"
@ -44,3 +45,45 @@ var _ = Describe("profilerHandler", func() {
Entry("with a trailing-slash BasePath", "/music/"), Entry("with a trailing-slash BasePath", "/music/"),
) )
}) })
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 ctx context.Context
var ds model.DataStore
BeforeEach(func() {
ctx = GinkgoT().Context()
ds = persistence.New(db.Db())
})
It("returns only the libraries whose PID config changed", func() {
pid := model.Library{}.EffectivePID()
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() {
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 package cmd
import ( import (
"context"
"os" "os"
"path/filepath" "path/filepath"
@ -18,7 +17,7 @@ var _ = Describe("trackScanInteractively", func() {
progress <- &scanner.ProgressInfo{Error: "scan failed"} progress <- &scanner.ProgressInfo{Error: "scan failed"}
close(progress) close(progress)
changesDetected, err := trackScanInteractively(context.Background(), progress) changesDetected, err := trackScanInteractively(GinkgoT().Context(), progress)
Expect(changesDetected).To(BeTrue()) Expect(changesDetected).To(BeTrue())
Expect(err).To(MatchError("scan failed")) Expect(err).To(MatchError("scan failed"))
}) })

View file

@ -53,8 +53,13 @@ func (p *svcControl) Start(service.Service) error {
p.done = make(chan struct{}) p.done = make(chan struct{})
p.ctx, p.cancel = context.WithCancel(context.Background()) p.ctx, p.cancel = context.WithCancel(context.Background())
go func() { go func() {
runNavidrome(p.ctx) err := runNavidrome(p.ctx)
close(p.done) close(p.done)
// service.Run() only returns when it gets a stop request, so exit here to let the
// service manager see the failure and restart the service
if err != nil {
log.Fatal("Fatal error in Navidrome. Aborting", err)
}
}() }()
return nil return nil
} }
@ -74,15 +79,15 @@ func (p *svcControl) Stop(service.Service) error {
var svcInstance = sync.OnceValue(func() service.Service { var svcInstance = sync.OnceValue(func() service.Service {
options := make(service.KeyValue) options := make(service.KeyValue)
options["Restart"] = "on-failure" options["Restart"] = "on-failure"
options["SuccessExitStatus"] = "1 2 8 SIGKILL" options["SuccessExitStatus"] = "SIGKILL"
options["UserService"] = false options["UserService"] = false
options["LogDirectory"] = conf.Server.DataFolder.String() options["LogDirectory"] = conf.Server().DataFolder.String()
options["SystemdScript"] = systemdScript options["SystemdScript"] = systemdScript
if conf.Server.LogFile != "" { if conf.Server().LogFile != "" {
options["LogOutput"] = false options["LogOutput"] = false
} else { } else {
options["LogOutput"] = true options["LogOutput"] = true
options["LogDirectory"] = conf.Server.DataFolder.String() options["LogDirectory"] = conf.Server().DataFolder.String()
} }
svcConfig := &service.Config{ svcConfig := &service.Config{
UserName: installUser, UserName: installUser,
@ -96,8 +101,8 @@ var svcInstance = sync.OnceValue(func() service.Service {
Option: options, Option: options,
} }
arguments := []string{"service", "execute"} arguments := []string{"service", "execute"}
if conf.Server.ConfigFile != "" { if conf.Server().ConfigFile != "" {
arguments = append(arguments, "-c", conf.Server.ConfigFile) arguments = append(arguments, "-c", conf.Server().ConfigFile)
} }
svcConfig.Arguments = arguments svcConfig.Arguments = arguments
@ -130,19 +135,21 @@ func buildInstallCmd() *cobra.Command {
var err error var err error
println("Installing service with:") println("Installing service with:")
println(" working directory: " + executablePath()) println(" working directory: " + executablePath())
println(" music folder: " + conf.Server.MusicFolder) println(" music folder: " + conf.Server().MusicFolder)
println(" data folder: " + conf.Server.DataFolder.String()) println(" data folder: " + conf.Server().DataFolder.String())
if conf.Server.LogFile != "" { if conf.Server().LogFile != "" {
println(" log file: " + conf.Server.LogFile) println(" log file: " + conf.Server().LogFile)
} else { } else {
println(" logs folder: " + conf.Server.DataFolder.String()) println(" logs folder: " + conf.Server().DataFolder.String())
} }
if cfgFile != "" { if cfgFile != "" {
conf.Server.ConfigFile, err = filepath.Abs(cfgFile) var absPath string
absPath, err = filepath.Abs(cfgFile)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
println(" config file: " + conf.Server.ConfigFile) conf.Update(func(c *conf.Options) { c.ConfigFile = absPath })
println(" config file: " + absPath)
} }
err = svcInstance().Install() err = svcInstance().Install()
if err != nil { if err != nil {

View file

@ -469,7 +469,10 @@ func runUserList(ctx context.Context) {
users[idx].Libraries = paths 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) fmt.Printf("%s\n", j)
} }
} }

View file

@ -18,11 +18,16 @@ import (
"github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/persistence"
) )
// requireExistingDB aborts the command when the database file (DbPath minus DSN // existingDBFile returns the database file (DbPath minus DSN params), and whether it exists.
// params) does not exist. func existingDBFile() (string, bool) {
path, _, _ := strings.Cut(conf.Server().DbPath, "?")
_, err := os.Stat(path)
return path, err == nil
}
// requireExistingDB aborts the command when the database file does not exist.
func requireExistingDB() { func requireExistingDB() {
path, _, _ := strings.Cut(conf.Server.DbPath, "?") if path, ok := existingDBFile(); !ok {
if _, err := os.Stat(path); os.IsNotExist(err) {
log.Fatal("No existing database", "path", path) log.Fatal("No existing database", "path", path)
} }
} }

View file

@ -80,7 +80,7 @@ func CreateNativeAPIRouter(ctx context.Context) *nativeapi.Router {
maintenance := core.NewMaintenance(dataStore) maintenance := core.NewMaintenance(dataStore)
agentsAgents := agents.GetAgents(dataStore, manager) agentsAgents := agents.GetAgents(dataStore, manager)
matcherMatcher := matcher.New(dataStore) matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher, broker) provider := external.NewProvider(ctx, dataStore, agentsAgents, matcherMatcher, broker)
quickConnect := quickconnect.GetInstance() quickConnect := quickconnect.GetInstance()
router := nativeapi.New(dataStore, share, playlistsPlaylists, insights, library, user, maintenance, manager, uploader, provider, quickConnect) router := nativeapi.New(dataStore, share, playlistsPlaylists, insights, library, user, maintenance, manager, uploader, provider, quickConnect)
return router return router
@ -95,22 +95,22 @@ func CreateSubsonicAPIRouter(ctx context.Context) *subsonic.Router {
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, imageStore, fFmpeg) artworkArtwork := artwork.NewArtwork(dataStore, fileCache, imageStore, fFmpeg)
transcodingCache := stream.GetTranscodingCache() transcodingCache := stream.GetTranscodingCache()
mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache) mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache)
transcodeDecider := stream.NewTranscodeDecider(dataStore, fFmpeg)
share := core.NewShare(dataStore) share := core.NewShare(dataStore)
archiver := core.NewArchiver(mediaStreamer, dataStore, share, artworkArtwork) archiver := core.NewArchiver(mediaStreamer, transcodeDecider, dataStore, share, artworkArtwork)
players := core.NewPlayers(dataStore) players := core.NewPlayers(dataStore)
broker := events.GetBroker() broker := events.GetBroker()
metricsMetrics := metrics.GetPrometheusInstance(dataStore) metricsMetrics := metrics.GetPrometheusInstance(dataStore)
manager := plugins.GetManager(dataStore, broker, metricsMetrics) manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager) agentsAgents := agents.GetAgents(dataStore, manager)
matcherMatcher := matcher.New(dataStore) matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher, broker) provider := external.NewProvider(ctx, dataStore, agentsAgents, matcherMatcher, broker)
uploader := artwork.NewUploader(dataStore) uploader := artwork.NewUploader(dataStore)
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader) playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader)
modelScanner := scanner.GetInstance(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics) modelScanner := scanner.GetInstance(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics)
playTracker := scrobbler.GetPlayTracker(dataStore, broker, manager) playTracker := scrobbler.GetPlayTracker(dataStore, broker, manager)
playbackServer := playback.GetInstance(dataStore) playbackServer := playback.GetInstance(dataStore)
lyricsLyrics := lyrics.NewLyrics(dataStore, manager) lyricsLyrics := lyrics.NewLyrics(dataStore, manager)
transcodeDecider := stream.NewTranscodeDecider(dataStore, fFmpeg)
sonicSonic := sonic.New(dataStore, manager, matcherMatcher) sonicSonic := sonic.New(dataStore, manager, matcherMatcher)
router := subsonic.New(dataStore, artworkArtwork, mediaStreamer, archiver, players, provider, modelScanner, broker, playlistsPlaylists, playTracker, share, playbackServer, metricsMetrics, lyricsLyrics, transcodeDecider, sonicSonic) router := subsonic.New(dataStore, artworkArtwork, mediaStreamer, archiver, players, provider, modelScanner, broker, playlistsPlaylists, playTracker, share, playbackServer, metricsMetrics, lyricsLyrics, transcodeDecider, sonicSonic)
return router return router
@ -135,7 +135,7 @@ func CreateJellyfinAPIRouter(ctx context.Context) *jellyfin.Router {
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader) playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader)
agentsAgents := agents.GetAgents(dataStore, manager) agentsAgents := agents.GetAgents(dataStore, manager)
matcherMatcher := matcher.New(dataStore) 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) sonicSonic := sonic.New(dataStore, manager, matcherMatcher)
lyricsLyrics := lyrics.NewLyrics(dataStore, manager) lyricsLyrics := lyrics.NewLyrics(dataStore, manager)
quickConnect := quickconnect.GetInstance() quickConnect := quickconnect.GetInstance()
@ -159,9 +159,10 @@ func CreatePublicRouter() *public.Router {
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, imageStore, fFmpeg) artworkArtwork := artwork.NewArtwork(dataStore, fileCache, imageStore, fFmpeg)
transcodingCache := stream.GetTranscodingCache() transcodingCache := stream.GetTranscodingCache()
mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache) mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache)
transcodeDecider := stream.NewTranscodeDecider(dataStore, fFmpeg)
share := core.NewShare(dataStore) share := core.NewShare(dataStore)
archiver := core.NewArchiver(mediaStreamer, dataStore, share, artworkArtwork) archiver := core.NewArchiver(mediaStreamer, transcodeDecider, dataStore, share, artworkArtwork)
router := public.New(dataStore, artworkArtwork, mediaStreamer, share, archiver) router := public.New(dataStore, artworkArtwork, mediaStreamer, transcodeDecider, share, archiver)
return router return router
} }

View file

@ -1,8 +1,14 @@
package configtest package configtest
import "github.com/navidrome/navidrome/conf" import (
"github.com/navidrome/navidrome/conf"
"github.com/onsi/ginkgo/v2"
)
// TODO Remove this redirection and call SnapshotConfig directly from tests // RestoreAfterEachSpec restores the config after every spec, and after each Ordered container as a
func SetupConfig() func() { // whole, so its BeforeAll can set config for all its specs. Call it at the top level of a suite.
return conf.SnapshotConfig() func RestoreAfterEachSpec() bool {
return ginkgo.BeforeEach(ginkgo.OncePerOrdered, func() {
ginkgo.DeferCleanup(conf.SnapshotConfig())
})
} }

View file

@ -0,0 +1,16 @@
package configtest_test
import (
"testing"
"github.com/navidrome/navidrome/conf/configtest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestConfigtest(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Configtest Suite")
}
var _ = configtest.RestoreAfterEachSpec()

View file

@ -0,0 +1,48 @@
package configtest_test
import (
"github.com/navidrome/navidrome/conf"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("RestoreAfterEachSpec", func() {
// Either spec can run first: the second one sees the first one's change if it leaks.
It("starts with the original value (A)", func() {
Expect(conf.Server().UIWelcomeMessage).To(BeEmpty())
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "A" })
})
It("starts with the original value (B)", func() {
Expect(conf.Server().UIWelcomeMessage).To(BeEmpty())
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() {
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "ordered" })
})
It("sees the BeforeAll change in the first spec", func() {
Expect(conf.Server().UIWelcomeMessage).To(Equal("ordered"))
})
It("still sees the BeforeAll change in later specs", func() {
Expect(conf.Server().UIWelcomeMessage).To(Equal("ordered"))
})
})
})

View file

@ -3,7 +3,7 @@ package conf
import ( import (
"cmp" "cmp"
"encoding" "encoding"
"encoding/json" "errors"
"fmt" "fmt"
"math" "math"
"net/url" "net/url"
@ -30,7 +30,7 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
) )
type configOptions struct { type Options struct {
ConfigFile string `conf:"-"` ConfigFile string `conf:"-"`
Address string Address string
Port int Port int
@ -71,7 +71,7 @@ type configOptions struct {
DefaultDownsamplingFormat string DefaultDownsamplingFormat string
Search searchOptions `json:",omitzero"` Search searchOptions `json:",omitzero"`
Matcher matcherOptions `json:",omitzero"` Matcher matcherOptions `json:",omitzero"`
RecentlyAddedByModTime bool RecentlyAddedBy string
PreferSortTags bool PreferSortTags bool
EnableNaturalSorting bool EnableNaturalSorting bool
IgnoredArticles string IgnoredArticles string
@ -102,6 +102,7 @@ type configOptions struct {
DefaultUIVolume int DefaultUIVolume int
UISearchDebounceMs int UISearchDebounceMs int
UICoverArtSize int UICoverArtSize int
UIAppendRemixers bool // Whether to show remixers after the track artists in the UI
EnableReplayGain bool EnableReplayGain bool
EnableCoverAnimation bool EnableCoverAnimation bool
EnableNowPlaying bool EnableNowPlaying bool
@ -143,6 +144,7 @@ type configOptions struct {
DevUIShowConfig bool DevUIShowConfig bool
DevNewEventStream bool DevNewEventStream bool
DevOffsetOptimize int DevOffsetOptimize int
DevMaxPlaylistTracksPerRequest int
DevArtworkMaxRequests int DevArtworkMaxRequests int
DevArtworkThrottleBacklogLimit int DevArtworkThrottleBacklogLimit int
DevArtworkThrottleBacklogTimeout time.Duration DevArtworkThrottleBacklogTimeout time.Duration
@ -161,6 +163,7 @@ type configOptions struct {
DevExternalArtistFetchMultiplier float64 DevExternalArtistFetchMultiplier float64
DevPreserveUnicodeInExternalCalls bool DevPreserveUnicodeInExternalCalls bool
DevEnableMediaFileProbe bool DevEnableMediaFileProbe bool
DevMatchEstimatedContentLength bool
DevAPIv1 bool DevAPIv1 bool
} }
@ -176,6 +179,7 @@ type scannerOptions struct {
GroupAlbumReleases bool // Deprecated: Use PID.Album instead GroupAlbumReleases bool // Deprecated: Use PID.Album instead
FollowSymlinks bool // Whether to follow symlinks when scanning directories FollowSymlinks bool // Whether to follow symlinks when scanning directories
IgnoreDotFolders bool // Whether to ignore folders whose name starts with a dot when scanning 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" PurgeMissing string // Values: "never", "always", "full"
} }
@ -206,10 +210,11 @@ type TagConf struct {
type lastfmOptions struct { type lastfmOptions struct {
Enabled bool Enabled bool
ApiKey string //nolint:gosec ApiKey string
Secret string //nolint:gosec Secret string
Language string Language string
ScrobbleFirstArtistOnly bool ScrobbleFirstArtistOnly bool
MinScrobbleDuration time.Duration
// Computed values // Computed values
Languages []string `conf:"-"` // Computed from Language, split by comma Languages []string `conf:"-"` // Computed from Language, split by comma
@ -251,7 +256,7 @@ type httpHeaderOptions struct {
type prometheusOptions struct { type prometheusOptions struct {
Enabled bool Enabled bool
MetricsPath string MetricsPath string
Password string //nolint:gosec Password string
} }
type AudioDeviceDefinition []string type AudioDeviceDefinition []string
@ -287,6 +292,7 @@ type pluginsOptions struct {
CacheSize string CacheSize string
AutoReload bool AutoReload bool
LogLevel string LogLevel string
MaxTaskDuration time.Duration
} }
type extAuthOptions struct { type extAuthOptions struct {
@ -320,30 +326,11 @@ var currentGOOS = func() string {
// TLSEnabled reports whether the server serves HTTPS. Both halves are required, // TLSEnabled reports whether the server serves HTTPS. Both halves are required,
// so callers cannot infer it from the certificate alone. // so callers cannot infer it from the certificate alone.
func (c *configOptions) TLSEnabled() bool { func (c Options) TLSEnabled() bool {
return c.TLSCert != "" && c.TLSKey != "" return c.TLSCert != "" && c.TLSKey != ""
} }
var ( var hooks []func()
Server = &configOptions{}
hooks []func()
)
// SnapshotConfig returns a function that restores Server to its current state.
// Uses JSON round-tripping so Dir fields get fresh sync.Once values.
func SnapshotConfig() func() {
snapshot, err := json.Marshal(Server)
if err != nil {
panic(fmt.Sprintf("SnapshotConfig: marshal failed: %v", err))
}
return func() {
var restored configOptions
if err := json.Unmarshal(snapshot, &restored); err != nil {
panic(fmt.Sprintf("SnapshotConfig: unmarshal failed: %v", err))
}
Server = &restored
}
}
func LoadFromFile(confFile string) { func LoadFromFile(confFile string) {
viper.SetConfigFile(confFile) viper.SetConfigFile(confFile)
@ -371,8 +358,10 @@ func Load(noConfigDump bool) {
mapDeprecatedOption(o.name, o.replacement) mapDeprecatedOption(o.name, o.replacement)
} }
} }
mapRecentlyAddedByModTime()
err := viper.Unmarshal(&Server, viper.DecodeHook( s := clone(current.Load())
err := viper.Unmarshal(s, viper.DecodeHook(
mapstructure.ComposeDecodeHookFunc( mapstructure.ComposeDecodeHookFunc(
mapstructure.TextUnmarshallerHookFunc(), mapstructure.TextUnmarshallerHookFunc(),
mapstructure.StringToTimeDurationHookFunc(), mapstructure.StringToTimeDurationHookFunc(),
@ -384,35 +373,35 @@ func Load(noConfigDump bool) {
} }
// Validate non-root user early, before any filesystem operations // Validate non-root user early, before any filesystem operations
if err := validateEnforceNonRootUser(); err != nil { if err := s.validateEnforceNonRootUser(); err != nil {
logFatal(err) logFatal(err)
} }
if Server.CacheFolder.String() == "" { if s.CacheFolder.String() == "" {
Server.CacheFolder = NewDir(filepath.Join(Server.DataFolder.String(), "cache")) s.CacheFolder = NewDir(filepath.Join(s.DataFolder.String(), "cache"))
} }
if Server.Plugins.Enabled { if s.Plugins.Enabled {
if Server.Plugins.Folder.String() == "" { if s.Plugins.Folder.String() == "" {
Server.Plugins.Folder = NewDirWithPerm(filepath.Join(Server.DataFolder.String(), "plugins"), 0700) s.Plugins.Folder = NewDirWithPerm(filepath.Join(s.DataFolder.String(), "plugins"), 0700)
} else { } else {
Server.Plugins.Folder = NewDirWithPerm(Server.Plugins.Folder.String(), 0700) s.Plugins.Folder = NewDirWithPerm(s.Plugins.Folder.String(), 0700)
} }
} }
Server.ConfigFile = viper.GetViper().ConfigFileUsed() s.ConfigFile = viper.GetViper().ConfigFileUsed()
if Server.DbPath == "" { if s.DbPath == "" {
Server.DbPath = filepath.Join(Server.DataFolder.String(), consts.DefaultDbPath) s.DbPath = filepath.Join(s.DataFolder.String(), consts.DefaultDbPath)
} }
out := os.Stderr out := os.Stderr
if Server.LogFile != "" { if s.LogFile != "" {
if mkErr := os.MkdirAll(filepath.Dir(Server.LogFile), os.ModePerm); mkErr != nil { 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(Server.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) out, err = os.OpenFile(s.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil { if err != nil {
logFatal(fmt.Sprintf("Error opening log file %s: %s", Server.LogFile, err.Error())) logFatal(fmt.Sprintf("Error opening log file %s: %s", s.LogFile, err.Error()))
} }
log.SetOutput(out) log.SetOutput(out)
} else if os.Getenv("ND_SYSTEMD_PRIORITY_LOGGING") != "" && os.Getenv("JOURNAL_STREAM") != "" { } else if os.Getenv("ND_SYSTEMD_PRIORITY_LOGGING") != "" && os.Getenv("JOURNAL_STREAM") != "" {
@ -423,24 +412,26 @@ func Load(noConfigDump bool) {
log.EnableJournalFormat() log.EnableJournalFormat()
} }
log.SetLevelString(Server.LogLevel) log.SetLevelString(s.LogLevel)
log.SetLogLevels(Server.DevLogLevels) log.SetLogLevels(s.DevLogLevels)
log.SetLogSourceLine(Server.DevLogSourceLine) log.SetLogSourceLine(s.DevLogSourceLine)
log.SetRedacting(Server.EnableLogRedacting) log.SetRedacting(s.EnableLogRedacting)
durationNonNegativeOrDefault(&Server.SessionTimeout, consts.DefaultSessionTimeout) durationNonNegativeOrDefault(&s.SessionTimeout, consts.DefaultSessionTimeout)
durationNonNegativeOrDefault(&Server.SmartPlaylistRefreshDelay, consts.DefaultSmartRefresh) durationNonNegativeOrDefault(&s.SmartPlaylistRefreshDelay, consts.DefaultSmartRefresh)
durationNonNegativeOrDefault(&Server.DefaultShareExpiration, consts.DefaultShareExpiration) durationNonNegativeOrDefault(&s.DefaultShareExpiration, consts.DefaultShareExpiration)
durationNonNegativeOrDefault(&Server.UIPlaybackReportInterval, consts.DefaultUIPlaybackReportInterval) durationNonNegativeOrDefault(&s.UIPlaybackReportInterval, consts.DefaultUIPlaybackReportInterval)
durationNonNegativeOrDefault(&Server.AuthWindowLength, consts.DefaultAuthWindowLength) durationNonNegativeOrDefault(&s.AuthWindowLength, consts.DefaultAuthWindowLength)
durationNonNegativeOrDefault(&Server.Scanner.WatcherWait, consts.DefaultWatcherWait) durationNonNegativeOrDefault(&s.Scanner.WatcherWait, consts.DefaultWatcherWait)
durationNonNegativeOrDefault(&Server.DevActivityPanelUpdateRate, consts.DefaultActivityPanelUpdateRate) durationNonNegativeOrDefault(&s.DevActivityPanelUpdateRate, consts.DefaultActivityPanelUpdateRate)
durationNonNegativeOrDefault(&Server.DevArtworkThrottleBacklogTimeout, consts.RequestThrottleBacklogTimeout) durationNonNegativeOrDefault(&s.DevArtworkThrottleBacklogTimeout, consts.RequestThrottleBacklogTimeout)
durationNonNegativeOrDefault(&Server.DevArtistInfoTimeToLive, consts.ArtistInfoTimeToLive) durationNonNegativeOrDefault(&s.DevArtistInfoTimeToLive, consts.ArtistInfoTimeToLive)
durationNonNegativeOrDefault(&Server.DevAlbumInfoTimeToLive, consts.AlbumInfoTimeToLive) durationNonNegativeOrDefault(&s.DevAlbumInfoTimeToLive, consts.AlbumInfoTimeToLive)
durationNonNegativeOrDefault(&Server.DevInsightsInitialDelay, consts.InsightsInitialDelay) durationNonNegativeOrDefault(&s.DevInsightsInitialDelay, consts.InsightsInitialDelay)
durationNonNegativeOrDefault(&Server.DevPluginCompilationTimeout, consts.DefaultPluginCompilationTimeout) durationNonNegativeOrDefault(&s.DevPluginCompilationTimeout, consts.DefaultPluginCompilationTimeout)
durationNonNegativeOrDefault(&s.LastFM.MinScrobbleDuration, consts.DefaultMinScrobbleDuration)
// Log deprecated, removed and unknown options // Log deprecated, removed and unknown options
for _, o := range deprecatedOptions { for _, o := range deprecatedOptions {
@ -450,35 +441,38 @@ func Load(noConfigDump bool) {
logUnknownOptions() logUnknownOptions()
err = run.Sequentially( err = run.Sequentially(
validateScanSchedule, s.validateScanSchedule,
validateBackupSchedule, s.validateBackupSchedule,
validatePlaylistsPath, s.validatePlaylistsPath,
validatePurgeMissingOption, validateEnum("Scanner.PurgeMissing", &s.Scanner.PurgeMissing,
validateByteSize("MaxImageUploadSize", Server.MaxImageUploadSize), consts.PurgeMissingNever, consts.PurgeMissingAlways, consts.PurgeMissingFull),
validateByteSize("MaxImageSize", Server.MaxImageSize), validateEnum("RecentlyAddedBy", &s.RecentlyAddedBy,
validateURL("ExtAuth.LogoutURL", Server.ExtAuth.LogoutURL), consts.RecentlyAddedByScan, consts.RecentlyAddedByBirth, consts.RecentlyAddedByModTime),
validateByteSize("MaxImageUploadSize", s.MaxImageUploadSize),
validateByteSize("MaxImageSize", s.MaxImageSize),
validateURL("ExtAuth.LogoutURL", s.ExtAuth.LogoutURL),
) )
if err != nil { if err != nil {
logFatal(err) logFatal(err)
} }
Server.Search.Backend = normalizeSearchBackend(Server.Search.Backend) s.Search.Backend = normalizeSearchBackend(s.Search.Backend)
if Server.BaseURL != "" { if s.BaseURL != "" {
u, err := url.Parse(Server.BaseURL) u, err := url.Parse(s.BaseURL)
if err != nil { if err != nil {
logFatal("Invalid BaseURL:", err) logFatal("Invalid BaseURL:", err)
} }
Server.BasePath = u.Path s.BasePath = u.Path
u.Path = "" u.Path = ""
u.RawQuery = "" u.RawQuery = ""
Server.BaseHost = u.Host s.BaseHost = u.Host
Server.BaseScheme = u.Scheme s.BaseScheme = u.Scheme
} }
// Log configuration source // Log configuration source
if Server.ConfigFile != "" { if s.ConfigFile != "" {
log.Info("Loaded configuration", "file", Server.ConfigFile) log.Info("Loaded configuration", "file", s.ConfigFile)
} else if hasNDEnvVars() { } else if hasNDEnvVars() {
log.Info("No configuration file found. Loaded configuration only from environment variables") log.Info("No configuration file found. Loaded configuration only from environment variables")
} else { } else {
@ -487,47 +481,49 @@ func Load(noConfigDump bool) {
// Print current configuration if log level is Debug // Print current configuration if log level is Debug
if log.IsGreaterOrEqualTo(log.LevelDebug) && !noConfigDump { if log.IsGreaterOrEqualTo(log.LevelDebug) && !noConfigDump {
prettyConf := pretty.Sprintf("Configuration: %# v", Server) prettyConf := pretty.Sprintf("Configuration: %# v", s)
if Server.EnableLogRedacting { if s.EnableLogRedacting {
prettyConf = log.Redact(prettyConf) prettyConf = log.Redact(prettyConf)
} }
_, _ = fmt.Fprintln(out, prettyConf) _, _ = fmt.Fprintln(out, prettyConf)
} }
if !Server.EnableExternalServices { if !s.EnableExternalServices {
disableExternalServices() s.disableExternalServices()
} }
// Make sure we don't have empty PIDs // Make sure we don't have empty PIDs
Server.PID.Album = cmp.Or(Server.PID.Album, consts.DefaultAlbumPID) s.PID.Album = cmp.Or(s.PID.Album, consts.DefaultAlbumPID)
Server.PID.Track = cmp.Or(Server.PID.Track, consts.DefaultTrackPID) s.PID.Track = cmp.Or(s.PID.Track, consts.DefaultTrackPID)
// Parse LastFM.Language into Languages slice (comma-separated, with fallback to DefaultInfoLanguage) // Parse LastFM.Language into Languages slice (comma-separated, with fallback to DefaultInfoLanguage)
Server.LastFM.Languages = parseLanguages(Server.LastFM.Language) s.LastFM.Languages = parseLanguages(s.LastFM.Language)
// Parse Deezer.Language into Languages slice (comma-separated, with fallback to DefaultInfoLanguage) // Parse Deezer.Language into Languages slice (comma-separated, with fallback to DefaultInfoLanguage)
Server.Deezer.Languages = parseLanguages(Server.Deezer.Language) s.Deezer.Languages = parseLanguages(s.Deezer.Language)
// Validate other options // Validate other options
if Server.UICoverArtSize < 200 || Server.UICoverArtSize > 1200 { if s.UICoverArtSize < 200 || s.UICoverArtSize > 1200 {
newValue := max(200, min(1200, Server.UICoverArtSize)) newValue := max(200, min(1200, s.UICoverArtSize))
log.Warn("UICoverArtSize must be between 200 and 1200, clamping", "value", Server.UICoverArtSize, "newValue", newValue) log.Warn("UICoverArtSize must be between 200 and 1200, clamping", "value", s.UICoverArtSize, "newValue", newValue)
Server.UICoverArtSize = newValue s.UICoverArtSize = newValue
} }
if Server.Scanner.Extractor != consts.DefaultScannerExtractor { if s.Scanner.Extractor != consts.DefaultScannerExtractor {
log.Warn("Invalid Scanner.Extractor, using default", "value", Server.Scanner.Extractor, "default", consts.DefaultScannerExtractor) log.Warn("Invalid Scanner.Extractor, using default", "value", s.Scanner.Extractor, "default", consts.DefaultScannerExtractor)
Server.Scanner.Extractor = consts.DefaultScannerExtractor s.Scanner.Extractor = consts.DefaultScannerExtractor
} }
// Floor MaxImageSize at MaxImageUploadSize so accepted uploads can always be read back. // Floor MaxImageSize at MaxImageUploadSize so accepted uploads can always be read back.
imgSize, _ := humanize.ParseBytes(Server.MaxImageSize) imgSize, _ := humanize.ParseBytes(s.MaxImageSize)
uploadSize, _ := humanize.ParseBytes(Server.MaxImageUploadSize) uploadSize, _ := humanize.ParseBytes(s.MaxImageUploadSize)
if imgSize < uploadSize { if imgSize < uploadSize {
log.Warn("MaxImageSize must be at least MaxImageUploadSize, raising", "value", Server.MaxImageSize, "newValue", Server.MaxImageUploadSize) log.Warn("MaxImageSize must be at least MaxImageUploadSize, raising", "value", s.MaxImageSize, "newValue", s.MaxImageUploadSize)
Server.MaxImageSize = Server.MaxImageUploadSize s.MaxImageSize = s.MaxImageUploadSize
} }
current.Store(s)
// Call init hooks // Call init hooks
for _, hook := range hooks { for _, hook := range hooks {
hook() hook()
@ -547,6 +543,7 @@ var deprecatedOptions = []struct{ name, replacement string }{
{"CoverJpegQuality", "CoverArtQuality"}, {"CoverJpegQuality", "CoverArtQuality"},
{"SimilarSongsMatchThreshold", "Matcher.FuzzyThreshold"}, {"SimilarSongsMatchThreshold", "Matcher.FuzzyThreshold"},
{"EnableTranscodingCancellation", "Transcoding.EnableCancellation"}, {"EnableTranscodingCancellation", "Transcoding.EnableCancellation"},
{"RecentlyAddedByModTime", "RecentlyAddedBy"},
} }
var removedOptions = []string{"Spotify.ID", "Spotify.Secret"} var removedOptions = []string{"Spotify.ID", "Spotify.Secret"}
@ -627,6 +624,18 @@ func mapDeprecatedOption(legacyName, newName string) {
} }
} }
// mapRecentlyAddedByModTime overrides the generic mapping, which would copy the legacy boolean as-is.
func mapRecentlyAddedByModTime() {
if !viper.IsSet("RecentlyAddedByModTime") || explicitlySet("RecentlyAddedBy") {
return
}
if viper.GetBool("RecentlyAddedByModTime") {
viper.Set("RecentlyAddedBy", consts.RecentlyAddedByModTime)
} else {
viper.Set("RecentlyAddedBy", consts.RecentlyAddedByScan)
}
}
// explicitlySet reports whether the user provided the option, ignoring defaults, // explicitlySet reports whether the user provided the option, ignoring defaults,
// which viper.IsSet counts as set. The ND_ spelling is also accepted in the config // which viper.IsSet counts as set. The ND_ spelling is also accepted in the config
// file, and remapEnvVarKeysFromConfig has already moved it out of InConfig's reach. // file, and remapEnvVarKeysFromConfig has already moved it out of InConfig's reach.
@ -740,7 +749,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*[]=:]`) var configFileKeyRx = regexp.MustCompile(`(?m)^\s*\[?\s*"?([\w.]+)"?\s*[]=:]`)
// configKeys maps every accepted option name, lowercased, to its canonical spelling, // configKeys maps every accepted option name, lowercased, to its canonical spelling,
@ -768,7 +777,7 @@ var configKeys = sync.OnceValues(func() (map[string]string, []string) {
} }
} }
} }
collect(reflect.TypeFor[configOptions](), "") collect(reflect.TypeFor[Options](), "")
for _, o := range deprecatedOptions { for _, o := range deprecatedOptions {
keys[strings.ToLower(o.name)] = o.name keys[strings.ToLower(o.name)] = o.name
@ -803,21 +812,21 @@ func parseIniFileConfiguration() {
} }
} }
func disableExternalServices() { func (s *Options) disableExternalServices() {
log.Info("All external integrations are DISABLED!") log.Info("All external integrations are DISABLED!")
Server.EnableInsightsCollector = false s.EnableInsightsCollector = false
Server.EnableM3UExternalAlbumArt = false s.EnableM3UExternalAlbumArt = false
Server.LastFM.Enabled = false s.LastFM.Enabled = false
Server.Deezer.Enabled = false s.Deezer.Enabled = false
Server.ListenBrainz.Enabled = false s.ListenBrainz.Enabled = false
Server.Agents = "" s.Agents = ""
if Server.UILoginBackgroundURL == consts.DefaultUILoginBackgroundURL { if s.UILoginBackgroundURL == consts.DefaultUILoginBackgroundURL {
Server.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURLOffline s.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURLOffline
} }
} }
func validatePlaylistsPath() error { func (s *Options) validatePlaylistsPath() error {
for path := range strings.SplitSeq(Server.PlaylistsPath, string(filepath.ListSeparator)) { for path := range strings.SplitSeq(s.PlaylistsPath, string(filepath.ListSeparator)) {
_, err := doublestar.Match(path, "") _, err := doublestar.Match(path, "")
if err != nil { if err != nil {
return fmt.Errorf("invalid PlaylistsPath %q: %w", path, err) return fmt.Errorf("invalid PlaylistsPath %q: %w", path, err)
@ -842,15 +851,16 @@ func parseLanguages(lang string) []string {
return languages return languages
} }
func validatePurgeMissingOption() error { // validateEnum resets value to its first allowed entry when it is not one of them.
allowedValues := []string{consts.PurgeMissingNever, consts.PurgeMissingAlways, consts.PurgeMissingFull} func validateEnum(name string, value *string, allowed ...string) func() error {
valid := slices.Contains(allowedValues, Server.Scanner.PurgeMissing) return func() error {
if !valid { if slices.Contains(allowed, *value) {
err := fmt.Errorf("invalid Scanner.PurgeMissing value: '%s'. Must be one of: %v", Server.Scanner.PurgeMissing, allowedValues) return nil
Server.Scanner.PurgeMissing = consts.PurgeMissingNever }
err := fmt.Errorf("invalid %s value: '%s'. Must be one of: %v", name, *value, allowed)
*value = allowed[0]
return err return err
} }
return nil
} }
func validateByteSize(name, value string) func() error { func validateByteSize(name, value string) func() error {
@ -869,35 +879,35 @@ func validateByteSize(name, value string) func() error {
} }
} }
func validateEnforceNonRootUser() error { func (s *Options) validateEnforceNonRootUser() error {
if !Server.EnforceNonRootUser || currentGOOS() == "windows" { if !s.EnforceNonRootUser || currentGOOS() == "windows" {
return nil return nil
} }
if getEUID() == 0 { 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 return nil
} }
func validateScanSchedule() error { func (s *Options) validateScanSchedule() error {
if Server.Scanner.Schedule == "0" || Server.Scanner.Schedule == "" { if s.Scanner.Schedule == "0" || s.Scanner.Schedule == "" {
Server.Scanner.Schedule = "" s.Scanner.Schedule = ""
return nil return nil
} }
var err error var err error
Server.Scanner.Schedule, err = validateSchedule(Server.Scanner.Schedule, "Scanner.Schedule") s.Scanner.Schedule, err = validateSchedule(s.Scanner.Schedule, "Scanner.Schedule")
return err return err
} }
func validateBackupSchedule() error { func (s *Options) validateBackupSchedule() error {
if Server.Backup.Path.String() == "" || Server.Backup.Schedule == "" || Server.Backup.Count == 0 { if s.Backup.Path.String() == "" || s.Backup.Schedule == "" || s.Backup.Count == 0 {
Server.Backup.Schedule = "" s.Backup.Schedule = ""
return nil return nil
} }
var err error var err error
Server.Backup.Schedule, err = validateSchedule(Server.Backup.Schedule, "Backup.Schedule") s.Backup.Schedule, err = validateSchedule(s.Backup.Schedule, "Backup.Schedule")
return err return err
} }
@ -1007,7 +1017,7 @@ func setViperDefaults() {
viper.SetDefault("search.backend", "fts") viper.SetDefault("search.backend", "fts")
viper.SetDefault("matcher.preferstarred", true) viper.SetDefault("matcher.preferstarred", true)
viper.SetDefault("matcher.fuzzythreshold", 85) viper.SetDefault("matcher.fuzzythreshold", 85)
viper.SetDefault("recentlyaddedbymodtime", false) viper.SetDefault("recentlyaddedby", consts.RecentlyAddedByScan)
viper.SetDefault("prefersorttags", false) viper.SetDefault("prefersorttags", false)
viper.SetDefault("enablenaturalsorting", false) viper.SetDefault("enablenaturalsorting", false)
viper.SetDefault("ignoredarticles", "The El La Los Las Le Les Os As O A") viper.SetDefault("ignoredarticles", "The El La Los Las Le Les Os As O A")
@ -1031,6 +1041,7 @@ func setViperDefaults() {
viper.SetDefault("defaultuivolume", consts.DefaultUIVolume) viper.SetDefault("defaultuivolume", consts.DefaultUIVolume)
viper.SetDefault("uisearchdebouncems", consts.DefaultUISearchDebounceMs) viper.SetDefault("uisearchdebouncems", consts.DefaultUISearchDebounceMs)
viper.SetDefault("uicoverartsize", consts.DefaultUICoverArtSize) viper.SetDefault("uicoverartsize", consts.DefaultUICoverArtSize)
viper.SetDefault("uiappendremixers", true)
viper.SetDefault("enablereplaygain", true) viper.SetDefault("enablereplaygain", true)
viper.SetDefault("enablecoveranimation", true) viper.SetDefault("enablecoveranimation", true)
viper.SetDefault("enablenowplaying", true) viper.SetDefault("enablenowplaying", true)
@ -1070,6 +1081,7 @@ func setViperDefaults() {
viper.SetDefault("scanner.groupalbumreleases", false) viper.SetDefault("scanner.groupalbumreleases", false)
viper.SetDefault("scanner.followsymlinks", true) viper.SetDefault("scanner.followsymlinks", true)
viper.SetDefault("scanner.ignoredotfolders", true) viper.SetDefault("scanner.ignoredotfolders", true)
viper.SetDefault("scanner.respectnomedia", false)
viper.SetDefault("scanner.purgemissing", consts.PurgeMissingNever) viper.SetDefault("scanner.purgemissing", consts.PurgeMissingNever)
viper.SetDefault("subsonic.appendsubtitle", true) viper.SetDefault("subsonic.appendsubtitle", true)
viper.SetDefault("subsonic.appendalbumversion", true) viper.SetDefault("subsonic.appendalbumversion", true)
@ -1087,6 +1099,7 @@ func setViperDefaults() {
viper.SetDefault("lastfm.apikey", "") viper.SetDefault("lastfm.apikey", "")
viper.SetDefault("lastfm.secret", "") viper.SetDefault("lastfm.secret", "")
viper.SetDefault("lastfm.scrobblefirstartistonly", false) viper.SetDefault("lastfm.scrobblefirstartistonly", false)
viper.SetDefault("lastfm.minscrobbleduration", consts.DefaultMinScrobbleDuration)
viper.SetDefault("deezer.enabled", true) viper.SetDefault("deezer.enabled", true)
viper.SetDefault("deezer.language", consts.DefaultInfoLanguage) viper.SetDefault("deezer.language", consts.DefaultInfoLanguage)
viper.SetDefault("listenbrainz.enabled", true) viper.SetDefault("listenbrainz.enabled", true)
@ -1113,6 +1126,7 @@ func setViperDefaults() {
viper.SetDefault("plugins.cachesize", "200MB") viper.SetDefault("plugins.cachesize", "200MB")
viper.SetDefault("plugins.autoreload", false) viper.SetDefault("plugins.autoreload", false)
viper.SetDefault("plugins.loglevel", "") viper.SetDefault("plugins.loglevel", "")
viper.SetDefault("plugins.maxtaskduration", time.Hour)
// DevFlags. These are used to enable/disable debugging and incomplete features // DevFlags. These are used to enable/disable debugging and incomplete features
viper.SetDefault("devlogsourceline", false) viper.SetDefault("devlogsourceline", false)
@ -1127,6 +1141,7 @@ func setViperDefaults() {
viper.SetDefault("devneweventstream", true) viper.SetDefault("devneweventstream", true)
viper.SetDefault("devapiv1", false) viper.SetDefault("devapiv1", false)
viper.SetDefault("devoffsetoptimize", 50000) 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, // Half the pool: streams may take up to this many connections, leaving the rest for the scanner,
// scrobbles and the UI. See MaxOpenConns. // scrobbles and the UI. See MaxOpenConns.
viper.SetDefault("jellyfin.maxconcurrentstreams", max(2, MaxOpenConns()/2)) viper.SetDefault("jellyfin.maxconcurrentstreams", max(2, MaxOpenConns()/2))
@ -1152,6 +1167,7 @@ func setViperDefaults() {
viper.SetDefault("devexternalartistfetchmultiplier", 1.5) viper.SetDefault("devexternalartistfetchmultiplier", 1.5)
viper.SetDefault("devpreserveunicodeinexternalcalls", false) viper.SetDefault("devpreserveunicodeinexternalcalls", false)
viper.SetDefault("devenablemediafileprobe", true) viper.SetDefault("devenablemediafileprobe", true)
viper.SetDefault("devmatchestimatedcontentlength", true)
} }
func init() { func init() {

View file

@ -23,6 +23,8 @@ func TestConfiguration(t *testing.T) {
RunSpecs(t, "Configuration Suite") RunSpecs(t, "Configuration Suite")
} }
var _ = configtest.RestoreAfterEachSpec()
var _ = Describe("Configuration", func() { var _ = Describe("Configuration", func() {
BeforeEach(func() { BeforeEach(func() {
// Reset viper configuration // Reset viper configuration
@ -32,10 +34,7 @@ var _ = Describe("Configuration", func() {
viper.SetDefault("loglevel", "error") viper.SetDefault("loglevel", "error")
conf.ResetConf() conf.ResetConf()
// Panic instead of exiting on fatal errors to allow testing error conditions DeferCleanup(conf.PanicOnLogFatal())
DeferCleanup(conf.SetLogFatal(func(args ...any) {
panic(fmt.Sprint(args...))
}))
}) })
Describe("ParseLanguages", func() { Describe("ParseLanguages", func() {
@ -67,13 +66,13 @@ var _ = Describe("Configuration", func() {
Describe("scheduled DB analysis", func() { Describe("scheduled DB analysis", func() {
It("is enabled by default", func() { It("is enabled by default", func() {
conf.Load(true) conf.Load(true)
Expect(conf.Server.EnableScheduledDBAnalyze).To(BeTrue()) Expect(conf.Server().EnableScheduledDBAnalyze).To(BeTrue())
}) })
It("can be disabled", func() { It("can be disabled", func() {
viper.Set("enablescheduleddbanalyze", false) viper.Set("enablescheduleddbanalyze", false)
conf.Load(true) conf.Load(true)
Expect(conf.Server.EnableScheduledDBAnalyze).To(BeFalse()) Expect(conf.Server().EnableScheduledDBAnalyze).To(BeFalse())
}) })
}) })
@ -110,7 +109,7 @@ var _ = Describe("Configuration", func() {
It("rejects a URL that cannot be parsed", func() { It("rejects a URL that cannot be parsed", func() {
fn := conf.ValidateURL("TestOption", "://invalid") fn := conf.ValidateURL("TestOption", "://invalid")
Expect(fn()).To(HaveOccurred()) Expect(fn()).ToNot(Succeed())
}) })
It("rejects a URL without a host", func() { It("rejects a URL without a host", func() {
@ -158,9 +157,9 @@ var _ = Describe("Configuration", func() {
conf.InitConfig(filename, false) conf.InitConfig(filename, false)
conf.Load(true) conf.Load(true)
Expect(conf.Server.Address).To(Equal("127.0.0.1")) Expect(conf.Server().Address).To(Equal("127.0.0.1"))
Expect(conf.Server.Port).To(Equal(4531)) Expect(conf.Server().Port).To(Equal(4531))
Expect(conf.Server.Scanner.Schedule).To(Equal("@every 1h")) Expect(conf.Server().Scanner.Schedule).To(Equal("@every 1h"))
}) })
It("exits with fatal error when both ND_ and canonical key exist", func() { It("exits with fatal error when both ND_ and canonical key exist", func() {
@ -180,7 +179,7 @@ var _ = Describe("Configuration", func() {
conf.Load(true) conf.Load(true)
// Verify normal config loading still works // Verify normal config loading still works
Expect(conf.Server.MusicFolder).To(Equal("/toml/music")) Expect(conf.Server().MusicFolder).To(Equal("/toml/music"))
}) })
}) })
@ -254,14 +253,14 @@ var _ = Describe("Configuration", func() {
conf.Load(true) conf.Load(true)
Expect(conf.UnknownConfigKeys()).To(ConsistOf("ND_TOTALLY_BOGUS_OPTION")) Expect(conf.UnknownConfigKeys()).To(ConsistOf("ND_TOTALLY_BOGUS_OPTION"))
Expect(conf.Server.Scanner.Schedule).To(Equal("@every 1h")) Expect(conf.Server().Scanner.Schedule).To(Equal("@every 1h"))
}) })
It("migrates every deprecated option that has a replacement", func() { It("migrates every deprecated option that has a replacement", func() {
conf.InitConfig(filepath.Join("testdata", "cfg_deprecated_search.toml"), false) conf.InitConfig(filepath.Join("testdata", "cfg_deprecated_search.toml"), false)
conf.Load(true) conf.Load(true)
Expect(conf.Server.Search.FullString).To(BeTrue()) Expect(conf.Server().Search.FullString).To(BeTrue())
Expect(conf.UnknownConfigKeys()).To(BeEmpty()) Expect(conf.UnknownConfigKeys()).To(BeEmpty())
}) })
@ -296,11 +295,44 @@ var _ = Describe("Configuration", func() {
}) })
It("keeps an explicit replacement over the deprecated value", func() { It("keeps an explicit replacement over the deprecated value", func() {
Expect(conf.Server.Search.FullString).To(BeFalse()) Expect(conf.Server().Search.FullString).To(BeFalse())
}) })
}) })
}) })
Describe("RecentlyAddedBy", func() {
loadTOML := func(content string, loadEnvVars ...bool) {
GinkgoHelper()
filename := filepath.Join(GinkgoT().TempDir(), "navidrome.toml")
Expect(os.WriteFile(filename, []byte(content), 0600)).To(Succeed())
conf.InitConfig(filename, len(loadEnvVars) > 0 && loadEnvVars[0])
conf.Load(true)
}
DescribeTable("resolves the sort mode",
func(content, expected string) {
loadTOML(content)
Expect(conf.Server().RecentlyAddedBy).To(Equal(expected))
},
Entry("defaults to scan", ``, consts.RecentlyAddedByScan),
Entry("accepts an explicit value", `RecentlyAddedBy = "birth"`, consts.RecentlyAddedByBirth),
Entry("maps the deprecated option set to true", `RecentlyAddedByModTime = true`, consts.RecentlyAddedByModTime),
Entry("maps the deprecated option set to false", `RecentlyAddedByModTime = false`, consts.RecentlyAddedByScan),
Entry("keeps an explicit value over the deprecated option",
"RecentlyAddedBy = \"birth\"\nRecentlyAddedByModTime = true", consts.RecentlyAddedByBirth),
)
It("maps the deprecated environment variable", func() {
GinkgoT().Setenv("ND_RECENTLYADDEDBYMODTIME", "true")
loadTOML(``, true)
Expect(conf.Server().RecentlyAddedBy).To(Equal(consts.RecentlyAddedByModTime))
})
It("exits with a fatal error for an unknown value", func() {
Expect(func() { loadTOML(`RecentlyAddedBy = "creation"`) }).To(PanicWith(ContainSubstring("invalid RecentlyAddedBy value")))
})
})
Describe("logFatal", func() { Describe("logFatal", func() {
var invalidPath string var invalidPath string
BeforeEach(func() { BeforeEach(func() {
@ -392,13 +424,38 @@ var _ = Describe("Configuration", func() {
viper.SetDefault("maximagesize", "5MB") viper.SetDefault("maximagesize", "5MB")
viper.SetDefault("maximageuploadsize", "50MB") viper.SetDefault("maximageuploadsize", "50MB")
conf.Load(true) conf.Load(true)
Expect(conf.Server.MaxImageSize).To(Equal("50MB")) Expect(conf.Server().MaxImageSize).To(Equal("50MB"))
}) })
It("keeps a larger MaxImageSize unchanged", func() { It("keeps a larger MaxImageSize unchanged", func() {
viper.SetDefault("maximagesize", "30MB") viper.SetDefault("maximagesize", "30MB")
conf.Load(true) conf.Load(true)
Expect(conf.Server.MaxImageSize).To(Equal("30MB")) Expect(conf.Server().MaxImageSize).To(Equal("30MB"))
})
})
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))
}) })
}) })
@ -414,12 +471,12 @@ var _ = Describe("Configuration", func() {
It("falls back to taglib for an unknown extractor", func() { It("falls back to taglib for an unknown extractor", func() {
viper.SetDefault("scanner.extractor", "ffmpeg") viper.SetDefault("scanner.extractor", "ffmpeg")
conf.Load(true) conf.Load(true)
Expect(conf.Server.Scanner.Extractor).To(Equal("taglib")) Expect(conf.Server().Scanner.Extractor).To(Equal("taglib"))
}) })
It("keeps taglib", func() { It("keeps taglib", func() {
conf.Load(true) conf.Load(true)
Expect(conf.Server.Scanner.Extractor).To(Equal("taglib")) Expect(conf.Server().Scanner.Extractor).To(Equal("taglib"))
}) })
}) })
@ -427,7 +484,7 @@ var _ = Describe("Configuration", func() {
It("defaults to false", func() { It("defaults to false", func() {
conf.Load(true) conf.Load(true)
Expect(conf.Server.EnforceNonRootUser).To(BeFalse()) Expect(conf.Server().EnforceNonRootUser).To(BeFalse())
}) })
It("allows startup for non-root users when enabled", func() { It("allows startup for non-root users when enabled", func() {
@ -436,7 +493,7 @@ var _ = Describe("Configuration", func() {
conf.Load(true) conf.Load(true)
Expect(conf.Server.EnforceNonRootUser).To(BeTrue()) Expect(conf.Server().EnforceNonRootUser).To(BeTrue())
}) })
It("exits when enabled and running as root without having created a data folder", func() { It("exits when enabled and running as root without having created a data folder", func() {
@ -462,7 +519,7 @@ var _ = Describe("Configuration", func() {
conf.Load(true) conf.Load(true)
Expect(conf.Server.EnforceNonRootUser).To(BeTrue()) Expect(conf.Server().EnforceNonRootUser).To(BeTrue())
}) })
}) })
@ -476,16 +533,16 @@ var _ = Describe("Configuration", func() {
conf.Load(true) conf.Load(true)
// Execute the format-specific assertions // Execute the format-specific assertions
Expect(conf.Server.MusicFolder).To(Equal(fmt.Sprintf("/%s/music", format))) Expect(conf.Server().MusicFolder).To(Equal(fmt.Sprintf("/%s/music", format)))
Expect(conf.Server.UIWelcomeMessage).To(Equal("Welcome " + format)) Expect(conf.Server().UIWelcomeMessage).To(Equal("Welcome " + format))
Expect(conf.Server.Tags["custom"].Aliases).To(Equal([]string{format, "test"})) Expect(conf.Server().Tags["custom"].Aliases).To(Equal([]string{format, "test"}))
Expect(conf.Server.Tags["artist"].Split).To(Equal([]string{";"})) Expect(conf.Server().Tags["artist"].Split).To(Equal([]string{";"}))
// Check deprecated option mapping // Check deprecated option mapping
Expect(conf.Server.ExtAuth.UserHeader).To(Equal("X-Auth-User")) Expect(conf.Server().ExtAuth.UserHeader).To(Equal("X-Auth-User"))
// The config file used should be the one we created // The config file used should be the one we created
Expect(conf.Server.ConfigFile).To(Equal(filename)) Expect(conf.Server().ConfigFile).To(Equal(filename))
}, },
Entry("TOML format", "toml"), Entry("TOML format", "toml"),
Entry("YAML format", "yaml"), Entry("YAML format", "yaml"),
@ -498,7 +555,7 @@ var _ = Describe("Configuration", func() {
conf.InitConfig(filename, false) conf.InitConfig(filename, false)
conf.Load(true) conf.Load(true)
server := conf.Server server := conf.Server()
Expect(server.SessionTimeout).To(Equal(consts.DefaultSessionTimeout)) Expect(server.SessionTimeout).To(Equal(consts.DefaultSessionTimeout))
Expect(server.SmartPlaylistRefreshDelay).To(Equal(consts.DefaultSmartRefresh)) Expect(server.SmartPlaylistRefreshDelay).To(Equal(consts.DefaultSmartRefresh))
Expect(server.DefaultShareExpiration).To(Equal(consts.DefaultShareExpiration)) Expect(server.DefaultShareExpiration).To(Equal(consts.DefaultShareExpiration))
@ -520,7 +577,7 @@ var _ = Describe("Configuration", func() {
configured := 1 * time.Second configured := 1 * time.Second
server := conf.Server server := conf.Server()
Expect(server.SessionTimeout).To(Equal(configured)) Expect(server.SessionTimeout).To(Equal(configured))
Expect(server.SmartPlaylistRefreshDelay).To(Equal(configured)) Expect(server.SmartPlaylistRefreshDelay).To(Equal(configured))
Expect(server.DefaultShareExpiration).To(Equal(configured)) Expect(server.DefaultShareExpiration).To(Equal(configured))
@ -538,27 +595,26 @@ var _ = Describe("Configuration", func() {
}) })
var _ = Describe("TLSEnabled", func() { var _ = Describe("TLSEnabled", func() {
BeforeEach(func() {
DeferCleanup(configtest.SetupConfig())
})
It("is false when neither the certificate nor the key is set", func() { It("is false when neither the certificate nor the key is set", func() {
Expect(conf.Server.TLSEnabled()).To(BeFalse()) Expect(conf.Server().TLSEnabled()).To(BeFalse())
}) })
It("is true when both the certificate and the key are set", func() { It("is true when both the certificate and the key are set", func() {
conf.Server.TLSCert = "cert.pem" conf.Update(func(c *conf.Options) {
conf.Server.TLSKey = "key.pem" c.TLSCert = "cert.pem"
Expect(conf.Server.TLSEnabled()).To(BeTrue()) c.TLSKey = "key.pem"
})
Expect(conf.Server().TLSEnabled()).To(BeTrue())
}) })
It("is false when only the certificate is set", func() { It("is false when only the certificate is set", func() {
conf.Server.TLSCert = "cert.pem" conf.Update(func(c *conf.Options) { c.TLSCert = "cert.pem" })
Expect(conf.Server.TLSEnabled()).To(BeFalse()) Expect(conf.Server().TLSEnabled()).To(BeFalse())
}) })
It("is false when only the key is set", func() { It("is false when only the key is set", func() {
conf.Server.TLSKey = "key.pem" conf.Update(func(c *conf.Options) { c.TLSKey = "key.pem" })
Expect(conf.Server.TLSEnabled()).To(BeFalse()) Expect(conf.Server().TLSEnabled()).To(BeFalse())
}) })
}) })

View file

@ -82,20 +82,14 @@ var _ = Describe("Dir", func() {
}) })
It("calls logFatal on error", func() { It("calls logFatal on error", func() {
var fatalMsg []any DeferCleanup(conf.PanicOnLogFatal())
restore := conf.SetLogFatal(func(args ...any) {
fatalMsg = args
panic("logFatal called")
})
DeferCleanup(restore)
f := GinkgoT().TempDir() + "/blocker" f := GinkgoT().TempDir() + "/blocker"
Expect(os.WriteFile(f, []byte("x"), 0600)).To(Succeed()) Expect(os.WriteFile(f, []byte("x"), 0600)).To(Succeed())
invalid := f + "/subdir" invalid := f + "/subdir"
d := conf.NewDir(invalid) d := conf.NewDir(invalid)
Expect(func() { d.MustPath() }).To(Panic()) Expect(func() { d.MustPath() }).To(PanicWith(ContainSubstring("creating directory")))
Expect(fatalMsg).ToNot(BeEmpty())
}) })
}) })

View file

@ -1,7 +1,9 @@
package conf package conf
import "fmt"
func ResetConf() { func ResetConf() {
Server = &configOptions{} current.Store(&Options{})
} }
var SetViperDefaults = setViperDefaults var SetViperDefaults = setViperDefaults
@ -33,6 +35,13 @@ func SetLogFatal(f func(...any)) func() {
return func() { logFatal = old } 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 UnknownConfigKeys = unknownConfigKeys
var SuggestOptions = suggestOptions var SuggestOptions = suggestOptions

87
conf/server.go Normal file
View file

@ -0,0 +1,87 @@
package conf
import (
"reflect"
"sync/atomic"
)
var current atomic.Pointer[Options]
func init() {
current.Store(&Options{})
}
// Server returns a copy of the current configuration. A published Options is never changed in place,
// so readers need no locking. Use Update to change it.
func Server() Options {
return *current.Load()
}
// Update applies fn to a deep copy of the current configuration and publishes the result.
// fn may run more than once if another change lands first, so it must only set fields.
func Update(fn func(*Options)) {
for {
old := current.Load()
next := clone(old)
fn(next)
if current.CompareAndSwap(old, next) {
return
}
}
}
// SnapshotConfig returns a function that restores the configuration to its current state.
func SnapshotConfig() func() {
snapshot := current.Load()
return func() { current.Store(snapshot) }
}
func clone(o *Options) *Options {
var c Options
deepCopy(reflect.ValueOf(&c).Elem(), reflect.ValueOf(o).Elem())
return &c
}
func deepCopy(dst, src reflect.Value) {
switch src.Kind() {
case reflect.Struct:
dst.Set(src)
for i := range src.NumField() {
if dst.Field(i).CanSet() {
deepCopy(dst.Field(i), src.Field(i))
}
}
case reflect.Map:
if src.IsNil() {
dst.Set(src)
return
}
m := reflect.MakeMapWithSize(src.Type(), src.Len())
for k, v := range src.Seq2() {
nv := reflect.New(v.Type()).Elem()
deepCopy(nv, v)
m.SetMapIndex(k, nv)
}
dst.Set(m)
case reflect.Slice:
if src.IsNil() {
dst.Set(src)
return
}
s := reflect.MakeSlice(src.Type(), src.Len(), src.Len())
for i := range src.Len() {
deepCopy(s.Index(i), src.Index(i))
}
dst.Set(s)
case reflect.Pointer:
if src.IsNil() {
dst.Set(src)
return
}
p := reflect.New(src.Type().Elem())
deepCopy(p.Elem(), src.Elem())
dst.Set(p)
default:
dst.Set(src)
}
}

89
conf/server_test.go Normal file
View file

@ -0,0 +1,89 @@
package conf_test
import (
"sync"
"github.com/navidrome/navidrome/conf"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Server state", func() {
BeforeEach(func() {
conf.Update(func(c *conf.Options) {
c.Tags = map[string]conf.TagConf{"genre": {Aliases: []string{"genre", "style"}}}
c.DevLogLevels = map[string]string{"scanner": "info"}
c.Scanner.ArtistSplitExceptions = []string{"AC/DC"}
})
})
It("keeps a copy taken from Server unchanged by later updates", func() {
before := conf.Server()
conf.Update(func(c *conf.Options) {
c.Tags["genre"].Aliases[0] = "changed"
c.DevLogLevels["scanner"] = "debug"
c.Scanner.ArtistSplitExceptions[0] = "changed"
})
Expect(before.Tags["genre"].Aliases).To(Equal([]string{"genre", "style"}))
Expect(before.DevLogLevels).To(Equal(map[string]string{"scanner": "info"}))
Expect(before.Scanner.ArtistSplitExceptions).To(Equal([]string{"AC/DC"}))
Expect(conf.Server().DevLogLevels["scanner"]).To(Equal("debug"))
})
It("restores map and slice contents changed in place by Update", func() {
restore := conf.SnapshotConfig()
conf.Update(func(c *conf.Options) {
c.Tags["genre"].Aliases[0] = "changed"
c.DevLogLevels["scanner"] = "debug"
})
restore()
Expect(conf.Server().Tags["genre"].Aliases).To(Equal([]string{"genre", "style"}))
Expect(conf.Server().DevLogLevels).To(Equal(map[string]string{"scanner": "info"}))
})
It("lets readers run while the config is updated and restored", func() {
stop := make(chan struct{})
var wg sync.WaitGroup
wg.Go(func() {
for {
select {
case <-stop:
return
default:
_ = conf.Server().DevLogLevels["scanner"]
_ = conf.Server().Scanner.Enabled
}
}
})
for range 100 {
restore := conf.SnapshotConfig()
conf.Update(func(c *conf.Options) {
c.DevLogLevels["scanner"] = "debug"
c.Scanner.Enabled = !c.Scanner.Enabled
})
restore()
}
close(stop)
wg.Wait()
})
It("keeps every change when updates run at the same time", func() {
conf.Update(func(c *conf.Options) { c.Port = 0 })
var wg sync.WaitGroup
for range 50 {
wg.Go(func() {
for range 20 {
conf.Update(func(c *conf.Options) { c.Port++ })
}
})
}
wg.Wait()
Expect(conf.Server().Port).To(Equal(1000))
})
})

View file

@ -34,6 +34,7 @@ const (
JWTPublicSecretKey = "JWTPublicSecret" JWTPublicSecretKey = "JWTPublicSecret"
JWTIssuer = "ND" JWTIssuer = "ND"
DefaultSessionTimeout = 48 * time.Hour DefaultSessionTimeout = 48 * time.Hour
APIv1GrantIdleExpiry = 90 * 24 * time.Hour
DefaultSmartRefresh = 5 * time.Second DefaultSmartRefresh = 5 * time.Second
DefaultShareExpiration = 8760 * time.Hour DefaultShareExpiration = 8760 * time.Hour
CookieExpiry = 365 * 24 * 3600 // One year CookieExpiry = 365 * 24 * 3600 // One year
@ -49,6 +50,7 @@ const (
DefaultEncryptionKey = "just for obfuscation" DefaultEncryptionKey = "just for obfuscation"
PasswordsEncryptedKey = "PasswordsEncryptedKey" PasswordsEncryptedKey = "PasswordsEncryptedKey"
PasswordAutogenPrefix = "__NAVIDROME_AUTOGEN__" //nolint:gosec PasswordAutogenPrefix = "__NAVIDROME_AUTOGEN__" //nolint:gosec
APIKeyPrefix = "nds_"
DevInitialUserName = "admin" DevInitialUserName = "admin"
DevInitialName = "Dev Admin" DevInitialName = "Dev Admin"
@ -82,6 +84,8 @@ const (
DefaultInfoLanguage = "en" DefaultInfoLanguage = "en"
DefaultMinScrobbleDuration = 30 * time.Second
ArtistInfoTimeToLive = 24 * time.Hour ArtistInfoTimeToLive = 24 * time.Hour
AlbumInfoTimeToLive = 7 * 24 * time.Hour AlbumInfoTimeToLive = 7 * 24 * time.Hour
UpdateLastAccessFrequency = time.Minute UpdateLastAccessFrequency = time.Minute
@ -89,6 +93,7 @@ const (
I18nFolder = "i18n" I18nFolder = "i18n"
ScanIgnoreFile = ".ndignore" ScanIgnoreFile = ".ndignore"
NoMediaFile = ".nomedia"
ArtworkFolder = "artwork" ArtworkFolder = "artwork"
// HashedArtworkFolder is a subtree of ArtworkFolder, kept apart from the name-addressed // HashedArtworkFolder is a subtree of ArtworkFolder, kept apart from the name-addressed
// upload folders beside it so Prune's sweep never reaches them. // upload folders beside it so Prune's sweep never reaches them.
@ -155,8 +160,6 @@ const (
//DefaultAlbumPID = "album_legacy" //DefaultAlbumPID = "album_legacy"
DefaultAlbumPID = "musicbrainz_albumid|albumartistid,album,albumversion,releasedate" DefaultAlbumPID = "musicbrainz_albumid|albumartistid,album,albumversion,releasedate"
DefaultTrackPID = "musicbrainz_trackid|albumid,discnumber,tracknumber,title" DefaultTrackPID = "musicbrainz_trackid|albumid,discnumber,tracknumber,title"
PIDAlbumKey = "PIDAlbum"
PIDTrackKey = "PIDTrack"
) )
const ( const (
@ -172,6 +175,12 @@ const (
PurgeMissingFull = "full" PurgeMissingFull = "full"
) )
const (
RecentlyAddedByScan = "scan"
RecentlyAddedByBirth = "birth"
RecentlyAddedByModTime = "modtime"
)
var ( var (
DefaultDownsamplingFormat = "opus" DefaultDownsamplingFormat = "opus"
DefaultTranscodings = []struct { DefaultTranscodings = []struct {
@ -211,12 +220,10 @@ var HTTPUserAgent = "Navidrome/" + Version + " - https://github.com/navidrome"
var ( var (
VariousArtists = "Various Artists" VariousArtists = "Various Artists"
// TODO This will be dynamic when using disambiguation VariousArtistsID = "63sqASlAfjbGMuLP4JhnZU" // TODO This will be dynamic when using disambiguation
VariousArtistsID = "63sqASlAfjbGMuLP4JhnZU"
UnknownAlbum = "[Unknown Album]" UnknownAlbum = "[Unknown Album]"
UnknownArtist = "[Unknown Artist]" UnknownArtist = "[Unknown Artist]"
// TODO This will be dynamic when using disambiguation UnknownArtistID = id.NewHash(strings.ToLower(UnknownArtist)) // TODO This will be dynamic when using disambiguation
UnknownArtistID = id.NewHash(strings.ToLower(UnknownArtist))
VariousArtistsMbzId = "89ad4ac3-39f7-470e-963a-56509c546377" VariousArtistsMbzId = "89ad4ac3-39f7-470e-963a-56509c546377"
ArtistJoiner = " • " ArtistJoiner = " • "

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