Compare commits

...

47 commits

Author SHA1 Message Date
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
569 changed files with 20095 additions and 13337 deletions

View file

@ -1,3 +1,5 @@
> **Before you open this PR:** read the full diff yourself and test the change. Do not submit AI output that you have not reviewed. See [Review your work before opening a PR](https://github.com/navidrome/navidrome/blob/master/CONTRIBUTING.md#review-your-work-before-opening-a-pr).
### Description ### Description
<!-- Please provide a clear and concise description of what this PR does and why it is needed. AI tools may help you draft, edit, or translate it, but review the final text and make sure you agree with it. Please be mindful of the maintainer's time. --> <!-- Please provide a clear and concise description of what this PR does and why it is needed. AI tools may help you draft, edit, or translate it, but review the final text and make sure you agree with it. Please be mindful of the maintainer's time. -->
@ -18,19 +20,19 @@
### Checklist ### Checklist
Please review and check all that apply. Leave unverified items unchecked and explain them under How to Test. 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. - [ ] 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. - [ ] 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 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. --> <!-- 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

View file

@ -1,9 +1,11 @@
#!/usr/bin/env bash #!/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. # 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). # Compares HEAD against $BASE_REF (default origin/master) and needs full history (fetch-depth: 0 in CI).
set -euo pipefail set -euo pipefail
BASE_REF="${BASE_REF:-origin/master}" BASE_REF="${BASE_REF:-origin/master}"
status=0
git diff --unified=0 --no-color "$BASE_REF"...HEAD -- '*.go' | awk ' git diff --unified=0 --no-color "$BASE_REF"...HEAD -- '*.go' | awk '
function directives(s, out) { function directives(s, out) {
@ -45,4 +47,19 @@ END {
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 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 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"

View file

@ -13,7 +13,7 @@ jobs:
steps: steps:
- name: Allowed by label - name: Allowed by label
if: contains(github.event.pull_request.labels.*.name, 'allow-nolint') if: contains(github.event.pull_request.labels.*.name, 'allow-nolint')
run: echo "::notice::The allow-nolint label is set, so new //nolint directives are allowed." run: echo "::notice::The allow-nolint label is set, so new //nolint directives and lint config changes are allowed."
- uses: actions/checkout@v7 - uses: actions/checkout@v7
if: "!contains(github.event.pull_request.labels.*.name, 'allow-nolint')" if: "!contains(github.event.pull_request.labels.*.name, 'allow-nolint')"

View file

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

2
.gitignore vendored
View file

@ -28,7 +28,7 @@ docker-compose.yml
binaries 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

@ -14,21 +14,29 @@ linters:
- depguard - 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 - nolintlint
- perfsprint
- rowserrcheck - rowserrcheck
- unconvert
- whitespace
disable:
- staticcheck - staticcheck
- thelper
- unconvert
- usestdlibvars
- usetesting
- whitespace
settings: settings:
depguard: depguard:
rules: rules:
@ -123,6 +131,22 @@ linters:
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:
@ -133,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$'
@ -151,6 +178,19 @@ linters:
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:
@ -169,6 +209,11 @@ linters:
linters: linters:
- forbidigo - forbidigo
text: "in tests use" 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

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

View file

@ -22,7 +22,7 @@ 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

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

View file

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

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

View file

@ -12,7 +12,7 @@ import (
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"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"
) )
@ -28,7 +28,7 @@ var _ = Describe("deezerAgent", func() {
Describe("deezerConstructor", func() { Describe("deezerConstructor", func() {
It("uses configured languages", func() { It("uses configured languages", func() {
conf.Update(func(c *conf.Options) { c.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"}))
}) })
}) })
@ -40,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),
} }
}) })
@ -48,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},
@ -66,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}
@ -83,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}}`)),
}) })
@ -97,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}`)),
@ -116,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",
@ -140,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",
@ -166,12 +164,12 @@ 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))),
} }
}) })
@ -179,7 +177,6 @@ var _ = Describe("deezerAgent", func() {
setupAgent := func(languages []string) { setupAgent := func(languages []string) {
conf.Update(func(c *conf.Options) { c.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,
} }
@ -190,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", "")
@ -205,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", "")
@ -224,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", "")
@ -259,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
} }
@ -270,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
} }
@ -285,7 +282,7 @@ 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
} }

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

@ -243,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")
) )
@ -377,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

View file

@ -14,7 +14,9 @@ import (
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"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,7 +32,7 @@ var _ = Describe("lastfmAgent", func() {
var ctx context.Context var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context() ctx = GinkgoT().Context()
ds = &tests.MockDataStore{} ds = persistence.New(db.Db())
conf.Update(func(c *conf.Options) { conf.Update(func(c *conf.Options) {
c.LastFM.Enabled = true c.LastFM.Enabled = true
c.LastFM.ApiKey = "123" c.LastFM.ApiKey = "123"
@ -76,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"))
@ -91,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))
@ -101,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())
@ -124,7 +126,7 @@ var _ = Describe("lastfmAgent", func() {
// 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", "")
@ -141,10 +143,10 @@ var _ = Describe("lastfmAgent", func() {
// 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", "")
@ -162,10 +164,10 @@ var _ = Describe("lastfmAgent", func() {
// 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", "")
@ -189,10 +191,10 @@ var _ = Describe("lastfmAgent", func() {
// 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", "")
@ -211,9 +213,9 @@ var _ = Describe("lastfmAgent", func() {
// 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", "")
@ -237,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"},
@ -255,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))
@ -275,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"},
@ -293,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))
@ -313,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"}}},
@ -328,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))
@ -342,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))
@ -354,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)
@ -370,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"},
}, },
}, },
} }
@ -383,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)
@ -413,7 +416,7 @@ var _ = Describe("lastfmAgent", func() {
}) })
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)
@ -429,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})
@ -456,7 +459,7 @@ var _ = Describe("lastfmAgent", func() {
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})
@ -470,7 +473,7 @@ var _ = Describe("lastfmAgent", func() {
It("skips songs at the 30-second minimum", func() { It("skips songs at the 30-second minimum", func() {
track.Duration = 30 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()})
@ -480,7 +483,7 @@ var _ = Describe("lastfmAgent", func() {
It("sends the duration parameter for a 30.5-second song", func() { It("sends the duration parameter for a 30.5-second song", func() {
track.Duration = 30.5 track.Duration = 30.5
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"scrobbles":{"scrobble":{"ignoredMessage":{"code":"0"}},"@attr":{"accepted":1}}}`)), StatusCode: 200} 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()}) err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
@ -495,7 +498,7 @@ var _ = Describe("lastfmAgent", func() {
It("skips songs according to the configured minimum duration", func() { It("skips songs according to the configured minimum duration", func() {
conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 60 * time.Second }) conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 60 * time.Second })
track.Duration = 59 track.Duration = 59
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()})
@ -506,7 +509,7 @@ var _ = Describe("lastfmAgent", func() {
It("does not skip short songs when the minimum duration is disabled", func() { It("does not skip short songs when the minimum duration is disabled", func() {
conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 0 }) conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 0 })
track.Duration = 29 track.Duration = 29
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()})
@ -526,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()})
@ -536,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()})
@ -546,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()})
@ -556,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()})
@ -566,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()})
@ -587,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",
@ -603,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",
@ -621,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))
@ -629,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.
@ -655,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())
@ -667,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())
@ -675,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())
@ -687,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))
@ -698,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))
@ -711,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())
@ -729,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", "")
@ -762,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

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

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

@ -30,17 +30,17 @@ 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(ctx, "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(ctx, "Lungs", "Florence + the Machine", "", "en") _, err := client.albumGetInfo(ctx, "Lungs", "Florence + the Machine", "", "en")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -51,17 +51,17 @@ 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(ctx, "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(ctx, "Florence + the Machine", "en") _, err := client.artistGetInfo(ctx, "Florence + the Machine", "en")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -71,7 +71,7 @@ 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(ctx, "U2", "pt") _, err := client.artistGetInfo(ctx, "U2", "pt")
@ -81,7 +81,7 @@ 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(`{"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(ctx, "U2", "pt") _, err := client.artistGetInfo(ctx, "U2", "pt")
@ -91,7 +91,7 @@ var _ = Describe("client", func() {
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(ctx, "U2", "pt") _, err := client.artistGetInfo(ctx, "U2", "pt")
@ -108,7 +108,7 @@ var _ = Describe("client", func() {
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(ctx, "U2", "pt") _, err := client.artistGetInfo(ctx, "U2", "pt")
@ -120,17 +120,17 @@ 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(ctx, "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(ctx, "+44", 2) _, err := client.artistGetSimilar(ctx, "+44", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -141,17 +141,17 @@ 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(ctx, "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(ctx, "C+C Music Factory", 2) _, err := client.artistGetTopTracks(ctx, "C+C Music Factory", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -162,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(ctx, "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))
@ -175,7 +175,7 @@ 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(ctx, "1+1", "Queen + Paul Rodgers", 5) _, err := client.trackGetSimilar(ctx, "1+1", "Queen + Paul Rodgers", 5)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -186,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(ctx, "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())
}) })
}) })
@ -198,7 +198,7 @@ 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(ctx)).To(Equal("TOKEN")) Expect(client.GetToken(ctx)).To(Equal("TOKEN"))
@ -214,7 +214,7 @@ 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(ctx, "TOKEN")).To(Equal("SESSION_KEY")) Expect(client.getSession(ctx, "TOKEN")).To(Equal("SESSION_KEY"))
@ -231,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{
@ -243,7 +243,7 @@ var _ = Describe("client", func() {
albumArtist: "U2", albumArtist: "U2",
} }
err := client.scrobble(ctx, "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))
@ -265,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{
@ -277,7 +277,7 @@ var _ = Describe("client", func() {
albumArtist: "U2", albumArtist: "U2",
} }
err := client.updateNowPlaying(ctx, "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

@ -5,6 +5,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest" "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"
@ -13,8 +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 _ = 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

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

View file

@ -8,13 +8,16 @@ import (
"io" "io"
"net/http" "net/http"
"os" "os"
"reflect"
"time" "time"
"github.com/navidrome/navidrome/conf" "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"
@ -30,8 +33,9 @@ var _ = Describe("listenBrainzAgent", func() {
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context() ctx = GinkgoT().Context()
ds = &tests.MockDataStore{} 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)
@ -47,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"},
}, },
}, },
} }
@ -81,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())
@ -101,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())
@ -129,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)
@ -139,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)
@ -149,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)
@ -159,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)
@ -168,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"}`)),
} }
@ -192,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"))
@ -200,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))
@ -218,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())
@ -248,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())
@ -258,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{
@ -285,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{
@ -311,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))
@ -323,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))
@ -355,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())
@ -365,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())
@ -379,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())
@ -415,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())
@ -425,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())
@ -457,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())
@ -483,7 +487,7 @@ var _ = Describe("register", func() {
var ds model.DataStore var ds model.DataStore
BeforeEach(func() { BeforeEach(func() {
ds = &tests.MockDataStore{} ds = struct{ model.DataStore }{}
delete(agents.Map, listenBrainzAgentName) delete(agents.Map, listenBrainzAgentName)
scrobbler.Unregister(listenBrainzAgentName) scrobbler.Unregister(listenBrainzAgentName)
}) })
@ -500,8 +504,9 @@ var _ = Describe("register", func() {
}) })
It("builds no scrobbler and no agent", func() { It("builds no scrobbler and no agent", func() {
Expect(newScrobbler(ds) == nil).To(BeTrue()) // TypeOf is nil only for an untyped nil; a typed nil would pass callers' != nil checks
Expect(agents.Map[listenBrainzAgentName](ds) == nil).To(BeTrue()) Expect(reflect.TypeOf(newScrobbler(ds))).To(BeNil())
Expect(reflect.TypeOf(agents.Map[listenBrainzAgentName](ds))).To(BeNil())
}) })
}) })

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

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

View file

@ -48,7 +48,7 @@ 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,
} }
}) })
@ -64,7 +64,7 @@ var _ = Describe("client", func() {
It("parses and returns the response", func() { It("parses and returns the response", func() {
res, err := client.validateToken(ctx, "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"))
}) })
}) })
@ -74,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{
@ -131,7 +131,7 @@ 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(ctx, "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."))
@ -143,7 +143,7 @@ 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(ctx, "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)"))
@ -154,7 +154,7 @@ 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(ctx, "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))
@ -164,7 +164,7 @@ 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(ctx, "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/"))
@ -180,7 +180,7 @@ 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(ctx, "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"))
@ -192,7 +192,7 @@ 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(ctx, "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)"))
@ -203,7 +203,7 @@ 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(ctx, "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{
@ -233,7 +233,7 @@ 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(ctx, "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{
@ -269,7 +269,7 @@ 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(ctx, "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)"))
@ -280,7 +280,7 @@ 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(ctx, 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))
@ -294,7 +294,7 @@ 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(ctx, "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))
@ -310,7 +310,7 @@ var _ = Describe("client", func() {
conf.Update(func(c *conf.Options) { c.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(ctx, 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))
@ -339,7 +339,7 @@ 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(ctx, "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)"))
@ -350,7 +350,7 @@ 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(ctx, 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))
@ -378,7 +378,7 @@ 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(ctx, 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))
@ -398,7 +398,7 @@ 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(ctx, mbid, 4) resp, err := client.getSimilarRecordings(ctx, mbid, 4)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -446,7 +446,7 @@ var _ = Describe("client", func() {
conf.Update(func(c *conf.Options) { c.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(ctx, 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))
@ -468,7 +468,7 @@ 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."}`)),
} }
@ -481,7 +481,7 @@ 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(ctx, "token") _, err := client.validateToken(ctx, "token")
@ -493,7 +493,7 @@ 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"}`)),
} }
@ -509,7 +509,7 @@ 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."}`)),
} }
@ -522,7 +522,7 @@ 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"}`)),
} }

View file

@ -5,6 +5,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest" "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"
@ -13,8 +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 _ = 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)
@ -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) {

View file

@ -10,8 +10,10 @@ import (
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"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"
) )
@ -54,14 +56,13 @@ var _ = Describe("parseArtworkKind", func() {
}) })
var _ = Describe("resolveArtworkTargets", func() { var _ = Describe("resolveArtworkTargets", func() {
var ds *tests.MockDataStore var ds model.DataStore
var ctx context.Context var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context() ctx = GinkgoT().Context()
artists := tests.CreateMockArtistRepo() ds = persistence.New(db.Db())
artists.SetData(model.Artists{{ID: "artist1"}}) persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "artist1", Name: "artist1"})
ds = &tests.MockDataStore{MockedArtist: artists}
}) })
It("accepts the explicit <kind> <id> leader shared by every id", func() { It("accepts the explicit <kind> <id> leader shared by every id", func() {
@ -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())
}) })
}) })
@ -493,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())
@ -565,9 +566,9 @@ 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
var ctx context.Context var ctx context.Context
@ -588,9 +589,9 @@ var _ = Describe("reprocessArtwork", func() {
c.EnableM3UExternalAlbumArt = false 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", "")
@ -810,22 +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
var ctx context.Context var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context() ctx = GinkgoT().Context()
ds = &tests.MockDataStore{} ds = persistence.New(db.Db())
art = ds.Artwork().(*tests.MockArtworkRepo) art = ds.Artwork()
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo) 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())
@ -971,19 +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
var ctx context.Context var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context() ctx = GinkgoT().Context()
albums := tests.CreateMockAlbumRepo() ds = persistence.New(db.Db())
albums.SetData(model.Albums{{ID: "al-1"}, {ID: "al-3"}}) for _, id := range []string{"al-1", "al-3"} {
ds = &tests.MockDataStore{MockedAlbum: albums} Expect(ds.Album().Put(ctx, &model.Album{ID: id, Name: id, LibraryID: model.DefaultLibraryID})).To(Succeed())
art = ds.Artwork().(*tests.MockArtworkRepo) }
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo) art = ds.Artwork()
queue = ds.ArtworkQueue()
out.Reset() out.Reset()
}) })
@ -1147,8 +1149,8 @@ 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
var ctx context.Context var ctx context.Context
accept := func(io.Writer, int64, int64) bool { return true } accept := func(io.Writer, int64, int64) bool { return true }
@ -1156,8 +1158,8 @@ var _ = Describe("cancelArtwork", func() {
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context() ctx = GinkgoT().Context()
ds = &tests.MockDataStore{} ds = persistence.New(db.Db())
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo) 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,
@ -1212,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

@ -5,6 +5,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest" "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"
@ -13,8 +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 _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

View file

@ -50,11 +50,11 @@ 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
} }

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

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

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

@ -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
@ -104,7 +104,7 @@ func CreateSubsonicAPIRouter(ctx context.Context) *subsonic.Router {
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)
@ -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()

View file

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

View file

@ -18,9 +18,22 @@ var _ = Describe("RestoreAfterEachSpec", func() {
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "B" }) 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() { Describe("in an Ordered container", Ordered, func() {
BeforeAll(func() { BeforeAll(func() {
DeferCleanup(conf.SnapshotConfig())
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "ordered" }) conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "ordered" })
}) })

View file

@ -3,6 +3,7 @@ package conf
import ( import (
"cmp" "cmp"
"encoding" "encoding"
"errors"
"fmt" "fmt"
"math" "math"
"net/url" "net/url"
@ -101,6 +102,7 @@ type Options 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
@ -142,6 +144,7 @@ type Options 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
@ -392,7 +395,7 @@ func Load(noConfigDump bool) {
out := os.Stderr out := os.Stderr
if s.LogFile != "" { if s.LogFile != "" {
if mkErr := os.MkdirAll(filepath.Dir(s.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(s.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 {
@ -728,7 +731,7 @@ func asWrittenInConfigFile(keys []string) []string {
}) })
} }
// Matches keys and section headers in all supported config formats. // configFileKeyRx matches keys and section headers in all supported config formats.
var configFileKeyRx = regexp.MustCompile(`(?m)^\s*\[?\s*"?([\w.]+)"?\s*[]=:]`) 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,
@ -863,7 +866,7 @@ func (s *Options) validateEnforceNonRootUser() error {
} }
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
@ -1019,6 +1022,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)
@ -1117,6 +1121,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))

View file

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

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
@ -213,12 +214,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 = " • "

View file

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

View file

@ -5,6 +5,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest" "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"
@ -13,8 +14,10 @@ import (
func TestAgents(t *testing.T) { func TestAgents(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, "Agents Test Suite") RunSpecs(t, "Agents Test Suite")
} }
var _ = configtest.RestoreAfterEachSpec() var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

View file

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

View file

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

View file

@ -3,6 +3,7 @@ package agents
import ( import (
"context" "context"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
) )
@ -13,6 +14,7 @@ type SessionKeys struct {
} }
func (sk *SessionKeys) Put(ctx context.Context, userId, sessionKey string) error { func (sk *SessionKeys) Put(ctx context.Context, userId, sessionKey string) error {
ctx = log.WithSecrets(ctx, sessionKey)
return sk.DataStore.UserProps().Put(ctx, userId, sk.KeyName, sessionKey) return sk.DataStore.UserProps().Put(ctx, userId, sk.KeyName, sessionKey)
} }

View file

@ -1,10 +1,14 @@
package agents package agents
import ( import (
"bytes"
"context" "context"
"os"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/persistence"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -12,30 +16,71 @@ import (
var _ = Describe("SessionKeys", func() { var _ = Describe("SessionKeys", func() {
var ctx context.Context var ctx context.Context
user := model.User{ID: "u-1"} var ds model.DataStore
ds := &tests.MockDataStore{MockedUserProps: &tests.MockedUserPropsRepo{}} var sk SessionKeys
sk := SessionKeys{DataStore: ds, KeyName: "fakeSessionKey"} user := model.User{ID: "u-1", UserName: "u-1"}
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context() ctx = GinkgoT().Context()
ds = persistence.New(db.Db())
Expect(ds.User().Put(ctx, &user)).To(Succeed())
sk = SessionKeys{DataStore: ds, KeyName: "fakeSessionKey"}
}) })
It("uses the assigned key name", func() { It("uses the assigned key name", func() {
Expect(sk.KeyName).To(Equal("fakeSessionKey")) other := SessionKeys{DataStore: ds, KeyName: "otherSessionKey"}
Expect(sk.Put(ctx, user.ID, "mine")).To(Succeed())
Expect(other.Put(ctx, user.ID, "theirs")).To(Succeed())
Expect(sk.Get(ctx, user.ID)).To(Equal("mine"))
}) })
It("stores a value in the DB", func() { It("stores a value in the DB", func() {
Expect(sk.Put(ctx, user.ID, "test-stored-value")).To(BeNil()) Expect(sk.Put(ctx, user.ID, "test-stored-value")).To(Succeed())
Expect(ds.UserProps().Get(ctx, user.ID, "fakeSessionKey")).To(Equal("test-stored-value"))
}) })
It("fetches the stored value", func() { It("fetches the stored value", func() {
Expect(ds.UserProps().Put(ctx, user.ID, "fakeSessionKey", "test-stored-value")).To(Succeed())
value, err := sk.Get(ctx, user.ID) value, err := sk.Get(ctx, user.ID)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(value).To(Equal("test-stored-value")) Expect(value).To(Equal("test-stored-value"))
}) })
It("deletes the stored value", func() { It("deletes the stored value", func() {
Expect(sk.Delete(ctx, user.ID)).To(BeNil()) Expect(ds.UserProps().Put(ctx, user.ID, "fakeSessionKey", "test-stored-value")).To(Succeed())
Expect(sk.Delete(ctx, user.ID)).To(Succeed())
_, err := ds.UserProps().Get(ctx, user.ID, "fakeSessionKey")
Expect(err).To(MatchError(model.ErrNotFound))
}) })
It("handles a not found value", func() { It("handles a not found value", func() {
_, err := sk.Get(ctx, "u-2") _, err := sk.Get(ctx, "u-2")
Expect(err).To(MatchError(model.ErrNotFound)) Expect(err).To(MatchError(model.ErrNotFound))
}) })
It("never logs the session key, but still logs the user id and key name", func() {
logged := model.User{ID: "logged-user-id", UserName: "logged-user-id"}
Expect(ds.User().Put(ctx, &logged)).To(Succeed())
dbKeys := SessionKeys{DataStore: ds, KeyName: "LastFMSessionKey"}
logs := &bytes.Buffer{}
log.SetOutput(logs)
log.SetLevel(log.LevelTrace)
DeferCleanup(func() {
log.SetOutput(os.Stderr)
log.SetLevel(log.LevelFatal)
})
Expect(dbKeys.Put(ctx, logged.ID, "inserted-session-key")).To(Succeed())
Expect(dbKeys.Put(ctx, logged.ID, "updated-session-key")).To(Succeed())
Expect(dbKeys.Get(ctx, logged.ID)).To(Equal("updated-session-key"))
Expect(logs.String()).To(ContainSubstring("INSERT INTO user_props"))
Expect(logs.String()).To(ContainSubstring("UPDATE user_props"))
Expect(logs.String()).To(ContainSubstring("logged-user-id"))
Expect(logs.String()).To(ContainSubstring("LastFMSessionKey"))
Expect(logs.String()).ToNot(ContainSubstring("inserted-session-key"))
Expect(logs.String()).ToNot(ContainSubstring("updated-session-key"))
})
}) })

View file

@ -0,0 +1,23 @@
package apiauth
import (
"testing"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestAPIAuth(t *testing.T) {
tests.Init(t, false)
log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail)
RunSpecs(t, "API Auth Suite")
}
var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

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

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

View file

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

View file

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

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

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

View file

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

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

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

View file

@ -0,0 +1,50 @@
package apiauth
import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("scopes", func() {
BeforeEach(func() {
saved := KnownScopes
KnownScopes = []string{ScopeRead, ScopePassword, ScopeAdmin, "playlists", "playlists:write"}
DeferCleanup(func() { KnownScopes = saved })
})
Describe("Entitled", func() {
It("stores all when nothing is requested", func() {
Expect(Entitled(nil, false)).To(Equal([]string{ScopeAll}))
})
It("drops unknown scopes and admin for non-admins", func() {
Expect(Entitled([]string{"read", "future", "admin"}, false)).To(Equal([]string{"read"}))
})
It("keeps admin for admins and keeps all", func() {
Expect(Entitled([]string{"admin", "all"}, true)).To(Equal([]string{"admin", "all"}))
})
})
Describe("Expand", func() {
It("replaces all with every known scope except admin for non-admins", func() {
Expect(Expand([]string{ScopeAll}, false)).To(Equal([]string{"password", "playlists", "playlists:write", "read"}))
})
It("includes admin for admins", func() {
Expect(Expand([]string{ScopeAll}, true)).To(ContainElement("admin"))
})
It("drops admin from explicit scopes when the user is no longer an admin", func() {
Expect(Expand([]string{"admin", "read"}, false)).To(Equal([]string{"read"}))
})
It("drops scopes that are no longer known", func() {
Expect(Expand([]string{"read", "retired"}, false)).To(Equal([]string{"read"}))
})
})
Describe("Satisfies", func() {
It("accepts the exact scope or its :write form", func() {
Expect(Satisfies([]string{"read"}, "read")).To(BeTrue())
Expect(Satisfies([]string{"playlists:write"}, "playlists")).To(BeTrue())
Expect(Satisfies([]string{"playlists"}, "playlists:write")).To(BeFalse())
Expect(Satisfies(nil, "read")).To(BeFalse())
})
})
})

20
core/apiauth/secret.go Normal file
View file

@ -0,0 +1,20 @@
package apiauth
import (
"crypto/sha256"
"encoding/hex"
"github.com/navidrome/navidrome/model/id"
)
const secretPrefix = "ndg_"
func newSecret() (secret, hash string) {
secret = secretPrefix + id.NewRandom()
return secret, hashSecret(secret)
}
func hashSecret(secret string) string {
sum := sha256.Sum256([]byte(secret))
return hex.EncodeToString(sum[:])
}

View file

@ -0,0 +1,23 @@
package apiauth
import (
"regexp"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("grant secrets", func() {
It("are ndg_ plus 22 base62 characters, hashed as hex SHA-256", func() {
secret, hash := newSecret()
Expect(secret).To(MatchRegexp(`^ndg_[0-9A-Za-z]{22}$`))
Expect(hash).To(MatchRegexp(`^[0-9a-f]{64}$`))
Expect(hashSecret(secret)).To(Equal(hash))
})
It("are unique", func() {
a, _ := newSecret()
b, _ := newSecret()
Expect(a).ToNot(Equal(b))
Expect(regexp.MustCompile(`^ndg_`).MatchString(a)).To(BeTrue())
})
})

264
core/apiauth/service.go Normal file
View file

@ -0,0 +1,264 @@
package apiauth
import (
"cmp"
"context"
"errors"
"fmt"
"time"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils/gg"
)
const (
IdleExpiry = consts.APIv1GrantIdleExpiry
touchInterval = 5 * time.Minute
)
var (
ErrPasswordManagedExternally = errors.New("password is managed externally")
ErrCurrentPasswordMismatch = errors.New("current password does not match")
)
type ClientMeta struct {
Name string
Client string
ClientVersion string
}
type Issued struct {
Secret string
Grant model.Grant
User model.User
}
type Principal struct {
User model.User
GrantID string
Scopes []string
}
type Service struct {
ds model.DataStore
checkers func(ds model.DataStore) []CredentialChecker // per datastore, so password change can check inside its transaction
now func() time.Time
}
func New(ds model.DataStore) *Service {
return &Service{
ds: ds,
checkers: func(ds model.DataStore) []CredentialChecker {
return []CredentialChecker{dbChecker{ds: ds}}
},
now: time.Now,
}
}
func PasswordChangeable(u model.User) bool {
return u.IsAdmin || conf.Server().EnableUserEditing
}
func (s *Service) Login(ctx context.Context, username, password string, meta ClientMeta, scopes []string) (*Issued, error) {
res, err := checkCredentials(ctx, s.checkers(s.ds), username, password)
if err != nil {
return nil, err
}
issued, err := s.issue(ctx, s.ds, *res.User, res.Provider, meta, scopes)
if err != nil {
return nil, err
}
if err := s.ds.User().UpdateLastLoginAt(ctx, res.User.ID); err != nil {
log.Warn(ctx, "API v1: could not update last login", "user", res.User.UserName, err)
}
return issued, nil
}
func (s *Service) Setup(ctx context.Context, username, password string, meta ClientMeta, scopes []string) (*Issued, error) {
var issued *Issued
_, err := auth.CreateFirstAdmin(ctx, s.ds, username, password, func(tx model.DataStore, u *model.User) error {
var err error
issued, err = s.issue(ctx, tx, *u, "setup", meta, scopes)
return err
})
if err != nil {
return nil, err
}
return issued, nil
}
// issue stores a grant bound to the epoch read with the user, so a racing password change leaves it dead.
func (s *Service) issue(ctx context.Context, ds model.DataStore, u model.User, provider string, meta ClientMeta, scopes []string) (*Issued, error) {
u.Password = ""
secret, hash := newSecret()
g := model.Grant{
UserID: u.ID,
Name: cmp.Or(meta.Name, meta.Client),
Client: meta.Client,
ClientVersion: meta.ClientVersion,
Scopes: Entitled(scopes, u.IsAdmin),
Provider: provider,
SecretHash: hash,
UserEpoch: u.TokenEpoch,
CreatedAt: s.now(),
}
if err := ds.Grant().Put(ctx, &g); err != nil {
return nil, fmt.Errorf("storing grant: %w", err)
}
return &Issued{Secret: secret, Grant: g, User: u}, nil
}
func (s *Service) Authenticate(ctx context.Context, secret, ip string) (*Principal, error) {
g, err := s.ds.Grant().FindBySecretHash(ctx, hashSecret(secret))
if errors.Is(err, model.ErrNotFound) {
return nil, model.ErrInvalidAuth
}
if err != nil {
return nil, err
}
if idleSince := s.now().Add(-IdleExpiry); g.LastActivity().Before(idleSince) {
s.dropIdle(ctx, g.ID, idleSince)
return nil, model.ErrInvalidAuth
}
u, err := s.ds.User().Get(ctx, g.UserID)
if errors.Is(err, model.ErrNotFound) {
return nil, model.ErrInvalidAuth
}
if err != nil {
return nil, err
}
if g.UserEpoch != u.TokenEpoch {
if g, u, err = s.settleEpoch(ctx, g.ID); err != nil {
return nil, err
}
}
s.touch(ctx, g, ip)
return &Principal{User: *u, GrantID: g.ID, Scopes: Expand(g.Scopes, u.IsAdmin)}, nil
}
// dropIdle deletes every grant still idle at idleSince, of any user, sparing one renewed meanwhile.
func (s *Service) dropIdle(ctx context.Context, id string, idleSince time.Time) {
if _, err := s.ds.Grant().DeleteIdle(ctx, idleSince); err != nil {
log.Warn(ctx, "API v1: could not delete idle grants", "grant", id, err)
}
}
// settleEpoch re-reads grant and user in one read transaction: separate reads can straddle a password change
// and make a kept grant look dead. Deleting below the snapshot's epoch is safe: a later change only moves kept grants up.
func (s *Service) settleEpoch(ctx context.Context, grantID string) (*model.Grant, *model.User, error) {
var g *model.Grant
var u *model.User
err := s.ds.WithTx(func(tx model.DataStore) error {
var err error
if g, err = tx.Grant().Get(ctx, grantID); err != nil {
return err
}
u, err = tx.User().Get(ctx, g.UserID)
return err
})
if errors.Is(err, model.ErrNotFound) {
return nil, nil, model.ErrInvalidAuth
}
if err != nil {
return nil, nil, err
}
if g.UserEpoch != u.TokenEpoch {
if err := s.ds.Grant().DeleteStaleEpochs(ctx, u.ID, u.TokenEpoch); err != nil {
log.Warn(ctx, "API v1: could not delete the user's grants from older epochs", "user", u.ID, "grant", grantID, err)
}
return nil, nil, model.ErrInvalidAuth
}
return g, u, nil
}
// touch writes last_used at most every touchInterval (zero lastUsed: never used); the SQL condition holds that across nodes.
func (s *Service) touch(ctx context.Context, g *model.Grant, ip string) {
now := s.now()
if lastUsed := gg.V(g.LastUsedAt); !lastUsed.IsZero() && now.Before(lastUsed.Add(touchInterval)) {
return
}
if err := s.ds.Grant().Touch(ctx, g.ID, ip, now, now.Add(-touchInterval)); err != nil {
log.Warn(ctx, "API v1: could not record grant use", "grant", g.ID, err)
}
}
// ListGrants shows only the current epoch: grants left on an older one are dead but only deleted when presented.
func (s *Service) ListGrants(ctx context.Context, p *Principal, offset, limit int) (model.Grants, int64, error) {
idleSince := s.now().Add(-IdleExpiry)
grants, err := s.ds.Grant().GetAllForUser(ctx, p.User.ID, p.User.TokenEpoch, idleSince, offset, limit)
if err != nil {
return nil, 0, err
}
total, err := s.ds.Grant().CountForUser(ctx, p.User.ID, p.User.TokenEpoch, idleSince)
return grants, total, err
}
func (s *Service) RevokeGrant(ctx context.Context, p *Principal, grantID string) error {
return s.ds.Grant().DeleteForUser(ctx, p.User.ID, grantID)
}
// Logout succeeds when the grant is already gone, e.g. revoked by another node or a concurrent logout.
func (s *Service) Logout(ctx context.Context, p *Principal) error {
err := s.RevokeGrant(ctx, p, p.GrantID)
if errors.Is(err, model.ErrNotFound) {
return nil
}
return err
}
// ChangePassword does every check inside the locked transaction, so a reset that lands first is never overwritten.
func (s *Service) ChangePassword(ctx context.Context, p *Principal, current, newPassword string, revokeOthers bool) error {
return s.ds.WithTxImmediate(func(tx model.DataStore) error {
u, err := tx.User().Get(ctx, p.User.ID)
if errors.Is(err, model.ErrNotFound) {
return model.ErrInvalidAuth
}
if err != nil {
return err
}
g, err := tx.Grant().Get(ctx, p.GrantID)
if errors.Is(err, model.ErrNotFound) {
return model.ErrInvalidAuth
}
if err != nil {
return err
}
if g.UserID != u.ID || g.UserEpoch != u.TokenEpoch {
return model.ErrInvalidAuth
}
if !PasswordChangeable(*u) {
return model.ErrNotAuthorized
}
res, err := checkCredentials(ctx, s.checkers(tx), u.UserName, current)
if errors.Is(err, model.ErrInvalidAuth) {
return ErrCurrentPasswordMismatch
}
if err != nil {
return err
}
if !res.PasswordLocal {
return ErrPasswordManagedExternally
}
oldEpoch := u.TokenEpoch
u.NewPassword = newPassword
if err := tx.User().Put(ctx, u); err != nil {
return err
}
updated, err := tx.User().Get(ctx, u.ID)
if err != nil {
return err
}
keep := ""
if revokeOthers {
keep = p.GrantID
}
if err := tx.Grant().SetEpoch(ctx, u.ID, oldEpoch, updated.TokenEpoch, keep); err != nil {
return err
}
return tx.Grant().DeleteStaleEpochs(ctx, u.ID, updated.TokenEpoch)
})
}

View file

@ -0,0 +1,461 @@
package apiauth
import (
"context"
"errors"
"strings"
"time"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var meta = ClientMeta{Name: "Living room", Client: "TestApp", ClientVersion: "1.0"}
var _ = Describe("Service", func() {
var ctx context.Context
var svc *Service
var now time.Time
BeforeEach(func() {
ctx = GinkgoT().Context()
now = time.Now().UTC().Truncate(time.Second)
svc = New(realDS)
svc.SetClock(func() time.Time { return now })
})
Describe("Login", func() {
It("creates a grant storing all, the user's epoch and the client metadata", func() {
u := createUser(ctx, "pw", false)
issued, err := svc.Login(ctx, u.UserName, "pw", meta, nil)
Expect(err).ToNot(HaveOccurred())
Expect(issued.Secret).To(HavePrefix("ndg_"))
Expect(issued.User.ID).To(Equal(u.ID))
Expect(issued.User.Password).To(BeEmpty())
Expect(issued.Grant.Scopes).To(Equal(model.Scopes{ScopeAll}))
Expect(issued.Grant.Provider).To(Equal("password"))
Expect(issued.Grant.Name).To(Equal("Living room"))
Expect(issued.Grant.UserEpoch).To(Equal(u.TokenEpoch))
stored, err := realDS.Grant().FindBySecretHash(ctx, hashSecret(issued.Secret))
Expect(err).ToNot(HaveOccurred())
Expect(stored.ID).To(Equal(issued.Grant.ID))
})
It("defaults the grant name to the client", func() {
u := createUser(ctx, "pw", false)
issued, err := svc.Login(ctx, u.UserName, "pw", ClientMeta{Client: "OnlyClient"}, nil)
Expect(err).ToNot(HaveOccurred())
Expect(issued.Grant.Name).To(Equal("OnlyClient"))
})
It("accepts the username in any case", func() {
u := createUser(ctx, "pw", false)
issued, err := svc.Login(ctx, strings.ToUpper(u.UserName), "pw", meta, nil)
Expect(err).ToNot(HaveOccurred())
Expect(issued.User.ID).To(Equal(u.ID))
})
It("stores only known requested scopes", func() {
u := createUser(ctx, "pw", false)
issued, err := svc.Login(ctx, u.UserName, "pw", meta, []string{"read", "future", "admin"})
Expect(err).ToNot(HaveOccurred())
Expect(issued.Grant.Scopes).To(Equal(model.Scopes{ScopeRead}))
})
It("fails with ErrInvalidAuth for bad credentials", func() {
u := createUser(ctx, "pw", false)
_, err := svc.Login(ctx, u.UserName, "wrong", meta, nil)
Expect(err).To(MatchError(model.ErrInvalidAuth))
})
})
Describe("Setup", func() {
It("refuses when users exist", func() {
createUser(ctx, "pw", false)
_, err := svc.Setup(ctx, "newadmin", "pw", meta, nil)
Expect(err).To(MatchError(auth.ErrSetupComplete))
})
// The empty-database path is covered end to end in server/apiv1, which owns a fresh DB.
})
Describe("Authenticate", func() {
It("resolves the secret to its user and the grant's expanded scopes", func() {
u := createUser(ctx, "pw", false)
issued, p := login(ctx, svc, u, "pw", nil)
Expect(p.User.ID).To(Equal(u.ID))
Expect(p.GrantID).To(Equal(issued.Grant.ID))
Expect(p.Scopes).To(Equal([]string{ScopeGrants, ScopePassword, ScopeRead}))
})
It("carries only the scopes stored on a narrow grant", func() {
u := createUser(ctx, "pw", false)
_, p := login(ctx, svc, u, "pw", []string{ScopePassword})
Expect(p.Scopes).To(Equal([]string{ScopePassword}))
})
It("records the first use with the client IP", func() {
u := createUser(ctx, "pw", false)
issued, _ := svc.Login(ctx, u.UserName, "pw", meta, nil)
_, err := svc.Authenticate(ctx, issued.Secret, "10.0.0.9")
Expect(err).ToNot(HaveOccurred())
g, _ := realDS.Grant().Get(ctx, issued.Grant.ID)
Expect(g.LastUsedAt).ToNot(BeNil())
Expect(g.LastUsedIP).To(Equal("10.0.0.9"))
})
It("records use again only after the touch interval", func() {
u := createUser(ctx, "pw", false)
issued, _ := svc.Login(ctx, u.UserName, "pw", meta, nil)
_, err := svc.Authenticate(ctx, issued.Secret, "10.0.0.1")
Expect(err).ToNot(HaveOccurred())
now = now.Add(touchInterval - time.Second)
_, err = svc.Authenticate(ctx, issued.Secret, "10.0.0.2")
Expect(err).ToNot(HaveOccurred())
g, _ := realDS.Grant().Get(ctx, issued.Grant.ID)
Expect(g.LastUsedIP).To(Equal("10.0.0.1"))
now = now.Add(2 * time.Second)
_, err = svc.Authenticate(ctx, issued.Secret, "10.0.0.3")
Expect(err).ToNot(HaveOccurred())
g, _ = realDS.Grant().Get(ctx, issued.Grant.ID)
Expect(g.LastUsedIP).To(Equal("10.0.0.3"))
Expect(g.LastUsedAt.Equal(now)).To(BeTrue())
})
It("rejects unknown secrets", func() {
_, err := svc.Authenticate(ctx, "ndg_unknown", "")
Expect(err).To(MatchError(model.ErrInvalidAuth))
})
It("deletes and rejects a grant idle for 90 days, including one never used", func() {
u := createUser(ctx, "pw", false)
issued, _ := svc.Login(ctx, u.UserName, "pw", meta, nil)
now = now.Add(IdleExpiry + time.Second)
_, err := svc.Authenticate(ctx, issued.Secret, "")
Expect(err).To(MatchError(model.ErrInvalidAuth))
_, err = realDS.Grant().Get(ctx, issued.Grant.ID)
Expect(err).To(MatchError(model.ErrNotFound))
})
It("keeps an idle grant that a concurrent request renewed before the delete ran", func() {
u := createUser(ctx, "pw", false)
issued, _ := svc.Login(ctx, u.UserName, "pw", meta, nil)
renewedAt := now.Add(IdleExpiry - time.Minute)
racing := New(hookDS{DataStore: realDS, beforeDeleteIdle: func() {
Expect(realDS.Grant().Touch(ctx, issued.Grant.ID, "10.0.0.2", renewedAt, renewedAt)).To(Succeed())
}})
now = now.Add(IdleExpiry + time.Second)
racing.SetClock(func() time.Time { return now })
_, err := racing.Authenticate(ctx, issued.Secret, "")
Expect(err).To(MatchError(model.ErrInvalidAuth))
g, err := realDS.Grant().Get(ctx, issued.Grant.ID)
Expect(err).ToNot(HaveOccurred())
Expect(g.LastUsedIP).To(Equal("10.0.0.2"))
})
It("rejects and deletes a grant whose epoch is behind the user's", func() {
u := createUser(ctx, "pw", false)
issued, _ := svc.Login(ctx, u.UserName, "pw", meta, nil)
u.NewPassword = "changed-elsewhere"
Expect(realDS.User().Put(ctx, &u)).To(Succeed())
_, err := svc.Authenticate(ctx, issued.Secret, "")
Expect(err).To(MatchError(model.ErrInvalidAuth))
_, err = realDS.Grant().Get(ctx, issued.Grant.ID)
Expect(err).To(MatchError(model.ErrNotFound))
})
It("does not delete a kept grant when the password changed between reading the grant and the user", func() {
u := createUser(ctx, "pw", false)
issued, p := login(ctx, svc, u, "pw", nil)
racing := New(hookDS{DataStore: realDS, afterFind: func() {
Expect(svc.ChangePassword(request.WithUser(ctx, p.User), p, "pw", "pw2", false)).To(Succeed())
}})
racing.SetClock(func() time.Time { return now })
_, err := racing.Authenticate(ctx, issued.Secret, "")
Expect(err).ToNot(HaveOccurred())
_, err = realDS.Grant().Get(ctx, p.GrantID)
Expect(err).ToNot(HaveOccurred())
})
It("drops admin from a grant once its user is no longer an admin", func() {
saved := KnownScopes
KnownScopes = []string{ScopeRead, ScopePassword, ScopeAdmin}
DeferCleanup(func() { KnownScopes = saved })
u := createUser(ctx, "pw", true)
issued, p := login(ctx, svc, u, "pw", nil)
Expect(p.Scopes).To(ContainElement(ScopeAdmin))
u.IsAdmin = false
Expect(realDS.User().Put(ctx, &u)).To(Succeed())
demoted, err := svc.Authenticate(ctx, issued.Secret, "")
Expect(err).ToNot(HaveOccurred())
Expect(demoted.Scopes).To(Equal([]string{ScopePassword, ScopeRead}))
})
It("rejects the secret after its user is deleted, and the grant row is gone", func() {
u := createUser(ctx, "pw", false)
issued, _ := login(ctx, svc, u, "pw", nil)
Expect(realDS.User().Delete(request.WithUser(ctx, model.User{IsAdmin: true}), u.ID)).To(Succeed())
_, err := realDS.Grant().Get(ctx, issued.Grant.ID)
Expect(err).To(MatchError(model.ErrNotFound))
_, err = svc.Authenticate(ctx, issued.Secret, "")
Expect(err).To(MatchError(model.ErrInvalidAuth))
})
It("leaves a login that raced a password change with a dead grant", func() {
u := createUser(ctx, "pw", false)
reached, release := make(chan struct{}), make(chan struct{})
svc.SetCheckers(func(ds model.DataStore) []CredentialChecker {
return []CredentialChecker{pausingChecker{inner: dbChecker{ds: ds}, reached: reached, release: release}}
})
var issued *Issued
var loginErr error
done := make(chan struct{})
go func() {
defer GinkgoRecover()
defer close(done)
issued, loginErr = svc.Login(ctx, u.UserName, "pw", meta, nil)
}()
<-reached // credentials (and the old epoch) were read
u.NewPassword = "changed-meanwhile"
Expect(realDS.User().Put(ctx, &u)).To(Succeed())
close(release)
<-done
Expect(loginErr).ToNot(HaveOccurred())
_, err := svc.Authenticate(ctx, issued.Secret, "")
Expect(err).To(MatchError(model.ErrInvalidAuth))
})
})
Describe("grant management", func() {
It("lists the user's grants and marks the current one", func() {
u := createUser(ctx, "pw", false)
first, _ := login(ctx, svc, u, "pw", nil)
_, p := login(ctx, svc, u, "pw", nil)
grants, total, err := svc.ListGrants(ctx, p, 0, 10)
Expect(err).ToNot(HaveOccurred())
Expect(total).To(Equal(int64(2)))
Expect(grants).To(HaveLen(2))
Expect([]string{grants[0].ID, grants[1].ID}).To(ContainElements(first.Grant.ID, p.GrantID))
})
It("lists only grants on the user's current epoch", func() {
u := createUser(ctx, "pw", false)
login(ctx, svc, u, "pw", nil)
u.NewPassword = "reset-by-admin" // old-UI reset leaves the old grant on the previous epoch
Expect(realDS.User().Put(ctx, &u)).To(Succeed())
issued, p := login(ctx, svc, u, "reset-by-admin", nil)
grants, total, err := svc.ListGrants(ctx, p, 0, 10)
Expect(err).ToNot(HaveOccurred())
Expect(total).To(Equal(int64(1)))
Expect(grants).To(HaveLen(1))
Expect(grants[0].ID).To(Equal(issued.Grant.ID))
})
It("logs out, and succeeds again when the grant is already gone", func() {
u := createUser(ctx, "pw", false)
issued, p := login(ctx, svc, u, "pw", nil)
Expect(svc.Logout(ctx, p)).To(Succeed())
_, err := svc.Authenticate(ctx, issued.Secret, "")
Expect(err).To(MatchError(model.ErrInvalidAuth))
Expect(svc.Logout(ctx, p)).To(Succeed())
})
It("refuses to revoke another user's grant", func() {
alice := createUser(ctx, "pw", false)
bob := createUser(ctx, "pw", false)
aliceGrant, _ := login(ctx, svc, alice, "pw", nil)
_, bobP := login(ctx, svc, bob, "pw", nil)
Expect(svc.RevokeGrant(ctx, bobP, aliceGrant.Grant.ID)).To(MatchError(model.ErrNotFound))
_, err := svc.Authenticate(ctx, aliceGrant.Secret, "")
Expect(err).ToNot(HaveOccurred())
})
It("rejects the secret after its grant is revoked", func() {
u := createUser(ctx, "pw", false)
other, _ := login(ctx, svc, u, "pw", nil)
_, p := login(ctx, svc, u, "pw", nil)
Expect(svc.RevokeGrant(ctx, p, other.Grant.ID)).To(Succeed())
_, err := svc.Authenticate(ctx, other.Secret, "")
Expect(err).To(MatchError(model.ErrInvalidAuth))
})
})
Describe("ChangePassword", func() {
It("revokes other grants by default and keeps the caller's", func() {
u := createUser(ctx, "pw", false)
other, _ := login(ctx, svc, u, "pw", nil)
mine, p := login(ctx, svc, u, "pw", nil)
Expect(svc.ChangePassword(request.WithUser(ctx, p.User), p, "pw", "pw2", true)).To(Succeed())
_, err := svc.Authenticate(ctx, mine.Secret, "")
Expect(err).ToNot(HaveOccurred())
_, err = svc.Authenticate(ctx, other.Secret, "")
Expect(err).To(MatchError(model.ErrInvalidAuth))
_, err = svc.Login(ctx, u.UserName, "pw2", meta, nil)
Expect(err).ToNot(HaveOccurred())
})
It("keeps every grant, the caller's included, when revokeOthers is false", func() {
u := createUser(ctx, "pw", false)
other, _ := login(ctx, svc, u, "pw", nil)
mine, p := login(ctx, svc, u, "pw", nil)
Expect(svc.ChangePassword(request.WithUser(ctx, p.User), p, "pw", "pw2", false)).To(Succeed())
_, err := svc.Authenticate(ctx, other.Secret, "")
Expect(err).ToNot(HaveOccurred())
_, err = svc.Authenticate(ctx, mine.Secret, "")
Expect(err).ToNot(HaveOccurred())
})
It("rejects a wrong current password without changing anything", func() {
u := createUser(ctx, "pw", false)
_, p := login(ctx, svc, u, "pw", nil)
err := svc.ChangePassword(request.WithUser(ctx, p.User), p, "wrong", "pw2", true)
Expect(err).To(MatchError(ErrCurrentPasswordMismatch))
_, err = svc.Login(ctx, u.UserName, "pw", meta, nil)
Expect(err).ToNot(HaveOccurred())
})
It("is forbidden for non-admins when user editing is off", func() {
conf.Update(func(c *conf.Options) { c.EnableUserEditing = false })
u := createUser(ctx, "pw", false)
_, p := login(ctx, svc, u, "pw", nil)
err := svc.ChangePassword(request.WithUser(ctx, p.User), p, "pw", "pw2", true)
Expect(err).To(MatchError(model.ErrNotAuthorized))
})
It("does not revive grants killed by an earlier reset when keeping grants", func() {
u := createUser(ctx, "pw", false)
killed, _ := login(ctx, svc, u, "pw", nil)
u.NewPassword = "reset-by-admin" // old-UI reset: the killed grant stays on the old epoch until presented
Expect(realDS.User().Put(ctx, &u)).To(Succeed())
_, p2 := login(ctx, svc, u, "reset-by-admin", nil)
Expect(svc.ChangePassword(request.WithUser(ctx, p2.User), p2, "reset-by-admin", "pw3", false)).To(Succeed())
_, err := svc.Authenticate(ctx, killed.Secret, "")
Expect(err).To(MatchError(model.ErrInvalidAuth))
})
It("rejects a caller whose grant was revoked before the change ran", func() {
u := createUser(ctx, "pw", false)
_, p := login(ctx, svc, u, "pw", nil)
Expect(realDS.Grant().DeleteForUser(ctx, u.ID, p.GrantID)).To(Succeed())
err := svc.ChangePassword(request.WithUser(ctx, p.User), p, "pw", "pw2", true)
Expect(err).To(MatchError(model.ErrInvalidAuth))
_, err = svc.Login(ctx, u.UserName, "pw", meta, nil)
Expect(err).ToNot(HaveOccurred())
})
It("rejects a caller naming another user's grant", func() {
alice := createUser(ctx, "pw", false)
bob := createUser(ctx, "pw", false)
_, aliceP := login(ctx, svc, alice, "pw", nil)
bobGrant, _ := login(ctx, svc, bob, "pw", nil)
forged := &Principal{User: aliceP.User, GrantID: bobGrant.Grant.ID}
err := svc.ChangePassword(request.WithUser(ctx, alice), forged, "pw", "pw2", true)
Expect(err).To(MatchError(model.ErrInvalidAuth))
})
It("rolls back the password and epoch when a grant update fails", func() {
u := createUser(ctx, "pw", false)
issued, p := login(ctx, svc, u, "pw", nil)
failing := New(failingEpochDS{realDS})
failing.SetClock(func() time.Time { return now })
err := failing.ChangePassword(request.WithUser(ctx, p.User), p, "pw", "pw2", true)
Expect(err).To(MatchError(ContainSubstring("boom")))
reloaded, _ := realDS.User().Get(ctx, u.ID)
Expect(reloaded.TokenEpoch).To(Equal(u.TokenEpoch))
_, err = svc.Login(ctx, u.UserName, "pw", meta, nil)
Expect(err).ToNot(HaveOccurred())
_, err = svc.Authenticate(ctx, issued.Secret, "")
Expect(err).ToNot(HaveOccurred())
})
})
Describe("PasswordChangeable", func() {
It("follows EnableUserEditing for non-admins only", func() {
conf.Update(func(c *conf.Options) { c.EnableUserEditing = false })
Expect(PasswordChangeable(model.User{IsAdmin: true})).To(BeTrue())
Expect(PasswordChangeable(model.User{})).To(BeFalse())
conf.Update(func(c *conf.Options) { c.EnableUserEditing = true })
Expect(PasswordChangeable(model.User{})).To(BeTrue())
})
})
})
// hookDS runs its optional callbacks inside grant lookups, to land a concurrent change mid-Authenticate.
type hookDS struct {
model.DataStore
afterFind func()
beforeDeleteIdle func()
}
func (d hookDS) Grant() model.GrantRepository {
return hookGrants{GrantRepository: d.DataStore.Grant(), hooks: d}
}
type hookGrants struct {
model.GrantRepository
hooks hookDS
}
func (g hookGrants) FindBySecretHash(ctx context.Context, hash string) (*model.Grant, error) {
found, err := g.GrantRepository.FindBySecretHash(ctx, hash)
if g.hooks.afterFind != nil {
g.hooks.afterFind()
}
return found, err
}
func (g hookGrants) DeleteIdle(ctx context.Context, idleSince time.Time) (int64, error) {
if g.hooks.beforeDeleteIdle != nil {
g.hooks.beforeDeleteIdle()
}
return g.GrantRepository.DeleteIdle(ctx, idleSince)
}
type pausingChecker struct {
inner CredentialChecker
reached, release chan struct{}
}
func (c pausingChecker) Check(ctx context.Context, username, password string) (CredentialResult, error) {
res, err := c.inner.Check(ctx, username, password)
close(c.reached)
<-c.release
return res, err
}
// failingEpochDS makes SetEpoch fail inside WithTxImmediate, to prove the whole change rolls back.
type failingEpochDS struct{ model.DataStore }
func (f failingEpochDS) WithTxImmediate(block func(tx model.DataStore) error, scope ...string) error {
return f.DataStore.WithTxImmediate(func(tx model.DataStore) error {
return block(failingEpochTx{tx})
}, scope...)
}
type failingEpochTx struct{ model.DataStore }
func (f failingEpochTx) Grant() model.GrantRepository { return failingGrants{f.DataStore.Grant()} }
type failingGrants struct{ model.GrantRepository }
func (failingGrants) SetEpoch(context.Context, string, int, int, string) error {
return errors.New("boom")
}

View file

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

View file

@ -8,14 +8,16 @@ import (
"io" "io"
"strings" "strings"
"github.com/Masterminds/squirrel"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core" "github.com/navidrome/navidrome/core"
"github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core/artwork"
"github.com/navidrome/navidrome/core/stream" "github.com/navidrome/navidrome/core/stream"
"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/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/utils/slice"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/stretchr/testify/mock" "github.com/stretchr/testify/mock"
@ -27,59 +29,76 @@ var _ = Describe("Archiver", func() {
arch core.Archiver arch core.Archiver
ms *mockMediaStreamer ms *mockMediaStreamer
dc *fakeDecider dc *fakeDecider
ds *mockDataStore ds model.DataStore
sh *mockShare sh *mockShare
ca *mockCoverArt ca *mockCoverArt
) )
putTracks := func(mfs ...model.MediaFile) []string {
GinkgoHelper()
return slice.Map(persistencetest.PutMediaFiles(ctx, ds, mfs...), func(mf model.MediaFile) string { return mf.ID })
}
byArtist := func(id string, mfs ...model.MediaFile) []model.MediaFile {
for i := range mfs {
mfs[i].Participants = model.Participants{model.RoleAlbumArtist: {{ID: id, Name: "Artist " + id}}}
}
return mfs
}
putPlaylist := func(id, name string, tracks ...model.MediaFile) {
GinkgoHelper()
ids := putTracks(tracks...)
Expect(ds.Playlist().Put(ctx, &model.Playlist{ID: id, Name: name, OwnerID: "user-1"})).To(Succeed())
_, err := ds.Playlist().Tracks(ctx, id, false).Add(ctx, ids)
Expect(err).ToNot(HaveOccurred())
}
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context() ctx = GinkgoT().Context()
ds = persistence.New(db.Db())
user := model.User{ID: "user-1", UserName: "user-1"}
Expect(ds.User().Put(ctx, &user)).To(Succeed())
ctx = request.WithUser(ctx, user)
for _, id := range []string{"1", "2"} {
Expect(ds.Artist().Put(ctx, &model.Artist{ID: id, Name: "Artist " + id})).To(Succeed())
}
ms = &mockMediaStreamer{} ms = &mockMediaStreamer{}
dc = &fakeDecider{} dc = &fakeDecider{}
sh = &mockShare{} sh = &mockShare{}
ds = &mockDataStore{}
ca = &mockCoverArt{images: map[string][]byte{}} ca = &mockCoverArt{images: map[string][]byte{}}
arch = core.NewArchiver(ms, dc, ds, sh, ca) arch = core.NewArchiver(ms, dc, ds, sh, ca)
}) })
Context("ZipAlbum", func() { Context("ZipAlbum", func() {
It("zips an album correctly", func() { It("zips an album correctly", func() {
mfs := model.MediaFiles{ putTracks(
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1}, model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1, TrackNumber: 2},
{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1}, model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1, TrackNumber: 1},
} model.MediaFile{Path: "other/01 - other.mp3", Suffix: "mp3", AlbumID: "2", Album: "Other", DiscNumber: 1},
)
mfRepo := &mockMediaFileRepository{}
mfRepo.On("GetAll", []model.QueryOptions{{
Filters: squirrel.Eq{"album_id": "1"},
Sort: "album",
}}).Return(mfs, nil)
ds.On("MediaFile").Return(mfRepo)
ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(3) ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(3)
out := new(bytes.Buffer) out := new(bytes.Buffer)
err := arch.ZipAlbum(ctx, "1", "mp3", 128, out) err := arch.ZipAlbum(ctx, "1", "mp3", 128, out)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(zr.File)).To(Equal(2)) Expect(zr.File).To(HaveLen(2))
Expect(zr.File[0].Name).To(Equal("Album_Promo/01 - track1.mp3")) Expect(zr.File[0].Name).To(Equal("Album_Promo/01 - track1.mp3"))
Expect(zr.File[1].Name).To(Equal("Album_Promo/02 - track2.mp3")) Expect(zr.File[1].Name).To(Equal("Album_Promo/02 - track2.mp3"))
}) })
It("streams the request resolved by the transcode decider and names the entry after its format", func() { It("streams the request resolved by the transcode decider and names the entry after its format", func() {
mfRepo := &mockMediaFileRepository{} putTracks(model.MediaFile{Path: "test_data/01 - track1.flac", Suffix: "flac", AlbumID: "1"})
mfRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{{Path: "test_data/01 - track1.flac", Suffix: "flac", AlbumID: "1"}}, nil)
ds.On("MediaFile").Return(mfRepo)
resolved := stream.Request{Format: "opus", BitRate: 128, SampleRate: 48000, Channels: 2} resolved := stream.Request{Format: "opus", BitRate: 128, SampleRate: 48000, Channels: 2}
dc.resolved = &resolved dc.resolved = &resolved
ms.On("NewStream", mock.Anything, mock.Anything, resolved).Return(io.NopCloser(strings.NewReader("test")), nil).Once() ms.On("NewStream", mock.Anything, mock.Anything, resolved).Return(io.NopCloser(strings.NewReader("test")), nil).Once()
out := new(bytes.Buffer) out := new(bytes.Buffer)
Expect(arch.ZipAlbum(GinkgoT().Context(), "1", "mp3", 128, out)).To(Succeed()) Expect(arch.ZipAlbum(ctx, "1", "mp3", 128, out)).To(Succeed())
ms.AssertExpectations(GinkgoT()) ms.AssertExpectations(GinkgoT())
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
@ -90,31 +109,24 @@ var _ = Describe("Archiver", func() {
Context("ZipArtist", func() { Context("ZipArtist", func() {
It("zips an artist's albums correctly", func() { It("zips an artist's albums correctly", func() {
mfs := model.MediaFiles{ putTracks(byArtist("1",
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumArtistID: "1", AlbumID: "1", Album: "Album 1", DiscNumber: 1}, model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, TrackNumber: 1},
{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumArtistID: "1", AlbumID: "1", Album: "Album 1", DiscNumber: 1}, model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, TrackNumber: 2},
} model.MediaFile{Path: "test_data/03 - missing.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, TrackNumber: 3, Missing: true},
)...)
mfRepo := &mockMediaFileRepository{} putTracks(byArtist("2",
mfRepo.On("GetAll", []model.QueryOptions{{ model.MediaFile{Path: "other/01 - other.mp3", Suffix: "mp3", AlbumID: "2", Album: "Other", DiscNumber: 1},
Filters: squirrel.And{ )...)
persistence.ParticipantIDFilter("media_file", "1", model.RoleAlbumArtist),
squirrel.Eq{"missing": false},
},
Sort: "album",
}}).Return(mfs, nil)
ds.On("MediaFile").Return(mfRepo)
ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2) ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2)
out := new(bytes.Buffer) out := new(bytes.Buffer)
err := arch.ZipArtist(ctx, "1", "mp3", 128, out) err := arch.ZipArtist(ctx, "1", "mp3", 128, out)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(zr.File)).To(Equal(2)) Expect(zr.File).To(HaveLen(2))
Expect(zr.File[0].Name).To(Equal("Album 1/01 - track1.mp3")) Expect(zr.File[0].Name).To(Equal("Album 1/01 - track1.mp3"))
Expect(zr.File[1].Name).To(Equal("Album 1/02 - track2.mp3")) Expect(zr.File[1].Name).To(Equal("Album 1/02 - track2.mp3"))
}) })
@ -123,15 +135,13 @@ var _ = Describe("Archiver", func() {
// zipArtistEntries zips the given tracks as artist "1" and returns the entry names in zip order. // zipArtistEntries zips the given tracks as artist "1" and returns the entry names in zip order.
zipArtistEntries := func(mfs model.MediaFiles) []string { zipArtistEntries := func(mfs model.MediaFiles) []string {
mfRepo := &mockMediaFileRepository{} putTracks(byArtist("1", mfs...)...)
mfRepo.On("GetAll", mock.Anything).Return(mfs, nil)
ds.On("MediaFile", mock.Anything).Return(mfRepo)
ms.On("NewStream", mock.Anything, mock.Anything, mock.Anything).Return(io.NopCloser(strings.NewReader("test")), nil) ms.On("NewStream", mock.Anything, mock.Anything, mock.Anything).Return(io.NopCloser(strings.NewReader("test")), nil)
out := new(bytes.Buffer) out := new(bytes.Buffer)
Expect(arch.ZipArtist(ctx, "1", "mp3", 128, out)).To(Succeed()) Expect(arch.ZipArtist(ctx, "1", "mp3", 128, out)).To(Succeed())
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
names := make([]string, len(zr.File)) names := make([]string, len(zr.File))
for i, f := range zr.File { for i, f := range zr.File {
names[i] = f.Name names[i] = f.Name
@ -141,10 +151,10 @@ var _ = Describe("Archiver", func() {
It("keeps the albums in query order", func() { It("keeps the albums in query order", func() {
names := zipArtistEntries(model.MediaFiles{ names := zipArtistEntries(model.MediaFiles{
{Path: "a/01.mp3", Suffix: "mp3", AlbumID: "3", Album: "Album C"}, {Path: "c/01.mp3", Suffix: "mp3", AlbumID: "3", Album: "Album C", OrderAlbumName: "1"},
{Path: "a/01.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album A"}, {Path: "a/01.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album A", OrderAlbumName: "2", TrackNumber: 1},
{Path: "a/02.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album A"}, {Path: "a/02.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album A", OrderAlbumName: "2", TrackNumber: 2},
{Path: "a/01.mp3", Suffix: "mp3", AlbumID: "2", Album: "Album B"}, {Path: "b/01.mp3", Suffix: "mp3", AlbumID: "2", Album: "Album B", OrderAlbumName: "3"},
}) })
Expect(names).To(Equal([]string{"Album C/01.mp3", "Album A/01.mp3", "Album A/02.mp3", "Album B/01.mp3"})) Expect(names).To(Equal([]string{"Album C/01.mp3", "Album A/01.mp3", "Album A/02.mp3", "Album B/01.mp3"}))
}) })
@ -253,17 +263,10 @@ var _ = Describe("Archiver", func() {
Context("when the transcode limiter rejects a file", func() { Context("when the transcode limiter rejects a file", func() {
It("aborts the archive instead of continuing with empty entries", func() { It("aborts the archive instead of continuing with empty entries", func() {
mfs := model.MediaFiles{ putTracks(
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1}, model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1, TrackNumber: 1},
{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1}, model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1, TrackNumber: 2},
} )
mfRepo := &mockMediaFileRepository{}
mfRepo.On("GetAll", []model.QueryOptions{{
Filters: squirrel.Eq{"album_id": "1"},
Sort: "album",
}}).Return(mfs, nil)
ds.On("MediaFile").Return(mfRepo)
ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}). ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).
Return(nil, stream.ErrTooManyTranscodes).Once() Return(nil, stream.ErrTooManyTranscodes).Once()
@ -296,16 +299,16 @@ var _ = Describe("Archiver", func() {
out := new(bytes.Buffer) out := new(bytes.Buffer)
err := arch.ZipShare(ctx, share, out) err := arch.ZipShare(ctx, share, out)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
// Share.Load records a visit; re-loading here would double-count // Share.Load records a visit; re-loading here would double-count
// every download. // every download.
sh.AssertNotCalled(GinkgoT(), "Load", mock.Anything, mock.Anything) sh.AssertNotCalled(GinkgoT(), "Load", mock.Anything, mock.Anything)
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(zr.File)).To(Equal(2)) Expect(zr.File).To(HaveLen(2))
Expect(zr.File[0].Name).To(Equal("01 - Artist 1 - track1.mp3")) Expect(zr.File[0].Name).To(Equal("01 - Artist 1 - track1.mp3"))
Expect(zr.File[1].Name).To(Equal("02 - Artist 2 - track2.mp3")) Expect(zr.File[1].Name).To(Equal("02 - Artist 2 - track2.mp3"))
@ -314,17 +317,14 @@ var _ = Describe("Archiver", func() {
Context("ZipPlaylist", func() { Context("ZipPlaylist", func() {
It("names the entries and the M3U lines after the resolved format", func() { It("names the entries and the M3U lines after the resolved format", func() {
pls := &model.Playlist{ID: "1", Name: "Test Playlist", Tracks: []model.PlaylistTrack{ putPlaylist("1", "Test Playlist",
{MediaFile: model.MediaFile{Path: "test_data/01 - track1.flac", Suffix: "flac", Artist: "Artist 1", Title: "track1"}}, model.MediaFile{Path: "test_data/01 - track1.flac", Suffix: "flac", Artist: "Artist 1", Title: "track1"},
}} )
plRepo := &mockPlaylistRepository{}
plRepo.On("GetWithTracks", "1", true, false).Return(pls, nil)
ds.On("Playlist").Return(plRepo)
dc.resolved = &stream.Request{Format: "opus", BitRate: 128} dc.resolved = &stream.Request{Format: "opus", BitRate: 128}
ms.On("NewStream", mock.Anything, mock.Anything, *dc.resolved).Return(io.NopCloser(strings.NewReader("test")), nil) ms.On("NewStream", mock.Anything, mock.Anything, *dc.resolved).Return(io.NopCloser(strings.NewReader("test")), nil)
out := new(bytes.Buffer) out := new(bytes.Buffer)
Expect(arch.ZipPlaylist(GinkgoT().Context(), "1", "mp3", 128, out)).To(Succeed()) Expect(arch.ZipPlaylist(ctx, "1", "mp3", 128, out)).To(Succeed())
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -338,41 +338,31 @@ var _ = Describe("Archiver", func() {
}) })
It("zips a playlist correctly", func() { It("zips a playlist correctly", func() {
tracks := []model.PlaylistTrack{ putPlaylist("1", "Test Playlist",
{MediaFile: model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "AC/DC", Title: "track1"}}, model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "AC/DC", Title: "track1"},
{MediaFile: model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "Artist 2", Title: "track2"}}, model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "Artist 2", Title: "track2"},
} )
pls := &model.Playlist{
ID: "1",
Name: "Test Playlist",
Tracks: tracks,
}
plRepo := &mockPlaylistRepository{}
plRepo.On("GetWithTracks", "1", true, false).Return(pls, nil)
ds.On("Playlist").Return(plRepo)
ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2) ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2)
out := new(bytes.Buffer) out := new(bytes.Buffer)
err := arch.ZipPlaylist(ctx, "1", "mp3", 128, out) err := arch.ZipPlaylist(ctx, "1", "mp3", 128, out)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len()))
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(len(zr.File)).To(Equal(3)) Expect(zr.File).To(HaveLen(3))
Expect(zr.File[0].Name).To(Equal("01 - AC_DC - track1.mp3")) Expect(zr.File[0].Name).To(Equal("01 - AC_DC - track1.mp3"))
Expect(zr.File[1].Name).To(Equal("02 - Artist 2 - track2.mp3")) Expect(zr.File[1].Name).To(Equal("02 - Artist 2 - track2.mp3"))
Expect(zr.File[2].Name).To(Equal("Test Playlist.m3u")) Expect(zr.File[2].Name).To(Equal("Test Playlist.m3u"))
// Verify M3U content // Verify M3U content
m3uFile, err := zr.File[2].Open() m3uFile, err := zr.File[2].Open()
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
defer m3uFile.Close() defer m3uFile.Close()
m3uContent, err := io.ReadAll(m3uFile) m3uContent, err := io.ReadAll(m3uFile)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
expectedM3U := "#EXTM3U\n#PLAYLIST:Test Playlist\n#EXTINF:0,AC/DC - track1\n01 - AC_DC - track1.mp3\n#EXTINF:0,Artist 2 - track2\n02 - Artist 2 - track2.mp3\n" expectedM3U := "#EXTM3U\n#PLAYLIST:Test Playlist\n#EXTINF:0,AC/DC - track1\n01 - AC_DC - track1.mp3\n#EXTINF:0,Artist 2 - track2\n02 - Artist 2 - track2.mp3\n"
Expect(string(m3uContent)).To(Equal(expectedM3U)) Expect(string(m3uContent)).To(Equal(expectedM3U))
@ -384,18 +374,15 @@ var _ = Describe("Archiver", func() {
pngData = []byte("\x89PNG\x0d\x0a\x1a\x0a fake png") pngData = []byte("\x89PNG\x0d\x0a\x1a\x0a fake png")
) )
mockAlbumTracks := func(filter squirrel.Sqlizer, mfs model.MediaFiles) { putAlbumTracks := func(mfs ...model.MediaFile) {
mfRepo := &mockMediaFileRepository{} GinkgoHelper()
mfRepo.On("GetAll", []model.QueryOptions{{Filters: filter, Sort: "album"}}).Return(mfs, nil) putTracks(mfs...)
ds.On("MediaFile", mock.Anything).Return(mfRepo)
ms.On("NewStream", mock.Anything, mock.Anything, mock.Anything).Return(io.NopCloser(strings.NewReader("test")), nil) ms.On("NewStream", mock.Anything, mock.Anything, mock.Anything).Return(io.NopCloser(strings.NewReader("test")), nil)
} }
It("adds the album cover to the album folder", func() { It("adds the album cover to the album folder", func() {
ca.images["al-1"] = jpegData ca.images["al-1"] = jpegData
mockAlbumTracks(squirrel.Eq{"album_id": "1"}, model.MediaFiles{ putAlbumTracks(model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1})
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1},
})
out := new(bytes.Buffer) out := new(bytes.Buffer)
Expect(arch.ZipAlbum(ctx, "1", "mp3", 128, out)).To(Succeed()) Expect(arch.ZipAlbum(ctx, "1", "mp3", 128, out)).To(Succeed())
@ -410,13 +397,10 @@ var _ = Describe("Archiver", func() {
ca.images["ar-1"] = pngData ca.images["ar-1"] = pngData
ca.images["al-1"] = jpegData ca.images["al-1"] = jpegData
ca.images["al-2"] = jpegData ca.images["al-2"] = jpegData
mockAlbumTracks(squirrel.And{ putAlbumTracks(byArtist("1",
persistence.ParticipantIDFilter("media_file", "1", model.RoleAlbumArtist), model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1},
squirrel.Eq{"missing": false}, model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "2", Album: "Album 2", DiscNumber: 1},
}, model.MediaFiles{ )...)
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1},
{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "2", Album: "Album 2", DiscNumber: 1},
})
out := new(bytes.Buffer) out := new(bytes.Buffer)
Expect(arch.ZipArtist(ctx, "1", "mp3", 128, out)).To(Succeed()) Expect(arch.ZipArtist(ctx, "1", "mp3", 128, out)).To(Succeed())
@ -431,13 +415,10 @@ var _ = Describe("Archiver", func() {
It("puts each same-named album's cover in that album's own folder", func() { It("puts each same-named album's cover in that album's own folder", func() {
ca.images["al-1"] = jpegData ca.images["al-1"] = jpegData
ca.images["al-2"] = pngData ca.images["al-2"] = pngData
mockAlbumTracks(squirrel.And{ putAlbumTracks(byArtist("1",
persistence.ParticipantIDFilter("media_file", "1", model.RoleAlbumArtist), model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Greatest Hits", Year: 2001, DiscNumber: 1},
squirrel.Eq{"missing": false}, model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "2", Album: "Greatest Hits", Year: 2005, DiscNumber: 1},
}, model.MediaFiles{ )...)
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Greatest Hits", Year: 2001, DiscNumber: 1},
{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "2", Album: "Greatest Hits", Year: 2005, DiscNumber: 1},
})
out := new(bytes.Buffer) out := new(bytes.Buffer)
Expect(arch.ZipArtist(ctx, "1", "mp3", 128, out)).To(Succeed()) Expect(arch.ZipArtist(ctx, "1", "mp3", 128, out)).To(Succeed())
@ -449,15 +430,9 @@ var _ = Describe("Archiver", func() {
It("adds the playlist cover to the root", func() { It("adds the playlist cover to the root", func() {
ca.images["pl-1"] = jpegData ca.images["pl-1"] = jpegData
plRepo := &mockPlaylistRepository{} putPlaylist("1", "Test Playlist",
plRepo.On("GetWithTracks", "1", true, false).Return(&model.Playlist{ model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Artist: "Artist 1", Title: "track1"},
ID: "1", )
Name: "Test Playlist",
Tracks: []model.PlaylistTrack{
{MediaFile: model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Artist: "Artist 1", Title: "track1"}},
},
}, nil)
ds.On("Playlist", mock.Anything).Return(plRepo)
ms.On("NewStream", mock.Anything, mock.Anything, mock.Anything).Return(io.NopCloser(strings.NewReader("test")), nil) ms.On("NewStream", mock.Anything, mock.Anything, mock.Anything).Return(io.NopCloser(strings.NewReader("test")), nil)
out := new(bytes.Buffer) out := new(bytes.Buffer)
@ -495,9 +470,7 @@ var _ = Describe("Archiver", func() {
It("still builds the archive when the cover cannot be read", func() { It("still builds the archive when the cover cannot be read", func() {
ca.err = errors.New("boom") ca.err = errors.New("boom")
mockAlbumTracks(squirrel.Eq{"album_id": "1"}, model.MediaFiles{ putAlbumTracks(model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1})
{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1},
})
out := new(bytes.Buffer) out := new(bytes.Buffer)
Expect(arch.ZipAlbum(ctx, "1", "mp3", 128, out)).To(Succeed()) Expect(arch.ZipAlbum(ctx, "1", "mp3", 128, out)).To(Succeed())
@ -551,54 +524,6 @@ func (m *mockCoverArt) Get(ctx context.Context, artID model.ArtworkID, size int,
return &artwork.Image{ReadCloser: io.NopCloser(bytes.NewReader(data))}, nil return &artwork.Image{ReadCloser: io.NopCloser(bytes.NewReader(data))}, nil
} }
type mockDataStore struct {
mock.Mock
model.DataStore
}
func (m *mockDataStore) MediaFile() model.MediaFileRepository {
args := m.Called()
return args.Get(0).(model.MediaFileRepository)
}
func (m *mockDataStore) Playlist() model.PlaylistRepository {
args := m.Called()
return args.Get(0).(model.PlaylistRepository)
}
func (m *mockDataStore) Library() model.LibraryRepository {
return &mockLibraryRepository{}
}
type mockLibraryRepository struct {
mock.Mock
model.LibraryRepository
}
func (m *mockLibraryRepository) GetPath(_ context.Context, id int) (string, error) {
return "/music", nil
}
type mockMediaFileRepository struct {
mock.Mock
model.MediaFileRepository
}
func (m *mockMediaFileRepository) GetAll(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) {
args := m.Called(options)
return args.Get(0).(model.MediaFiles), args.Error(1)
}
type mockPlaylistRepository struct {
mock.Mock
model.PlaylistRepository
}
func (m *mockPlaylistRepository) GetWithTracks(_ context.Context, id string, refreshSmartPlaylists, includeMissing bool) (*model.Playlist, error) {
args := m.Called(id, refreshSmartPlaylists, includeMissing)
return args.Get(0).(*model.Playlist), args.Error(1)
}
type mockMediaStreamer struct { type mockMediaStreamer struct {
mock.Mock mock.Mock
stream.MediaStreamer stream.MediaStreamer

View file

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

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