Compare commits

..

37 commits

Author SHA1 Message Date
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
479 changed files with 12281 additions and 13143 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,12 +20,12 @@
### 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.

View file

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

View file

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

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

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

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

@ -213,12 +213,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,8 +3,9 @@ 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/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -12,27 +13,43 @@ 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")

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

View file

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

View file

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

View file

@ -15,8 +15,14 @@ func BenchmarkImageDecode(b *testing.B) {
name string name string
gen func(tb testing.TB, w, h int) []byte gen func(tb testing.TB, w, h int) []byte
}{ }{
{"jpeg", func(tb testing.TB, w, h int) []byte { return generateJPEG(tb, w, h, 75) }}, {"jpeg", func(tb testing.TB, w, h int) []byte {
{"png", func(tb testing.TB, w, h int) []byte { return generatePNG(tb, w, h) }}, tb.Helper()
return generateJPEG(tb, w, h, 75)
}},
{"png", func(tb testing.TB, w, h int) []byte {
tb.Helper()
return generatePNG(tb, w, h)
}},
} }
for _, format := range formats { for _, format := range formats {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -3,6 +3,7 @@ package e2e
import ( import (
"bytes" "bytes"
"context" "context"
"errors"
"fmt" "fmt"
"hash/fnv" "hash/fnv"
"image" "image"
@ -29,6 +30,7 @@ import (
"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/scanner" "github.com/navidrome/navidrome/scanner"
"github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/server/events"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
@ -49,7 +51,7 @@ const (
var ( var (
rctx context.Context rctx context.Context
rds *tests.MockDataStore rds model.DataStore
rstore *artwork.ImageStore rstore *artwork.ImageStore
rsvc artwork.Artwork rsvc artwork.Artwork
rworker *artwork.Worker rworker *artwork.Worker
@ -73,7 +75,9 @@ var _ = BeforeSuite(func() {
db.Db().SetMaxOpenConns(1) db.Db().SetMaxOpenConns(1)
db.Init(request.WithUser(GinkgoT().Context(), model.User{ID: "admin-1", IsAdmin: true})) db.Init(request.WithUser(GinkgoT().Context(), model.User{ID: "admin-1", IsAdmin: true}))
userTables = harness.ResettableTables() var err error
userTables, err = persistencetest.Tables()
Expect(err).ToNot(HaveOccurred())
}) })
var _ = AfterSuite(func() { var _ = AfterSuite(func() {
@ -98,7 +102,7 @@ func setupResolutionHarness() {
rctx = request.WithUser(GinkgoT().Context(), model.User{ID: "admin-1", UserName: "admin", IsAdmin: true}) rctx = request.WithUser(GinkgoT().Context(), model.User{ID: "admin-1", UserName: "admin", IsAdmin: true})
harness.TruncateDB(userTables) harness.TruncateDB(userTables)
rds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} rds = persistence.New(db.Db())
adminUser := model.User{ID: "admin-1", UserName: "admin", Name: "Admin", IsAdmin: true, NewPassword: "password"} adminUser := model.User{ID: "admin-1", UserName: "admin", Name: "Admin", IsAdmin: true, NewPassword: "password"}
Expect(rds.User().Put(rctx, &adminUser)).To(Succeed()) Expect(rds.User().Put(rctx, &adminUser)).To(Succeed())
@ -117,7 +121,7 @@ func setupResolutionHarness() {
// size=0 requests stream originals, so this reader is never called (serving_test covers resizing). // size=0 requests stream originals, so this reader is never called (serving_test covers resizing).
imgCache := cache.NewFileCache("ArtworkResolutionE2E", "100MB", "images", 0, imgCache := cache.NewFileCache("ArtworkResolutionE2E", "100MB", "images", 0,
func(context.Context, cache.Item) (io.Reader, error) { func(context.Context, cache.Item) (io.Reader, error) {
return nil, fmt.Errorf("resize not exercised in e2e") return nil, errors.New("resize not exercised in e2e")
}) })
Eventually(func() bool { return imgCache.Available(rctx) }, 10*time.Second).Should(BeTrue()) Eventually(func() bool { return imgCache.Available(rctx) }, 10*time.Second).Should(BeTrue())

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -7,6 +7,7 @@ import (
"slices" "slices"
"sync" "sync"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/utils/str" "github.com/navidrome/navidrome/utils/str"
) )
@ -94,7 +95,10 @@ func encodeSteps(steps []TraceStep, sourcePath string) string {
} }
out = append(out, storedStep{C: s.Candidate, O: s.Outcome, D: str.TruncateRunes(d, maxTraceDetail, "...")}) out = append(out, storedStep{C: s.Candidate, O: s.Outcome, D: str.TruncateRunes(d, maxTraceDetail, "...")})
} }
b, _ := json.Marshal(out) // []storedStep is all strings, so this cannot fail b, err := json.Marshal(out)
if err != nil {
log.Error("Artwork: Could not encode resolution trace", err)
}
return string(b) return string(b)
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -8,20 +8,24 @@ import (
"github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/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"
) )
func TestAuth(t *testing.T) { func TestAuth(t *testing.T) {
log.SetLevel(log.LevelFatal) log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail) RegisterFailHandler(Fail)
RunSpecs(t, "Auth Test Suite") RunSpecs(t, "Auth Test Suite")
} }
var _ = configtest.RestoreAfterEachSpec() var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()
const ( const (
oneDay = 24 * time.Hour oneDay = 24 * time.Hour
@ -34,10 +38,7 @@ var _ = BeforeSuite(func() {
var _ = Describe("Auth", func() { var _ = Describe("Auth", func() {
BeforeEach(func() { BeforeEach(func() {
ds := &tests.MockDataStore{ auth.Init(persistence.New(db.Db()))
MockedProperty: &tests.MockedPropertyRepo{},
}
auth.Init(ds)
}) })
Describe("Validate", func() { Describe("Validate", func() {
@ -87,7 +88,7 @@ var _ = Describe("Auth", func() {
Expect(claims.Issuer).To(Equal(consts.JWTIssuer)) Expect(claims.Issuer).To(Equal(consts.JWTIssuer))
Expect(claims.Subject).To(Equal("johndoe")) Expect(claims.Subject).To(Equal("johndoe"))
Expect(claims.UserID).To(Equal("123")) Expect(claims.UserID).To(Equal("123"))
Expect(claims.IsAdmin).To(Equal(true)) Expect(claims.IsAdmin).To(BeTrue())
Expect(claims.ExpiresAt).To(BeTemporally(">", time.Now())) Expect(claims.ExpiresAt).To(BeTemporally(">", time.Now()))
}) })
}) })

View file

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

View file

@ -7,9 +7,11 @@ import (
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"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/tests" "github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
) )
var _ = Describe("common.go", func() { var _ = Describe("common.go", func() {
@ -31,18 +33,15 @@ var _ = Describe("common.go", func() {
Describe("AbsolutePath", func() { Describe("AbsolutePath", func() {
var ( var (
ds *tests.MockDataStore ds model.DataStore
libId int libId int
path string path string
) )
BeforeEach(func() { BeforeEach(func() {
ds = &tests.MockDataStore{} ds = persistence.New(db.Db())
libId = 1
path = "music/file.mp3" path = "music/file.mp3"
mockLib := &tests.MockLibraryRepo{} libId = persistencetest.SetLibraries(ctx, ds, "/other", "/library/root")[1]
mockLib.SetData(model.Libraries{{ID: libId, Path: "/library/root"}})
ds.MockedLibrary = mockLib
}) })
It("returns the absolute path when library exists", func() { It("returns the absolute path when library exists", func() {

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 TestCore(t *testing.T) { func TestCore(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, "Core Suite") RunSpecs(t, "Core Suite")
} }
var _ = configtest.RestoreAfterEachSpec() var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

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

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

View file

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

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 TestExternal(t *testing.T) { func TestExternal(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, "External Suite") RunSpecs(t, "External Suite")
} }
var _ = configtest.RestoreAfterEachSpec() var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

View file

@ -17,7 +17,7 @@ import (
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/server/events"
"github.com/navidrome/navidrome/utils" "github.com/navidrome/navidrome/utils"
. "github.com/navidrome/navidrome/utils/gg" "github.com/navidrome/navidrome/utils/gg"
"github.com/navidrome/navidrome/utils/slice" "github.com/navidrome/navidrome/utils/slice"
"github.com/navidrome/navidrome/utils/str" "github.com/navidrome/navidrome/utils/str"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
@ -87,10 +87,11 @@ type Agents interface {
agents.SimilarSongsByArtistRetriever agents.SimilarSongsByArtistRetriever
} }
func NewProvider(ds model.DataStore, agents Agents, m *matcher.Matcher, broker events.Broker) Provider { // NewProvider runs background info refreshes until ctx is done.
func NewProvider(ctx context.Context, ds model.DataStore, agents Agents, m *matcher.Matcher, broker events.Broker) Provider {
e := &provider{ds: ds, ag: agents, matcher: m, broker: broker} e := &provider{ds: ds, ag: agents, matcher: m, broker: broker}
e.artistQueue = newRefreshQueue(context.TODO(), e.populateArtistInfo) e.artistQueue = newRefreshQueue(ctx, e.populateArtistInfo)
e.albumQueue = newRefreshQueue(context.TODO(), e.populateAlbumInfo) e.albumQueue = newRefreshQueue(ctx, e.populateAlbumInfo)
return e return e
} }
@ -125,7 +126,7 @@ func (e *provider) UpdateAlbumInfo(ctx context.Context, id string) (*model.Album
return nil, err return nil, err
} }
updatedAt := V(album.ExternalInfoUpdatedAt) updatedAt := gg.V(album.ExternalInfoUpdatedAt)
albumName := album.Name() albumName := album.Name()
if updatedAt.IsZero() { if updatedAt.IsZero() {
log.Debug(ctx, "AlbumInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", albumName) log.Debug(ctx, "AlbumInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", albumName)
@ -133,10 +134,7 @@ func (e *provider) UpdateAlbumInfo(ctx context.Context, id string) (*model.Album
if err != nil { if err != nil {
return nil, err return nil, err
} }
} } else if time.Since(updatedAt) > conf.Server().DevAlbumInfoTimeToLive {
// If info is expired, trigger a populateAlbumInfo in the background
if time.Since(updatedAt) > conf.Server().DevAlbumInfoTimeToLive {
log.Debug("Found expired cached AlbumInfo, refreshing in the background", "updatedAt", album.ExternalInfoUpdatedAt, "name", albumName) log.Debug("Found expired cached AlbumInfo, refreshing in the background", "updatedAt", album.ExternalInfoUpdatedAt, "name", albumName)
e.albumQueue.enqueue(&album) e.albumQueue.enqueue(&album)
} }
@ -232,7 +230,7 @@ func (e *provider) refreshArtistInfo(ctx context.Context, id string) (auxArtist,
} }
// If we don't have any info, retrieves it now // If we don't have any info, retrieves it now
updatedAt := V(artist.ExternalInfoUpdatedAt) updatedAt := gg.V(artist.ExternalInfoUpdatedAt)
artistName := artist.Name() artistName := artist.Name()
if updatedAt.IsZero() { if updatedAt.IsZero() {
log.Debug(ctx, "ArtistInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", artistName) log.Debug(ctx, "ArtistInfo not cached. Retrieving it now", "updatedAt", updatedAt, "id", id, "name", artistName)
@ -240,10 +238,7 @@ func (e *provider) refreshArtistInfo(ctx context.Context, id string) (auxArtist,
if err != nil { if err != nil {
return auxArtist{}, err return auxArtist{}, err
} }
} } else if time.Since(updatedAt) > conf.Server().DevArtistInfoTimeToLive {
// If info is expired, trigger a populateArtistInfo in the background
if time.Since(updatedAt) > conf.Server().DevArtistInfoTimeToLive {
log.Debug("Found expired cached ArtistInfo, refreshing in the background", "updatedAt", updatedAt, "name", artistName) log.Debug("Found expired cached ArtistInfo, refreshing in the background", "updatedAt", updatedAt, "name", artistName)
e.artistQueue.enqueue(&artist) e.artistQueue.enqueue(&artist)
} }

View file

@ -9,9 +9,11 @@ import (
"github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/external" "github.com/navidrome/navidrome/core/external"
"github.com/navidrome/navidrome/core/matcher" "github.com/navidrome/navidrome/core/matcher"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/server/events"
"github.com/navidrome/navidrome/tests"
. "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"
@ -39,11 +41,9 @@ var _ = Describe("Provider - RefreshInfo", func() {
var ( var (
ctx context.Context ctx context.Context
p external.Provider p external.Provider
ds *tests.MockDataStore ds model.DataStore
ag *mockAgents ag *mockAgents
broker *fakeBroker broker *fakeBroker
mockArtistRepo *tests.MockArtistRepo
mockAlbumRepo *tests.MockAlbumRepo
) )
expectArtistAgents := func() { expectArtistAgents := func() {
@ -67,39 +67,37 @@ var _ = Describe("Provider - RefreshInfo", func() {
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context() ctx = GinkgoT().Context()
ds = new(tests.MockDataStore) ds = persistence.New(db.Db())
ag = new(mockAgents) ag = new(mockAgents)
broker = &fakeBroker{} broker = &fakeBroker{}
p = external.NewProvider(ds, ag, matcher.New(ds), broker) p = external.NewProvider(ctx, ds, ag, matcher.New(ds), broker)
mockArtistRepo = ds.Artist().(*tests.MockArtistRepo)
mockAlbumRepo = ds.Album().(*tests.MockAlbumRepo)
}) })
It("repopulates an artist even when its info is fresh", func() { It("repopulates an artist even when its info is fresh", func() {
fresh := time.Now() fresh := time.Now()
mockArtistRepo.SetData(model.Artists{{ persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{
ID: "ar-1", Name: "Test Artist", Biography: "stale", ExternalInfoUpdatedAt: &fresh, ID: "ar-1", Name: "Test Artist", Biography: "stale", ExternalInfoUpdatedAt: &fresh,
}}) })
expectArtistAgents() expectArtistAgents()
Expect(p.RefreshInfo(ctx, model.KindArtistArtwork, "ar-1")).To(Succeed()) Expect(p.RefreshInfo(ctx, model.KindArtistArtwork, "ar-1")).To(Succeed())
saved, err := mockArtistRepo.Get(ctx, "ar-1") saved, err := ds.Artist().Get(ctx, "ar-1")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(saved.Biography).To(Equal("Fresh Bio")) Expect(saved.Biography).To(Equal("Fresh Bio"))
}) })
It("repopulates an album even when its info is fresh", func() { It("repopulates an album even when its info is fresh", func() {
fresh := time.Now() fresh := time.Now()
mockAlbumRepo.SetData(model.Albums{{ persistencetest.PutAlbums(ctx, ds, model.Album{
ID: "al-1", Name: "Test Album", AlbumArtist: "Test Artist", ID: "al-1", Name: "Test Album", AlbumArtist: "Test Artist",
Description: "stale", ExternalInfoUpdatedAt: &fresh, Description: "stale", ExternalInfoUpdatedAt: &fresh,
}}) })
expectAlbumAgents() expectAlbumAgents()
Expect(p.RefreshInfo(ctx, model.KindAlbumArtwork, "al-1")).To(Succeed()) Expect(p.RefreshInfo(ctx, model.KindAlbumArtwork, "al-1")).To(Succeed())
saved, err := mockAlbumRepo.Get(ctx, "al-1") saved, err := ds.Album().Get(ctx, "al-1")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(saved.Description).To(Equal("Fresh Notes")) Expect(saved.Description).To(Equal("Fresh Notes"))
}) })
@ -113,7 +111,7 @@ var _ = Describe("Provider - RefreshInfo", func() {
}) })
It("broadcasts a RefreshResource naming the artist", func() { It("broadcasts a RefreshResource naming the artist", func() {
mockArtistRepo.SetData(model.Artists{{ID: "ar-1", Name: "Test Artist"}}) persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar-1", Name: "Test Artist"})
expectArtistAgents() expectArtistAgents()
Expect(p.RefreshInfo(ctx, model.KindArtistArtwork, "ar-1")).To(Succeed()) Expect(p.RefreshInfo(ctx, model.KindArtistArtwork, "ar-1")).To(Succeed())
@ -127,7 +125,7 @@ var _ = Describe("Provider - RefreshInfo", func() {
}) })
It("broadcasts a RefreshResource naming the album", func() { It("broadcasts a RefreshResource naming the album", func() {
mockAlbumRepo.SetData(model.Albums{{ID: "al-1", Name: "Test Album", AlbumArtist: "Test Artist"}}) persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al-1", Name: "Test Album", AlbumArtist: "Test Artist"})
expectAlbumAgents() expectAlbumAgents()
Expect(p.RefreshInfo(ctx, model.KindAlbumArtwork, "al-1")).To(Succeed()) Expect(p.RefreshInfo(ctx, model.KindAlbumArtwork, "al-1")).To(Succeed())
@ -139,11 +137,12 @@ var _ = Describe("Provider - RefreshInfo", func() {
}) })
It("does not broadcast when the artist cannot be loaded", func() { It("does not broadcast when the artist cannot be loaded", func() {
mockArtistRepo.SetData(model.Artists{{ID: "ar-1", Name: "Test Artist"}}) persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar-1", Name: "Test Artist"})
expectArtistAgents() expectArtistAgents()
mockArtistRepo.SetError(true) failing := failingArtists(ds, errDBDown)
p = external.NewProvider(ctx, failing, ag, matcher.New(failing), broker)
_ = p.RefreshInfo(ctx, model.KindArtistArtwork, "ar-1") Expect(p.RefreshInfo(ctx, model.KindArtistArtwork, "ar-1")).To(MatchError(errDBDown))
Expect(broker.sent()).To(BeEmpty()) Expect(broker.sent()).To(BeEmpty())
}) })

View file

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

File diff suppressed because it is too large Load diff

View file

@ -10,8 +10,11 @@ import (
"github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/agents"
. "github.com/navidrome/navidrome/core/external" . "github.com/navidrome/navidrome/core/external"
"github.com/navidrome/navidrome/core/matcher" "github.com/navidrome/navidrome/core/matcher"
"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/persistence/persistencetest"
. "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"
@ -20,189 +23,132 @@ import (
var _ = Describe("Provider - TopSongs", func() { var _ = Describe("Provider - TopSongs", func() {
var ( var (
p Provider p Provider
artistRepo *mockArtistRepo // From provider_helper_test.go ds model.DataStore
mediaFileRepo *mockMediaFileRepo // From provider_helper_test.go ag *mockAgents
ag *mockAgents // Consolidated mock from export_test.go
ctx context.Context ctx context.Context
) )
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"}
BeforeEach(func() { BeforeEach(func() {
// Disable fuzzy matching for these tests to avoid unexpected GetAll calls ctx = request.WithUser(GinkgoT().Context(), adminUser)
conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 }) conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 })
ds = persistence.New(db.Db())
ctx = GinkgoT().Context()
artistRepo = newMockArtistRepo() // Use helper mock
mediaFileRepo = newMockMediaFileRepo() // Use helper mock
// Configure tests.MockDataStore to use the testify/mock-based repos
ds := &tests.MockDataStore{
MockedArtist: artistRepo,
MockedMediaFile: mediaFileRepo,
}
ag = new(mockAgents) ag = new(mockAgents)
p = NewProvider(ctx, ds, ag, matcher.New(ds), &fakeBroker{})
p = NewProvider(ds, ag, matcher.New(ds), &fakeBroker{})
}) })
It("returns top songs for a known artist", func() { withFailingArtists := func(err error) {
// Mock finding the artist failing := failingArtists(ds, err)
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} p = NewProvider(ctx, failing, ag, matcher.New(failing), &fakeBroker{})
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() }
// Mock agent response It("returns top songs for a known artist", func() {
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
persistencetest.PutMediaFiles(ctx, ds,
model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"},
model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-song-2"},
)
agentSongs := []agents.Song{ agentSongs := []agents.Song{
{Name: "Song One", MBID: "mbid-song-1"}, {Name: "Song One", MBID: "mbid-song-1"},
{Name: "Song Two", MBID: "mbid-song-2"}, {Name: "Song Two", MBID: "mbid-song-2"},
} }
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
// Mock finding matching tracks (both returned in a single query)
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}
song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-song-2"}
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once()
songs, err := p.TopSongs(ctx, "Artist One", "", 2) songs, err := p.TopSongs(ctx, "Artist One", "", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(songs).To(HaveLen(2)) Expect(ids(songs)).To(Equal([]string{"song-1", "song-2"}))
Expect(songs[0].ID).To(Equal("song-1"))
Expect(songs[1].ID).To(Equal("song-2"))
artistRepo.AssertExpectations(GinkgoT())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
mediaFileRepo.AssertExpectations(GinkgoT())
}) })
Context("artist id and/or name", func() { Context("artist id and/or name", func() {
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
BeforeEach(func() { BeforeEach(func() {
persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"})
agentSongs := []agents.Song{{Name: "Song One", MBID: "mbid-song-1"}} agentSongs := []agents.Song{{Name: "Song One", MBID: "mbid-song-1"}}
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once()
}) })
It("returns top songs for a known artist by id only", func() { It("returns top songs for a known artist by id only", func() {
artistRepo.On("Get", "artist-1").Return(&artist1, nil).Once()
songs, err := p.TopSongs(ctx, "", "artist-1", 2) songs, err := p.TopSongs(ctx, "", "artist-1", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(songs).To(HaveLen(1)) Expect(ids(songs)).To(Equal([]string{"song-1"}))
Expect(songs[0].ID).To(Equal("song-1"))
artistRepo.AssertExpectations(GinkgoT())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
mediaFileRepo.AssertExpectations(GinkgoT())
}) })
It("returns top songs for a known artist by id, falling back to name", func() { It("returns top songs for a known artist by id, falling back to name", func() {
artistRepo.On("Get", "fake-id").Return(nil, model.ErrNotFound).Once()
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
songs, err := p.TopSongs(ctx, "Artist One", "fake-id", 2) songs, err := p.TopSongs(ctx, "Artist One", "fake-id", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(songs).To(HaveLen(1)) Expect(ids(songs)).To(Equal([]string{"song-1"}))
Expect(songs[0].ID).To(Equal("song-1"))
artistRepo.AssertExpectations(GinkgoT())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
mediaFileRepo.AssertExpectations(GinkgoT())
}) })
}) })
It("bails if lookup by id returns a fatal error", func() { It("bails if lookup by id returns a fatal error", func() {
artistRepo.On("Get", "artist-1").Return(nil, model.ErrInvalidAuth).Once() withFailingArtists(model.ErrInvalidAuth)
songs, err := p.TopSongs(ctx, "Artist One", "artist-1", 2) songs, err := p.TopSongs(ctx, "Artist One", "artist-1", 2)
Expect(songs).To(BeEmpty()) Expect(songs).To(BeEmpty())
Expect(err).To(HaveOccurred()) Expect(err).To(MatchError(model.ErrInvalidAuth))
}) })
It("bails if lookup by name returns a fatal error", func() { It("bails if lookup by name returns a fatal error", func() {
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(nil, model.ErrInvalidAuth).Once() withFailingArtists(model.ErrInvalidAuth)
songs, err := p.TopSongs(ctx, "Artist One", "", 2) songs, err := p.TopSongs(ctx, "Artist One", "", 2)
Expect(songs).To(BeEmpty()) Expect(songs).To(BeEmpty())
Expect(err).To(HaveOccurred()) Expect(err).To(MatchError(model.ErrInvalidAuth))
}) })
It("backfills name and MBID onto an unnamed primary credit (the queried artist) and matches", func() { It("backfills name and MBID onto an unnamed primary credit (the queried artist) and matches", func() {
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil) persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", Participants: credited(artist1)})
// Agent leaves the first credit unnamed (e.g. an MBID-less collaborator slot). That blank // The blank first credit IS the queried artist, so enrichment fills both name and MBID and
// credit IS the queried artist, so enrichment fills both name and MBID; the song then matches // the song matches the queried artist's track via the backfilled identity.
// the queried artist's track via the backfilled identity.
agentSongs := []agents.Song{ agentSongs := []agents.Song{
{Name: "Song One", Artists: []agents.Artist{{}}}, {Name: "Song One", Artists: []agents.Artist{{}}},
} }
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once()
track := model.MediaFile{
ID: "song-1", Title: "Song One", ArtistID: "artist-1",
Participants: model.Participants{model.RoleArtist: model.ParticipantList{
{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"}},
}},
}
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{track}, nil)
songs, err := p.TopSongs(ctx, "Artist One", "", 1) songs, err := p.TopSongs(ctx, "Artist One", "", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(songs).To(HaveLen(1)) Expect(ids(songs)).To(Equal([]string{"song-1"}))
Expect(songs[0].ID).To(Equal("song-1"))
}) })
It("does not stamp the queried MBID onto an already-named different first credit", func() { It("does not stamp the queried MBID onto an already-named different first credit", func() {
// The queried artist (One) appears only as a featured collaborator; the displayed first credit // The first credit is a different artist (Two) without an MBID. Stamping One's MBID onto it
// is a DIFFERENT artist (Two) returned without an MBID. Enrichment must NOT assign One's MBID // would resolve it to One, matching One's same-titled track.
// to Two — only Two's name match (which fails here) or One's own credit may resolve the track. persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "one-track", Title: "Collab Song", ArtistID: "artist-1", Participants: credited(artist1)})
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil)
agentSongs := []agents.Song{ agentSongs := []agents.Song{
{Name: "Collab Song", Artists: []agents.Artist{{Name: "Artist Two"}}}, {Name: "Collab Song", Artists: []agents.Artist{{Name: "Artist Two"}}},
} }
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once()
// Library track is credited to Artist One (the queried artist) under a same title. If the
// queried MBID were wrongly stamped onto the "Artist Two" credit, that mismatched name+MBID artistRepo.On("Get", "fake-id").Return(nil, model.ErrNotFound).Once()
// could mis-resolve. With the guard, "Artist Two" stays MBID-less and does not match One's track.
track := model.MediaFile{
ID: "one-track", Title: "Collab Song", ArtistID: "artist-1",
Participants: model.Participants{model.RoleArtist: model.ParticipantList{
{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"}},
}},
}
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{track}, nil)
songs, err := p.TopSongs(ctx, "Artist One", "", 1) songs, err := p.TopSongs(ctx, "Artist One", "", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
// "Artist Two" (named, MBID-less, not in the library) does not resolve to One's track.
Expect(songs).To(BeEmpty()) Expect(songs).To(BeEmpty())
}) })
It("returns nil for an unknown artist", func() { It("returns nil for an unknown artist", func() {
// Mock artist not found
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{}, nil).Once()
songs, err := p.TopSongs(ctx, "Unknown Artist", "", 5) songs, err := p.TopSongs(ctx, "Unknown Artist", "", 5)
Expect(err).ToNot(HaveOccurred()) // TopSongs returns nil error if artist not found Expect(err).ToNot(HaveOccurred()) // TopSongs returns nil error if artist not found
Expect(songs).To(BeNil()) Expect(songs).To(BeNil())
artistRepo.AssertExpectations(GinkgoT())
ag.AssertNotCalled(GinkgoT(), "GetArtistTopSongs", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) ag.AssertNotCalled(GinkgoT(), "GetArtistTopSongs", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything)
}) })
It("returns error when the agent returns an error", func() { It("returns error when the agent returns an error", func() {
// Mock finding the artist persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
// Mock agent error
agentErr := errors.New("agent error") agentErr := errors.New("agent error")
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 5).Return(nil, agentErr).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 5).Return(nil, agentErr).Once()
@ -210,30 +156,23 @@ var _ = Describe("Provider - TopSongs", func() {
Expect(err).To(MatchError(agentErr)) Expect(err).To(MatchError(agentErr))
Expect(songs).To(BeNil()) Expect(songs).To(BeNil())
artistRepo.AssertExpectations(GinkgoT())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
}) })
It("returns ErrNotFound when the agent returns ErrNotFound", func() { It("returns ErrNotFound when the agent returns ErrNotFound", func() {
// Mock finding the artist persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
// Mock agent ErrNotFound
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 5).Return(nil, agents.ErrNotFound).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 5).Return(nil, agents.ErrNotFound).Once()
songs, err := p.TopSongs(ctx, "Artist One", "", 5) songs, err := p.TopSongs(ctx, "Artist One", "", 5)
Expect(err).To(MatchError(model.ErrNotFound)) Expect(err).To(MatchError(model.ErrNotFound))
Expect(songs).To(BeNil()) Expect(songs).To(BeNil())
artistRepo.AssertExpectations(GinkgoT())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
}) })
// This endpoint answered with an empty list before retry-later existed; it must keep doing so. // This endpoint answered with an empty list before retry-later existed; it must keep doing so.
It("returns an empty list, not a client error, when the agents are throttled", func() { It("returns an empty list, not a client error, when the agents are throttled", func() {
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 5). ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 5).
Return(nil, agents.ErrRetryLater).Once() Return(nil, agents.ErrRetryLater).Once()
@ -246,231 +185,136 @@ var _ = Describe("Provider - TopSongs", func() {
}) })
It("returns fewer songs if count is less than available top songs", func() { It("returns fewer songs if count is less than available top songs", func() {
// Mock finding the artist persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"})
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
// Mock agent response (only need 1 for the test)
agentSongs := []agents.Song{{Name: "Song One", MBID: "mbid-song-1"}} agentSongs := []agents.Song{{Name: "Song One", MBID: "mbid-song-1"}}
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once()
// Mock finding matching track
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once()
songs, err := p.TopSongs(ctx, "Artist One", "", 1) songs, err := p.TopSongs(ctx, "Artist One", "", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(songs).To(HaveLen(1)) Expect(ids(songs)).To(Equal([]string{"song-1"}))
Expect(songs[0].ID).To(Equal("song-1"))
artistRepo.AssertExpectations(GinkgoT())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
mediaFileRepo.AssertExpectations(GinkgoT())
}) })
It("returns fewer songs if fewer matching tracks are found", func() { It("returns fewer songs if fewer matching tracks are found", func() {
// Mock finding the artist persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"})
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
// Matcher artist resolution for the title-match path (song2 falls through).
artistRepo.On("GetAll", mock.Anything).Return(model.Artists{artist1}, nil).Maybe()
// Mock agent response
agentSongs := []agents.Song{ agentSongs := []agents.Song{
{Name: "Song One", MBID: "mbid-song-1"}, {Name: "Song One", MBID: "mbid-song-1"},
{Name: "Song Two", MBID: "mbid-song-2"}, {Name: "Song Two", MBID: "mbid-song-2"},
} }
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
// Mock finding matching tracks (only find song 1 on bulk query)
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once() // bulk MBID query
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{}, nil).Once() // title track-fetch for song2: no match
songs, err := p.TopSongs(ctx, "Artist One", "", 2) songs, err := p.TopSongs(ctx, "Artist One", "", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(songs).To(HaveLen(1)) Expect(ids(songs)).To(Equal([]string{"song-1"}))
Expect(songs[0].ID).To(Equal("song-1"))
artistRepo.AssertExpectations(GinkgoT())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
mediaFileRepo.AssertExpectations(GinkgoT())
}) })
It("returns error when context is canceled during agent call", func() { It("returns error when context is canceled during agent call", func() {
// Mock finding the artist persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"}
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
// Setup context that will be canceled
canceledCtx, cancel := context.WithCancel(ctx) canceledCtx, cancel := context.WithCancel(ctx)
ag.On("GetArtistTopSongs", canceledCtx, "artist-1", "Artist One", "mbid-artist-1", 5).
Run(func(mock.Arguments) { cancel() }).
Return(nil, context.Canceled).Once()
// Mock agent call to return context canceled error
ag.On("GetArtistTopSongs", canceledCtx, "artist-1", "Artist One", "mbid-artist-1", 5).Return(nil, context.Canceled).Once()
cancel() // Cancel the context before calling
songs, err := p.TopSongs(canceledCtx, "Artist One", "", 5) songs, err := p.TopSongs(canceledCtx, "Artist One", "", 5)
Expect(err).To(MatchError(context.Canceled)) Expect(err).To(MatchError(context.Canceled))
Expect(songs).To(BeNil()) Expect(songs).To(BeNil())
artistRepo.AssertExpectations(GinkgoT())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
}) })
It("falls back to title matching when MbzRecordingID is missing", func() { It("falls back to title matching when MbzRecordingID is missing", func() {
// Mock finding the artist persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} persistencetest.PutMediaFiles(ctx, ds,
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() model.MediaFile{ID: "song-1", Title: "Song One", Artist: "Artist One", ArtistID: "artist-1", Participants: credited(artist1)},
// Matcher artist resolution for both title-fallback songs. model.MediaFile{ID: "song-2", Title: "Song Two", Artist: "Artist One", ArtistID: "artist-1", Participants: credited(artist1)},
artistRepo.On("GetAll", mock.Anything).Return(model.Artists{artist1}, nil).Maybe() )
// Mock agent response with songs that have NO MBID (empty string)
agentSongs := []agents.Song{ agentSongs := []agents.Song{
{Name: "Song One", MBID: ""}, // No MBID, should fall back to title matching {Name: "Song One", MBID: ""},
{Name: "Song Two", MBID: ""}, // No MBID, should fall back to title matching {Name: "Song Two", MBID: ""},
} }
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
// Title track-fetch: tracks must carry RoleArtist participants so back-mapping routes them.
participant1 := model.Participant{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}}
song1 := model.MediaFile{
ID: "song-1", Title: "Song One", Artist: "Artist One", ArtistID: "artist-1",
Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}},
}
song2 := model.MediaFile{
ID: "song-2", Title: "Song Two", Artist: "Artist One", ArtistID: "artist-1",
Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}},
}
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once()
songs, err := p.TopSongs(ctx, "Artist One", "", 2) songs, err := p.TopSongs(ctx, "Artist One", "", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(songs).To(HaveLen(2)) Expect(ids(songs)).To(Equal([]string{"song-1", "song-2"}))
Expect(songs[0].ID).To(Equal("song-1"))
Expect(songs[1].ID).To(Equal("song-2"))
artistRepo.AssertExpectations(GinkgoT())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
mediaFileRepo.AssertExpectations(GinkgoT())
}) })
It("combines MBID and title matching when some songs have missing MbzRecordingID", func() { It("combines MBID and title matching when some songs have missing MbzRecordingID", func() {
// Mock finding the artist persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} persistencetest.PutMediaFiles(ctx, ds,
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"},
// Matcher artist resolution for song2's title-fallback path. model.MediaFile{ID: "song-2", Title: "Song Two", Artist: "Artist One", ArtistID: "artist-1", Participants: credited(artist1)},
artistRepo.On("GetAll", mock.Anything).Return(model.Artists{artist1}, nil).Maybe() )
// Mock agent response with mixed MBID availability
agentSongs := []agents.Song{ agentSongs := []agents.Song{
{Name: "Song One", MBID: "mbid-song-1"}, // Has MBID, should match by MBID {Name: "Song One", MBID: "mbid-song-1"},
{Name: "Song Two", MBID: ""}, // No MBID, should fall back to title matching {Name: "Song Two", MBID: ""},
} }
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
// Mock the MBID query (finds song1 by MBID)
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1", OrderTitle: "song one"}
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once()
// Title track-fetch: song2 must carry RoleArtist participants for back-mapping.
participant1 := model.Participant{Artist: model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"}}
song2 := model.MediaFile{
ID: "song-2", Title: "Song Two", Artist: "Artist One", ArtistID: "artist-1",
Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}},
}
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song2}, nil).Once()
songs, err := p.TopSongs(ctx, "Artist One", "", 2) songs, err := p.TopSongs(ctx, "Artist One", "", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(songs).To(HaveLen(2)) Expect(ids(songs)).To(Equal([]string{"song-1", "song-2"}))
Expect(songs[0].ID).To(Equal("song-1")) // Found by MBID
Expect(songs[1].ID).To(Equal("song-2")) // Found by title
artistRepo.AssertExpectations(GinkgoT())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
mediaFileRepo.AssertExpectations(GinkgoT())
}) })
It("only returns requested count when provider returns additional items", func() { It("only returns requested count when provider returns additional items", func() {
// Mock finding the artist persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} persistencetest.PutMediaFiles(ctx, ds,
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"},
model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-song-2"},
// Mock agent response )
agentSongs := []agents.Song{ agentSongs := []agents.Song{
{Name: "Song One", MBID: "mbid-song-1"}, {Name: "Song One", MBID: "mbid-song-1"},
{Name: "Song Two", MBID: "mbid-song-2"}, {Name: "Song Two", MBID: "mbid-song-2"},
} }
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once()
// Mock finding matching tracks (both returned in a single query)
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}
song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-song-2"}
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once()
songs, err := p.TopSongs(ctx, "Artist One", "", 1) songs, err := p.TopSongs(ctx, "Artist One", "", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(songs).To(HaveLen(1)) Expect(ids(songs)).To(Equal([]string{"song-1"}))
Expect(songs[0].ID).To(Equal("song-1"))
artistRepo.AssertExpectations(GinkgoT())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
mediaFileRepo.AssertExpectations(GinkgoT())
}) })
It("matches songs by ID first when agent provides IDs", func() { It("matches songs by ID first when agent provides IDs", func() {
// Mock finding the artist persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} persistencetest.PutMediaFiles(ctx, ds,
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1"},
model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1"},
// Mock agent response with IDs provided (highest priority matching) )
// Note: Songs have no MBID to ensure only ID matching is used
agentSongs := []agents.Song{ agentSongs := []agents.Song{
{ID: "song-1", Name: "Song One"}, {ID: "song-1", Name: "Song One"},
{ID: "song-2", Name: "Song Two"}, {ID: "song-2", Name: "Song Two"},
} }
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once()
// Mock ID lookup (first query - should match both songs directly)
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1"}
song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1"}
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once()
songs, err := p.TopSongs(ctx, "Artist One", "", 2) songs, err := p.TopSongs(ctx, "Artist One", "", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(songs).To(HaveLen(2)) Expect(ids(songs)).To(Equal([]string{"song-1", "song-2"}))
Expect(songs[0].ID).To(Equal("song-1"))
Expect(songs[1].ID).To(Equal("song-2"))
artistRepo.AssertExpectations(GinkgoT())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
mediaFileRepo.AssertExpectations(GinkgoT())
}) })
It("falls back to MBID when ID is not found", func() { It("falls back to MBID when ID is not found", func() {
// Mock finding the artist persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1)
artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"})
artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once()
// Mock agent response with ID that won't be found, but MBID that will
agentSongs := []agents.Song{ agentSongs := []agents.Song{
{ID: "non-existent-id", Name: "Song One", MBID: "mbid-song-1"}, {ID: "non-existent-id", Name: "Song One", MBID: "mbid-song-1"},
} }
ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once() ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once()
// Mock ID lookup - returns empty (ID not found)
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{}, nil).Once()
// Mock MBID lookup - finds the song
song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}
mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once()
songs, err := p.TopSongs(ctx, "Artist One", "", 1) songs, err := p.TopSongs(ctx, "Artist One", "", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(songs).To(HaveLen(1)) Expect(ids(songs)).To(Equal([]string{"song-1"}))
Expect(songs[0].ID).To(Equal("song-1"))
artistRepo.AssertExpectations(GinkgoT())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
mediaFileRepo.AssertExpectations(GinkgoT())
}) })
}) })

View file

@ -9,9 +9,11 @@ import (
"github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/external" "github.com/navidrome/navidrome/core/external"
"github.com/navidrome/navidrome/core/matcher" "github.com/navidrome/navidrome/core/matcher"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/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"
"github.com/stretchr/testify/mock" "github.com/stretchr/testify/mock"
@ -25,17 +27,29 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() {
var ( var (
ctx context.Context ctx context.Context
p external.Provider p external.Provider
ds *tests.MockDataStore ds model.DataStore
ag *mockAgents ag *mockAgents
mockAlbumRepo *tests.MockAlbumRepo
) )
expectCached := func(got, want *model.Album) {
GinkgoHelper()
Expect(got.ID).To(Equal(want.ID))
Expect(got.Name).To(Equal(want.Name))
Expect(got.ExternalUrl).To(Equal(want.ExternalUrl))
Expect(got.Description).To(Equal(want.Description))
Expect(got.LargeImageUrl).To(Equal(want.LargeImageUrl))
if want.ExternalInfoUpdatedAt == nil {
Expect(got.ExternalInfoUpdatedAt).To(BeNil())
} else {
Expect(*got.ExternalInfoUpdatedAt).To(BeTemporally("==", *want.ExternalInfoUpdatedAt))
}
}
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context() ctx = GinkgoT().Context()
ds = new(tests.MockDataStore) ds = persistence.New(db.Db())
ag = new(mockAgents) ag = new(mockAgents)
p = external.NewProvider(ds, ag, matcher.New(ds), &fakeBroker{}) p = external.NewProvider(ctx, ds, ag, matcher.New(ds), &fakeBroker{})
mockAlbumRepo = ds.Album().(*tests.MockAlbumRepo)
conf.Update(func(c *conf.Options) { c.DevAlbumInfoTimeToLive = 1 * time.Hour }) conf.Update(func(c *conf.Options) { c.DevAlbumInfoTimeToLive = 1 * time.Hour })
}) })
@ -54,7 +68,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() {
AlbumArtist: "Test Artist", AlbumArtist: "Test Artist",
MbzAlbumID: "mbid-album", MbzAlbumID: "mbid-album",
} }
mockAlbumRepo.SetData(model.Albums{*originalAlbum}) persistencetest.PutAlbums(ctx, ds, *originalAlbum)
expectedInfo := &agents.AlbumInfo{ expectedInfo := &agents.AlbumInfo{
URL: "http://example.com/album", URL: "http://example.com/album",
@ -77,6 +91,13 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() {
Expect(updatedAlbum.ExternalInfoUpdatedAt).NotTo(BeNil()) Expect(updatedAlbum.ExternalInfoUpdatedAt).NotTo(BeNil())
Expect(*updatedAlbum.ExternalInfoUpdatedAt).To(BeTemporally("~", time.Now(), time.Second)) Expect(*updatedAlbum.ExternalInfoUpdatedAt).To(BeTemporally("~", time.Now(), time.Second))
stored, err := ds.Album().Get(ctx, "al-existing")
Expect(err).NotTo(HaveOccurred())
Expect(stored.Description).To(Equal("Album Description"))
Expect(stored.LargeImageUrl).To(Equal("http://example.com/large.jpg"))
Expect(stored.SmallImageUrl).To(Equal("http://example.com/small.jpg"))
Expect(external.QueuedAlbumRefreshes(p)).To(BeZero(), "freshly fetched info must not be refreshed again")
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
}) })
@ -91,13 +112,13 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() {
LargeImageUrl: "http://cached.com/large.jpg", LargeImageUrl: "http://cached.com/large.jpg",
ExternalInfoUpdatedAt: new(now.Add(-conf.Server().DevAlbumInfoTimeToLive / 2)), ExternalInfoUpdatedAt: new(now.Add(-conf.Server().DevAlbumInfoTimeToLive / 2)),
} }
mockAlbumRepo.SetData(model.Albums{*originalAlbum}) persistencetest.PutAlbums(ctx, ds, *originalAlbum)
updatedAlbum, err := p.UpdateAlbumInfo(ctx, "al-cached") updatedAlbum, err := p.UpdateAlbumInfo(ctx, "al-cached")
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(updatedAlbum).NotTo(BeNil()) Expect(updatedAlbum).NotTo(BeNil())
Expect(*updatedAlbum).To(Equal(*originalAlbum)) expectCached(updatedAlbum, originalAlbum)
ag.AssertNotCalled(GinkgoT(), "GetAlbumInfo", mock.Anything, mock.Anything, mock.Anything, mock.Anything) ag.AssertNotCalled(GinkgoT(), "GetAlbumInfo", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
}) })
@ -114,13 +135,14 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() {
LargeImageUrl: "http://expired.com/large.jpg", LargeImageUrl: "http://expired.com/large.jpg",
ExternalInfoUpdatedAt: new(expiredTime), ExternalInfoUpdatedAt: new(expiredTime),
} }
mockAlbumRepo.SetData(model.Albums{*originalAlbum}) persistencetest.PutAlbums(ctx, ds, *originalAlbum)
updatedAlbum, err := p.UpdateAlbumInfo(ctx, "al-expired") updatedAlbum, err := p.UpdateAlbumInfo(ctx, "al-expired")
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(updatedAlbum).NotTo(BeNil()) Expect(updatedAlbum).NotTo(BeNil())
Expect(*updatedAlbum).To(Equal(*originalAlbum)) expectCached(updatedAlbum, originalAlbum)
Expect(external.QueuedAlbumRefreshes(p)).To(Equal(1))
ag.AssertNotCalled(GinkgoT(), "GetAlbumInfo", mock.Anything, mock.Anything, mock.Anything, mock.Anything) ag.AssertNotCalled(GinkgoT(), "GetAlbumInfo", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
}) })
@ -132,7 +154,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() {
AlbumArtist: "Agent Error Artist", AlbumArtist: "Agent Error Artist",
MbzAlbumID: "mbid-agent-error", MbzAlbumID: "mbid-agent-error",
} }
mockAlbumRepo.SetData(model.Albums{*originalAlbum}) persistencetest.PutAlbums(ctx, ds, *originalAlbum)
expectedErr := errors.New("agent communication failed") expectedErr := errors.New("agent communication failed")
ag.On("GetAlbumInfo", ctx, "Agent Error Album", "Agent Error Artist", "mbid-agent-error").Return(nil, expectedErr) ag.On("GetAlbumInfo", ctx, "Agent Error Album", "Agent Error Artist", "mbid-agent-error").Return(nil, expectedErr)
@ -151,7 +173,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() {
AlbumArtist: "Agent NotFound Artist", AlbumArtist: "Agent NotFound Artist",
MbzAlbumID: "mbid-agent-notfound", MbzAlbumID: "mbid-agent-notfound",
} }
mockAlbumRepo.SetData(model.Albums{*originalAlbum}) persistencetest.PutAlbums(ctx, ds, *originalAlbum)
ag.On("GetAlbumInfo", ctx, "Agent NotFound Album", "Agent NotFound Artist", "mbid-agent-notfound").Return(nil, agents.ErrNotFound) ag.On("GetAlbumInfo", ctx, "Agent NotFound Album", "Agent NotFound Artist", "mbid-agent-notfound").Return(nil, agents.ErrNotFound)
@ -159,7 +181,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(updatedAlbum).NotTo(BeNil()) Expect(updatedAlbum).NotTo(BeNil())
Expect(*updatedAlbum).To(Equal(*originalAlbum)) expectCached(updatedAlbum, originalAlbum)
Expect(updatedAlbum.ExternalInfoUpdatedAt).To(BeNil()) Expect(updatedAlbum.ExternalInfoUpdatedAt).To(BeNil())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
@ -172,7 +194,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() {
AlbumArtist: "Throttled Artist", AlbumArtist: "Throttled Artist",
MbzAlbumID: "mbid-throttled", MbzAlbumID: "mbid-throttled",
} }
mockAlbumRepo.SetData(model.Albums{*originalAlbum}) persistencetest.PutAlbums(ctx, ds, *originalAlbum)
ag.On("GetAlbumInfo", ctx, "Throttled Album", "Throttled Artist", "mbid-throttled"). ag.On("GetAlbumInfo", ctx, "Throttled Album", "Throttled Artist", "mbid-throttled").
Return(nil, agents.ErrRetryLater) Return(nil, agents.ErrRetryLater)
@ -181,7 +203,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(updatedAlbum).NotTo(BeNil()) Expect(updatedAlbum).NotTo(BeNil())
Expect(*updatedAlbum).To(Equal(*originalAlbum)) expectCached(updatedAlbum, originalAlbum)
Expect(updatedAlbum.ExternalInfoUpdatedAt).To(BeNil()) Expect(updatedAlbum.ExternalInfoUpdatedAt).To(BeNil())
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())

View file

@ -9,9 +9,11 @@ import (
"github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/external" "github.com/navidrome/navidrome/core/external"
"github.com/navidrome/navidrome/core/matcher" "github.com/navidrome/navidrome/core/matcher"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/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"
"github.com/stretchr/testify/mock" "github.com/stretchr/testify/mock"
@ -25,18 +27,16 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
var ( var (
ctx context.Context ctx context.Context
p external.Provider p external.Provider
ds *tests.MockDataStore ds model.DataStore
ag *mockAgents ag *mockAgents
mockArtistRepo *tests.MockArtistRepo
) )
BeforeEach(func() { BeforeEach(func() {
conf.Update(func(c *conf.Options) { c.DevArtistInfoTimeToLive = 1 * time.Hour })
ctx = GinkgoT().Context() ctx = GinkgoT().Context()
ds = new(tests.MockDataStore) conf.Update(func(c *conf.Options) { c.DevArtistInfoTimeToLive = 1 * time.Hour })
ds = persistence.New(db.Db())
ag = new(mockAgents) ag = new(mockAgents)
p = external.NewProvider(ds, ag, matcher.New(ds), &fakeBroker{}) p = external.NewProvider(ctx, ds, ag, matcher.New(ds), &fakeBroker{})
mockArtistRepo = ds.Artist().(*tests.MockArtistRepo)
}) })
It("returns error when artist is not found", func() { It("returns error when artist is not found", func() {
@ -56,7 +56,6 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
ID: "ar-existing", ID: "ar-existing",
Name: "Test Artist", Name: "Test Artist",
} }
mockArtistRepo.SetData(model.Artists{*originalArtist})
expectedMBID := "mbid-artist-123" expectedMBID := "mbid-artist-123"
expectedBio := "Artist Bio" expectedBio := "Artist Bio"
@ -79,7 +78,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
ag.On("GetArtistURL", ctx, "ar-existing", "Test Artist", expectedMBID).Return(expectedURL, nil).Once() ag.On("GetArtistURL", ctx, "ar-existing", "Test Artist", expectedMBID).Return(expectedURL, nil).Once()
ag.On("GetSimilarArtists", ctx, "ar-existing", "Test Artist", expectedMBID, 100).Return(rawSimilar, nil).Once() ag.On("GetSimilarArtists", ctx, "ar-existing", "Test Artist", expectedMBID, 100).Return(rawSimilar, nil).Once()
mockArtistRepo.SetData(model.Artists{*originalArtist, similarInDS}) persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarInDS)
updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-existing", 10, false) updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-existing", 10, false)
@ -99,13 +98,22 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
Expect(updatedArtist.SimilarArtists[0].ID).To(Equal("ar-similar-2")) Expect(updatedArtist.SimilarArtists[0].ID).To(Equal("ar-similar-2"))
Expect(updatedArtist.SimilarArtists[0].Name).To(Equal("Similar Artist 2")) Expect(updatedArtist.SimilarArtists[0].Name).To(Equal("Similar Artist 2"))
stored, err := ds.Artist().Get(ctx, "ar-existing")
Expect(err).NotTo(HaveOccurred())
Expect(stored.Biography).To(Equal("Artist Bio"))
Expect(stored.LargeImageUrl).To(Equal("http://large.jpg"))
Expect(stored.ExternalInfoUpdatedAt).NotTo(BeNil())
Expect(stored.SimilarArtists).To(HaveLen(3), "the stored list keeps similar artists missing from the library")
Expect(stored.SimilarArtists[0].ID).To(Equal("ar-similar-2"))
Expect(external.QueuedArtistRefreshes(p)).To(BeZero(), "freshly fetched info must not be refreshed again")
ag.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT())
}) })
// Stamping a throttled round would cache the empty result for the whole TTL. // Stamping a throttled round would cache the empty result for the whole TTL.
It("does not stamp ExternalInfoUpdatedAt when the agents are throttled", func() { It("does not stamp ExternalInfoUpdatedAt when the agents are throttled", func() {
originalArtist := &model.Artist{ID: "ar-throttled", Name: "Throttled Artist"} originalArtist := &model.Artist{ID: "ar-throttled", Name: "Throttled Artist"}
mockArtistRepo.SetData(model.Artists{*originalArtist}) persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist)
ag.On("GetArtistMBID", ctx, "ar-throttled", "Throttled Artist").Return("", agents.ErrRetryLater).Once() ag.On("GetArtistMBID", ctx, "ar-throttled", "Throttled Artist").Return("", agents.ErrRetryLater).Once()
ag.On("GetArtistImages", ctx, "ar-throttled", "Throttled Artist", "").Return(nil, agents.ErrRetryLater).Once() ag.On("GetArtistImages", ctx, "ar-throttled", "Throttled Artist", "").Return(nil, agents.ErrRetryLater).Once()
@ -126,7 +134,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
ID: "ar-encoded-bio", ID: "ar-encoded-bio",
Name: "Encoded Bio Artist", Name: "Encoded Bio Artist",
} }
mockArtistRepo.SetData(model.Artists{*originalArtist}) persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist)
expectedMBID := "mbid-encoded-bio" expectedMBID := "mbid-encoded-bio"
expectedBio := "R&amp;B" expectedBio := "R&amp;B"
@ -160,7 +168,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
}, },
} }
similarInDS := model.Artist{ID: "ar-similar-present", Name: "Similar Present Updated"} similarInDS := model.Artist{ID: "ar-similar-present", Name: "Similar Present Updated"}
mockArtistRepo.SetData(model.Artists{*originalArtist, similarInDS}) persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarInDS)
updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-cached", 5, false) updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-cached", 5, false)
@ -172,7 +180,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
Expect(updatedArtist.ExternalUrl).To(Equal(originalArtist.ExternalUrl)) Expect(updatedArtist.ExternalUrl).To(Equal(originalArtist.ExternalUrl))
Expect(updatedArtist.Biography).To(Equal(originalArtist.Biography)) Expect(updatedArtist.Biography).To(Equal(originalArtist.Biography))
Expect(updatedArtist.LargeImageUrl).To(Equal(originalArtist.LargeImageUrl)) Expect(updatedArtist.LargeImageUrl).To(Equal(originalArtist.LargeImageUrl))
Expect(updatedArtist.ExternalInfoUpdatedAt).To(Equal(originalArtist.ExternalInfoUpdatedAt)) Expect(*updatedArtist.ExternalInfoUpdatedAt).To(BeTemporally("==", *originalArtist.ExternalInfoUpdatedAt))
Expect(updatedArtist.SimilarArtists).To(HaveLen(1)) Expect(updatedArtist.SimilarArtists).To(HaveLen(1))
Expect(updatedArtist.SimilarArtists[0].ID).To(Equal(similarInDS.ID)) Expect(updatedArtist.SimilarArtists[0].ID).To(Equal(similarInDS.ID))
@ -196,15 +204,16 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
}, },
} }
similarInDS := model.Artist{ID: "ar-exp-similar", Name: "Expired Similar Updated"} similarInDS := model.Artist{ID: "ar-exp-similar", Name: "Expired Similar Updated"}
mockArtistRepo.SetData(model.Artists{*originalArtist, similarInDS}) persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarInDS)
updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-expired", 5, false) updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-expired", 5, false)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(external.QueuedArtistRefreshes(p)).To(Equal(1))
Expect(updatedArtist).NotTo(BeNil()) Expect(updatedArtist).NotTo(BeNil())
Expect(updatedArtist.ID).To(Equal(originalArtist.ID)) Expect(updatedArtist.ID).To(Equal(originalArtist.ID))
Expect(updatedArtist.Name).To(Equal(originalArtist.Name)) Expect(updatedArtist.Name).To(Equal(originalArtist.Name))
Expect(updatedArtist.ExternalInfoUpdatedAt).To(Equal(originalArtist.ExternalInfoUpdatedAt)) Expect(*updatedArtist.ExternalInfoUpdatedAt).To(BeTemporally("==", *originalArtist.ExternalInfoUpdatedAt))
Expect(updatedArtist.SimilarArtists).To(HaveLen(1)) Expect(updatedArtist.SimilarArtists).To(HaveLen(1))
Expect(updatedArtist.SimilarArtists[0].ID).To(Equal(similarInDS.ID)) Expect(updatedArtist.SimilarArtists[0].ID).To(Equal(similarInDS.ID))
@ -229,7 +238,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
}, },
} }
similarInDS := model.Artist{ID: "ar-sim-present", Name: "Similar Present Updated"} similarInDS := model.Artist{ID: "ar-sim-present", Name: "Similar Present Updated"}
mockArtistRepo.SetData(model.Artists{*originalArtist, similarInDS}) persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarInDS)
updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-similar-test", 5, true) updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-similar-test", 5, true)
@ -250,7 +259,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
ID: "ar-agent-fail", ID: "ar-agent-fail",
Name: "Agent Fail Artist", Name: "Agent Fail Artist",
} }
mockArtistRepo.SetData(model.Artists{*originalArtist}) persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist)
expectedErr := errors.New("agent MBID failed") expectedErr := errors.New("agent MBID failed")
ag.On("GetArtistMBID", ctx, "ar-agent-fail", "Agent Fail Artist").Return("", expectedErr).Once() ag.On("GetArtistMBID", ctx, "ar-agent-fail", "Agent Fail Artist").Return("", expectedErr).Once()
@ -273,7 +282,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
Name: "ID Match Artist", Name: "ID Match Artist",
} }
similarByID := model.Artist{ID: "ar-similar-by-id", Name: "Similar By ID", MbzArtistID: "mbid-similar"} similarByID := model.Artist{ID: "ar-similar-by-id", Name: "Similar By ID", MbzArtistID: "mbid-similar"}
mockArtistRepo.SetData(model.Artists{*originalArtist, similarByID}) persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarByID)
// Agent returns similar artist with ID (highest priority matching) // Agent returns similar artist with ID (highest priority matching)
rawSimilar := []agents.Artist{ rawSimilar := []agents.Artist{
@ -301,7 +310,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
Name: "MBID Match Artist", Name: "MBID Match Artist",
} }
similarByMBID := model.Artist{ID: "ar-similar-by-mbid", Name: "Similar By MBID", MbzArtistID: "mbid-similar"} similarByMBID := model.Artist{ID: "ar-similar-by-mbid", Name: "Similar By MBID", MbzArtistID: "mbid-similar"}
mockArtistRepo.SetData(model.Artists{*originalArtist, similarByMBID}) persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarByMBID)
// Agent returns similar artist with only MBID (no ID) // Agent returns similar artist with only MBID (no ID)
rawSimilar := []agents.Artist{ rawSimilar := []agents.Artist{
@ -329,7 +338,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() {
Name: "Name Match Artist", Name: "Name Match Artist",
} }
similarByName := model.Artist{ID: "ar-similar-by-name", Name: "Similar By Name"} similarByName := model.Artist{ID: "ar-similar-by-name", Name: "Similar By Name"}
mockArtistRepo.SetData(model.Artists{*originalArtist, similarByName}) persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarByName)
// Agent returns similar artist with non-matching ID and MBID // Agent returns similar artist with non-matching ID and MBID
rawSimilar := []agents.Artist{ rawSimilar := []agents.Artist{

View file

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

View file

@ -27,7 +27,7 @@ func TestFFmpeg(t *testing.T) {
_, file, _, _ := runtime.Caller(0) _, file, _, _ := runtime.Caller(0)
appPath, _ := filepath.Abs(filepath.Join(filepath.Dir(file), "..", "..")) appPath, _ := filepath.Abs(filepath.Join(filepath.Dir(file), "..", ".."))
confPath := filepath.Join(appPath, "tests", "navidrome-test.toml") confPath := filepath.Join(appPath, "tests", "navidrome-test.toml")
_ = os.Chdir(appPath) t.Chdir(appPath)
conf.LoadFromFile(confPath) conf.LoadFromFile(confPath)
log.SetLevel(log.LevelFatal) log.SetLevel(log.LevelFatal)
RegisterFailHandler(Fail) RegisterFailHandler(Fail)

View file

@ -111,7 +111,7 @@ func (s *libraryService) SetUserLibraries(ctx context.Context, userID string, li
func (s *libraryService) ValidateLibraryAccess(ctx context.Context, userID string, libraryID int) error { func (s *libraryService) ValidateLibraryAccess(ctx context.Context, userID string, libraryID int) error {
user, ok := request.UserFrom(ctx) user, ok := request.UserFrom(ctx)
if !ok { if !ok {
return fmt.Errorf("user not found in context") return errors.New("user not found in context")
} }
// Admin users have access to all libraries // Admin users have access to all libraries
@ -157,7 +157,7 @@ func (r *libraryRepositoryWrapper) Save(ctx context.Context, lib *model.Library)
return "", err return "", err
} }
err := r.LibraryRepository.Put(ctx, lib) err := r.Put(ctx, lib)
if err != nil { if err != nil {
return "", r.mapError(err) return "", r.mapError(err)
} }
@ -205,7 +205,7 @@ func (r *libraryRepositoryWrapper) Update(ctx context.Context, id string, entity
pidChanged := (updatesColumn(cols, "pidAlbum") && originalLib.PIDAlbum != lib.PIDAlbum) || pidChanged := (updatesColumn(cols, "pidAlbum") && originalLib.PIDAlbum != lib.PIDAlbum) ||
(updatesColumn(cols, "pidTrack") && originalLib.PIDTrack != lib.PIDTrack) (updatesColumn(cols, "pidTrack") && originalLib.PIDTrack != lib.PIDTrack)
err = r.LibraryRepository.Put(ctx, lib, cols...) err = r.Put(ctx, lib, cols...)
if err != nil { if err != nil {
return r.mapError(err) return r.mapError(err)
} }
@ -350,7 +350,7 @@ func updatesColumn(cols []string, col string) bool {
func (r *libraryRepositoryWrapper) validateLibraryPath(ctx context.Context, library *model.Library) error { func (r *libraryRepositoryWrapper) validateLibraryPath(ctx context.Context, library *model.Library) error {
// Validate path format // Validate path format
if !filepath.IsAbs(library.Path) { if !filepath.IsAbs(library.Path) {
return fmt.Errorf("library path must be absolute") return errors.New("library path must be absolute")
} }
// Clean the path to normalize it // Clean the path to normalize it
@ -377,7 +377,7 @@ func (r *libraryRepositoryWrapper) validateLibraryPath(ctx context.Context, libr
} }
if !info.IsDir() { if !info.IsDir() {
return fmt.Errorf("resources.library.validation.pathNotDirectory") return errors.New("resources.library.validation.pathNotDirectory")
} }
return nil return nil

View file

@ -7,13 +7,16 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"sync" "sync"
"time"
"github.com/deluan/rest" "github.com/deluan/rest"
_ "github.com/navidrome/navidrome/adapters/gotaglib" // Register taglib extractor _ "github.com/navidrome/navidrome/adapters/gotaglib" // Register taglib extractor
"github.com/navidrome/navidrome/core" "github.com/navidrome/navidrome/core"
_ "github.com/navidrome/navidrome/core/storage/local" // Register local storage _ "github.com/navidrome/navidrome/core/storage/local" // Register local storage
"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/server/events" "github.com/navidrome/navidrome/server/events"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
@ -23,9 +26,7 @@ import (
// These tests require the local storage adapter and the taglib extractor to be registered. // These tests require the local storage adapter and the taglib extractor to be registered.
var _ = Describe("Library Service", func() { var _ = Describe("Library Service", func() {
var service core.Library var service core.Library
var ds *tests.MockDataStore var ds model.DataStore
var libraryRepo *tests.MockLibraryRepo
var userRepo *tests.MockedUserRepo
var ctx context.Context var ctx context.Context
var tempDir string var tempDir string
var scanner *tests.MockScanner var scanner *tests.MockScanner
@ -33,13 +34,21 @@ var _ = Describe("Library Service", func() {
var broker *mockEventBroker var broker *mockEventBroker
var pluginManager *mockPluginUnloader var pluginManager *mockPluginUnloader
putLibrary := func(lib model.Library) {
GinkgoHelper()
Expect(ds.Library().Put(ctx, &lib)).To(Succeed())
}
storedLibrary := func(id int) *model.Library {
GinkgoHelper()
lib, err := ds.Library().Get(ctx, id)
Expect(err).NotTo(HaveOccurred())
return lib
}
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context() ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "admin1", UserName: "admin", IsAdmin: true})
ds = &tests.MockDataStore{} ds = persistence.New(db.Db())
libraryRepo = &tests.MockLibraryRepo{}
userRepo = tests.CreateMockUserRepo()
ds.MockedLibrary = libraryRepo
ds.MockedUser = userRepo
// Create a mock scanner that tracks calls // Create a mock scanner that tracks calls
scanner = tests.NewMockScanner() scanner = tests.NewMockScanner()
@ -72,13 +81,13 @@ var _ = Describe("Library Service", func() {
Describe("Create", func() { Describe("Create", func() {
It("creates a new library successfully", func() { It("creates a new library successfully", func() {
library := &model.Library{ID: 1, Name: "New Library", Path: tempDir} library := &model.Library{ID: 2, Name: "New Library", Path: tempDir}
_, err := repo.Save(ctx, library) _, err := repo.Save(ctx, library)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(libraryRepo.Data[1].Name).To(Equal("New Library")) Expect(storedLibrary(2).Name).To(Equal("New Library"))
Expect(libraryRepo.Data[1].Path).To(Equal(tempDir)) Expect(storedLibrary(2).Path).To(Equal(tempDir))
}) })
It("fails when library name is empty", func() { It("fails when library name is empty", func() {
@ -113,14 +122,7 @@ var _ = Describe("Library Service", func() {
Context("Database constraint violations", func() { Context("Database constraint violations", func() {
BeforeEach(func() { BeforeEach(func() {
// Set up an existing library that will cause constraint violations // Set up an existing library that will cause constraint violations
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Existing Library", Path: tempDir})
{ID: 1, Name: "Existing Library", Path: tempDir},
})
})
AfterEach(func() {
// Reset custom PutFn after each test
libraryRepo.PutFn = nil
}) })
It("handles name uniqueness constraint violation from database", func() { It("handles name uniqueness constraint violation from database", func() {
@ -129,13 +131,7 @@ var _ = Describe("Library Service", func() {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
DeferCleanup(func() { os.RemoveAll(otherTempDir) }) DeferCleanup(func() { os.RemoveAll(otherTempDir) })
// Try to create another library with the same name library := &model.Library{ID: 3, Name: "Existing Library", Path: otherTempDir}
library := &model.Library{ID: 2, Name: "Existing Library", Path: otherTempDir}
// Mock the repository to return a UNIQUE constraint error
libraryRepo.PutFn = func(library *model.Library) error {
return errors.New("UNIQUE constraint failed: library.name")
}
_, err = repo.Save(ctx, library) _, err = repo.Save(ctx, library)
@ -146,13 +142,7 @@ var _ = Describe("Library Service", func() {
}) })
It("handles path uniqueness constraint violation from database", func() { It("handles path uniqueness constraint violation from database", func() {
// Try to create another library with the same path library := &model.Library{ID: 3, Name: "Different Library", Path: tempDir}
library := &model.Library{ID: 2, Name: "Different Library", Path: tempDir}
// Mock the repository to return a UNIQUE constraint error
libraryRepo.PutFn = func(library *model.Library) error {
return errors.New("UNIQUE constraint failed: library.path")
}
_, err := repo.Save(ctx, library) _, err := repo.Save(ctx, library)
@ -166,9 +156,7 @@ var _ = Describe("Library Service", func() {
Describe("Update", func() { Describe("Update", func() {
BeforeEach(func() { BeforeEach(func() {
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir})
{ID: 1, Name: "Original Library", Path: tempDir},
})
}) })
It("updates an existing library successfully", func() { It("updates an existing library successfully", func() {
@ -176,22 +164,24 @@ var _ = Describe("Library Service", func() {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
DeferCleanup(func() { os.RemoveAll(newTempDir) }) DeferCleanup(func() { os.RemoveAll(newTempDir) })
library := &model.Library{ID: 1, Name: "Updated Library", Path: newTempDir} library := &model.Library{ID: 2, Name: "Updated Library", Path: newTempDir}
err = repo.Update(ctx, "1", *library) err = repo.Update(ctx, "2", *library)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(libraryRepo.Data[1].Name).To(Equal("Updated Library")) Expect(storedLibrary(2).Name).To(Equal("Updated Library"))
Expect(libraryRepo.Data[1].Path).To(Equal(newTempDir)) Expect(storedLibrary(2).Path).To(Equal(newTempDir))
}) })
It("forwards the columns sent by the client to the repository", func() { It("forwards the columns sent by the client to the repository", func() {
library := &model.Library{ID: 1, Name: "Updated Library", Path: tempDir} putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir, PIDAlbum: "folder"})
library := &model.Library{ID: 2, Name: "Updated Library", Path: tempDir}
err := repo.Update(ctx, "1", *library, "name", "path") err := repo.Update(ctx, "2", *library, "name", "path")
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(libraryRepo.PutCols).To(Equal([]string{"name", "path"})) Expect(storedLibrary(2).Name).To(Equal("Updated Library"))
Expect(storedLibrary(2).PIDAlbum).To(Equal("folder"))
}) })
It("fails when library doesn't exist", func() { It("fails when library doesn't exist", func() {
@ -209,9 +199,9 @@ var _ = Describe("Library Service", func() {
}) })
It("fails when library name is empty", func() { It("fails when library name is empty", func() {
library := &model.Library{ID: 1, Path: tempDir} library := &model.Library{ID: 2, Path: tempDir}
err := repo.Update(ctx, "1", *library) err := repo.Update(ctx, "2", *library)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("ra.validation.required")) Expect(err.Error()).To(ContainSubstring("ra.validation.required"))
@ -219,48 +209,39 @@ var _ = Describe("Library Service", func() {
It("cleans and normalizes the path on update", func() { It("cleans and normalizes the path on update", func() {
unnormalizedPath := tempDir + "//../" + filepath.Base(tempDir) unnormalizedPath := tempDir + "//../" + filepath.Base(tempDir)
library := &model.Library{ID: 1, Name: "Updated Library", Path: unnormalizedPath} library := &model.Library{ID: 2, Name: "Updated Library", Path: unnormalizedPath}
err := repo.Update(ctx, "1", *library) err := repo.Update(ctx, "2", *library)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(libraryRepo.Data[1].Path).To(Equal(filepath.Clean(unnormalizedPath))) Expect(storedLibrary(2).Path).To(Equal(filepath.Clean(unnormalizedPath)))
}) })
It("allows updating library with same name (no change)", func() { It("allows updating library with same name (no change)", func() {
// Set up a library // Set up a library
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Test Library", Path: tempDir})
{ID: 1, Name: "Test Library", Path: tempDir},
})
// Update the library keeping the same name (should be allowed) // Update the library keeping the same name (should be allowed)
library := &model.Library{ID: 1, Name: "Test Library", Path: tempDir} library := &model.Library{ID: 2, Name: "Test Library", Path: tempDir}
err := repo.Update(ctx, "1", *library) err := repo.Update(ctx, "2", *library)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
}) })
It("allows updating library with same path (no change)", func() { It("allows updating library with same path (no change)", func() {
// Set up a library // Set up a library
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Test Library", Path: tempDir})
{ID: 1, Name: "Test Library", Path: tempDir},
})
// Update the library keeping the same path (should be allowed) // Update the library keeping the same path (should be allowed)
library := &model.Library{ID: 1, Name: "Test Library", Path: tempDir} library := &model.Library{ID: 2, Name: "Test Library", Path: tempDir}
err := repo.Update(ctx, "1", *library) err := repo.Update(ctx, "2", *library)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
}) })
Context("Database constraint violations during update", func() { Context("Database constraint violations during update", func() {
BeforeEach(func() {
// Reset any custom PutFn from previous tests
libraryRepo.PutFn = nil
})
It("handles name uniqueness constraint violation during update", func() { It("handles name uniqueness constraint violation during update", func() {
// Create additional temp directory for the test // Create additional temp directory for the test
otherTempDir, err := os.MkdirTemp("", "navidrome-other-") otherTempDir, err := os.MkdirTemp("", "navidrome-other-")
@ -268,20 +249,12 @@ var _ = Describe("Library Service", func() {
DeferCleanup(func() { os.RemoveAll(otherTempDir) }) DeferCleanup(func() { os.RemoveAll(otherTempDir) })
// Set up two libraries // Set up two libraries
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Library One", Path: tempDir})
{ID: 1, Name: "Library One", Path: tempDir}, putLibrary(model.Library{ID: 3, Name: "Library Two", Path: otherTempDir})
{ID: 2, Name: "Library Two", Path: otherTempDir},
})
// Mock database constraint violation library := &model.Library{ID: 3, Name: "Library One", Path: otherTempDir}
libraryRepo.PutFn = func(library *model.Library) error {
return errors.New("UNIQUE constraint failed: library.name")
}
// Try to update library 2 to have the same name as library 1 err = repo.Update(ctx, "3", *library)
library := &model.Library{ID: 2, Name: "Library One", Path: otherTempDir}
err = repo.Update(ctx, "2", *library)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
var validationErr *rest.ValidationError var validationErr *rest.ValidationError
@ -296,20 +269,12 @@ var _ = Describe("Library Service", func() {
DeferCleanup(func() { os.RemoveAll(otherTempDir) }) DeferCleanup(func() { os.RemoveAll(otherTempDir) })
// Set up two libraries // Set up two libraries
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Library One", Path: tempDir})
{ID: 1, Name: "Library One", Path: tempDir}, putLibrary(model.Library{ID: 3, Name: "Library Two", Path: otherTempDir})
{ID: 2, Name: "Library Two", Path: otherTempDir},
})
// Mock database constraint violation library := &model.Library{ID: 3, Name: "Library Two", Path: tempDir}
libraryRepo.PutFn = func(library *model.Library) error {
return errors.New("UNIQUE constraint failed: library.path")
}
// Try to update library 2 to have the same path as library 1 err = repo.Update(ctx, "3", *library)
library := &model.Library{ID: 2, Name: "Library Two", Path: tempDir}
err = repo.Update(ctx, "2", *library)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
var validationErr *rest.ValidationError var validationErr *rest.ValidationError
@ -413,15 +378,13 @@ var _ = Describe("Library Service", func() {
Context("Update operation", func() { Context("Update operation", func() {
BeforeEach(func() { BeforeEach(func() {
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Test Library", Path: tempDir})
{ID: 1, Name: "Test Library", Path: tempDir},
})
}) })
It("fails when updated path is not absolute", func() { It("fails when updated path is not absolute", func() {
library := &model.Library{ID: 1, Name: "Test", Path: "relative/path"} library := &model.Library{ID: 2, Name: "Test", Path: "relative/path"}
err := repo.Update(ctx, "1", *library) err := repo.Update(ctx, "2", *library)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
var validationErr *rest.ValidationError var validationErr *rest.ValidationError
@ -431,23 +394,21 @@ var _ = Describe("Library Service", func() {
It("allows updating library with same name (no change)", func() { It("allows updating library with same name (no change)", func() {
// Set up a library // Set up a library
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Test Library", Path: tempDir})
{ID: 1, Name: "Test Library", Path: tempDir},
})
// Update the library keeping the same name (should be allowed) // Update the library keeping the same name (should be allowed)
library := &model.Library{ID: 1, Name: "Test Library", Path: tempDir} library := &model.Library{ID: 2, Name: "Test Library", Path: tempDir}
err := repo.Update(ctx, "1", *library) err := repo.Update(ctx, "2", *library)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
}) })
It("fails when updated path does not exist", func() { It("fails when updated path does not exist", func() {
nonExistentPath := filepath.Join(tempDir, "nonexistent") nonExistentPath := filepath.Join(tempDir, "nonexistent")
library := &model.Library{ID: 1, Name: "Test", Path: nonExistentPath} library := &model.Library{ID: 2, Name: "Test", Path: nonExistentPath}
err := repo.Update(ctx, "1", *library) err := repo.Update(ctx, "2", *library)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
var validationErr *rest.ValidationError var validationErr *rest.ValidationError
@ -460,9 +421,9 @@ var _ = Describe("Library Service", func() {
err := os.WriteFile(testFile, []byte("test"), 0600) err := os.WriteFile(testFile, []byte("test"), 0600)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
library := &model.Library{ID: 1, Name: "Test", Path: testFile} library := &model.Library{ID: 2, Name: "Test", Path: testFile}
err = repo.Update(ctx, "1", *library) err = repo.Update(ctx, "2", *library)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
var validationErr *rest.ValidationError var validationErr *rest.ValidationError
@ -472,9 +433,9 @@ var _ = Describe("Library Service", func() {
It("handles multiple validation errors on update", func() { It("handles multiple validation errors on update", func() {
// Try to update with empty name and invalid path // Try to update with empty name and invalid path
library := &model.Library{ID: 1, Name: "", Path: "relative/path"} library := &model.Library{ID: 2, Name: "", Path: "relative/path"}
err := repo.Update(ctx, "1", *library) err := repo.Update(ctx, "2", *library)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
var validationErr *rest.ValidationError var validationErr *rest.ValidationError
@ -489,16 +450,15 @@ var _ = Describe("Library Service", func() {
Describe("Delete", func() { Describe("Delete", func() {
BeforeEach(func() { BeforeEach(func() {
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Library to Delete", Path: tempDir})
{ID: 1, Name: "Library to Delete", Path: tempDir},
})
}) })
It("deletes an existing library successfully", func() { It("deletes an existing library successfully", func() {
err := repo.Delete(ctx, "1") err := repo.Delete(ctx, "2")
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(libraryRepo.Data).To(HaveLen(0)) _, err = ds.Library().Get(ctx, 2)
Expect(err).To(MatchError(model.ErrNotFound))
}) })
It("fails when library doesn't exist", func() { It("fails when library doesn't exist", func() {
@ -517,22 +477,15 @@ var _ = Describe("Library Service", func() {
regularUser = &model.User{ID: "user1", UserName: "regular", IsAdmin: false} regularUser = &model.User{ID: "user1", UserName: "regular", IsAdmin: false}
adminUser = &model.User{ID: "admin1", UserName: "admin", IsAdmin: true} adminUser = &model.User{ID: "admin1", UserName: "admin", IsAdmin: true}
userRepo.Data = map[string]*model.User{ Expect(ds.User().Put(ctx, regularUser)).To(Succeed())
"regular": regularUser, Expect(ds.User().Put(ctx, adminUser)).To(Succeed())
"admin": adminUser, putLibrary(model.Library{ID: 2, Name: "Library 2", Path: "/music2"})
} putLibrary(model.Library{ID: 3, Name: "Library 3", Path: "/music3"})
libraryRepo.SetData(model.Libraries{
{ID: 1, Name: "Library 1", Path: "/music1"},
{ID: 2, Name: "Library 2", Path: "/music2"},
{ID: 3, Name: "Library 3", Path: "/music3"},
})
}) })
Describe("GetUserLibraries", func() { Describe("GetUserLibraries", func() {
It("returns user's libraries", func() { It("returns user's libraries", func() {
userRepo.UserLibraries = map[string][]int{ Expect(ds.User().SetUserLibraries(ctx, "user1", []int{1})).To(Succeed())
"user1": {1},
}
result, err := service.GetUserLibraries(ctx, "user1") result, err := service.GetUserLibraries(ctx, "user1")
@ -554,7 +507,8 @@ var _ = Describe("Library Service", func() {
err := service.SetUserLibraries(ctx, "user1", []int{1, 2}) err := service.SetUserLibraries(ctx, "user1", []int{1, 2})
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
libraries := userRepo.UserLibraries["user1"] libraries, err := ds.User().GetUserLibraries(ctx, "user1")
Expect(err).NotTo(HaveOccurred())
Expect(libraries).To(HaveLen(2)) Expect(libraries).To(HaveLen(2))
}) })
@ -609,10 +563,8 @@ var _ = Describe("Library Service", func() {
Context("regular user", func() { Context("regular user", func() {
BeforeEach(func() { BeforeEach(func() {
Expect(ds.User().SetUserLibraries(ctx, "user1", []int{1})).To(Succeed())
ctx = request.WithUser(ctx, *regularUser) ctx = request.WithUser(ctx, *regularUser)
userRepo.UserLibraries = map[string][]int{
"user1": {1},
}
}) })
It("allows access to user's libraries", func() { It("allows access to user's libraries", func() {
@ -631,7 +583,7 @@ var _ = Describe("Library Service", func() {
Context("no user in context", func() { Context("no user in context", func() {
It("fails with user not found error", func() { It("fails with user not found error", func() {
err := service.ValidateLibraryAccess(ctx, "user1", 1) err := service.ValidateLibraryAccess(GinkgoT().Context(), "user1", 1)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("user not found in context")) Expect(err.Error()).To(ContainSubstring("user not found in context"))
@ -649,7 +601,7 @@ var _ = Describe("Library Service", func() {
}) })
It("triggers scan when creating a new library", func() { It("triggers scan when creating a new library", func() {
library := &model.Library{ID: 1, Name: "New Library", Path: tempDir} library := &model.Library{ID: 2, Name: "New Library", Path: tempDir}
_, err := repo.Save(ctx, library) _, err := repo.Save(ctx, library)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
@ -657,7 +609,7 @@ var _ = Describe("Library Service", func() {
// Wait briefly for the goroutine to complete // Wait briefly for the goroutine to complete
Eventually(func() int { Eventually(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
// Verify scan was called with correct parameters // Verify scan was called with correct parameters
calls := scanner.GetScanAllCalls() calls := scanner.GetScanAllCalls()
@ -666,9 +618,7 @@ var _ = Describe("Library Service", func() {
It("triggers scan when updating library path", func() { It("triggers scan when updating library path", func() {
// First create a library // First create a library
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir})
{ID: 1, Name: "Original Library", Path: tempDir},
})
// Create a new temporary directory for the update // Create a new temporary directory for the update
newTempDir, err := os.MkdirTemp("", "navidrome-library-update-") newTempDir, err := os.MkdirTemp("", "navidrome-library-update-")
@ -676,14 +626,14 @@ var _ = Describe("Library Service", func() {
DeferCleanup(func() { os.RemoveAll(newTempDir) }) DeferCleanup(func() { os.RemoveAll(newTempDir) })
// Update the library with a new path // Update the library with a new path
library := &model.Library{ID: 1, Name: "Updated Library", Path: newTempDir} library := &model.Library{ID: 2, Name: "Updated Library", Path: newTempDir}
err = repo.Update(ctx, "1", *library) err = repo.Update(ctx, "2", *library)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
// Wait briefly for the goroutine to complete // Wait briefly for the goroutine to complete
Eventually(func() int { Eventually(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
// Verify scan was called with correct parameters // Verify scan was called with correct parameters
calls := scanner.GetScanAllCalls() calls := scanner.GetScanAllCalls()
@ -692,61 +642,59 @@ var _ = Describe("Library Service", func() {
It("does not trigger scan when updating library without path change", func() { It("does not trigger scan when updating library without path change", func() {
// First create a library // First create a library
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir})
{ID: 1, Name: "Original Library", Path: tempDir},
})
// Update the library name only (same path) // Update the library name only (same path)
library := &model.Library{ID: 1, Name: "Updated Name", Path: tempDir} library := &model.Library{ID: 2, Name: "Updated Name", Path: tempDir}
err := repo.Update(ctx, "1", *library) err := repo.Update(ctx, "2", *library)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
// Wait a bit to ensure no scan was triggered // Wait a bit to ensure no scan was triggered
Consistently(func() int { Consistently(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
It("triggers scan when updating the library PID config", func() { It("triggers scan when updating the library PID config", func() {
libraryRepo.SetData(model.Libraries{{ID: 1, Name: "Library", Path: tempDir}}) putLibrary(model.Library{ID: 2, Name: "Library", Path: tempDir})
library := model.Library{ID: 1, Name: "Library", Path: tempDir, PIDAlbum: "folder"} library := model.Library{ID: 2, Name: "Library", Path: tempDir, PIDAlbum: "folder"}
Expect(repo.Update(ctx, "1", library)).To(Succeed()) Expect(repo.Update(ctx, "2", library)).To(Succeed())
Eventually(func() int { Eventually(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
// A quick scan: the scanner itself rescans this library in full // A quick scan: the scanner itself rescans this library in full
Expect(scanner.GetScanAllCalls()[0].FullScan).To(BeFalse()) Expect(scanner.GetScanAllCalls()[0].FullScan).To(BeFalse())
}) })
It("does not trigger scan when the PID fields were not sent", func() { It("does not trigger scan when the PID fields were not sent", func() {
libraryRepo.SetData(model.Libraries{{ID: 1, Name: "Library", Path: tempDir, PIDAlbum: "folder"}}) putLibrary(model.Library{ID: 2, Name: "Library", Path: tempDir, PIDAlbum: "folder"})
// The REST layer decodes a missing pidAlbum as "". Only the sent fields count. // The REST layer decodes a missing pidAlbum as "". Only the sent fields count.
library := model.Library{ID: 1, Name: "Renamed", Path: tempDir} library := model.Library{ID: 2, Name: "Renamed", Path: tempDir}
Expect(repo.Update(ctx, "1", library, "name", "path")).To(Succeed()) Expect(repo.Update(ctx, "2", library, "name", "path")).To(Succeed())
Consistently(func() int { Consistently(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
It("waits for a running scan before triggering a new one", func() { It("waits for a running scan before triggering a new one", func() {
libraryRepo.SetData(model.Libraries{{ID: 1, Name: "Library", Path: tempDir}}) putLibrary(model.Library{ID: 2, Name: "Library", Path: tempDir})
scanner.SetScanning(true) scanner.SetScanning(true)
library := model.Library{ID: 1, Name: "Library", Path: tempDir, PIDAlbum: "folder"} library := model.Library{ID: 2, Name: "Library", Path: tempDir, PIDAlbum: "folder"}
Expect(repo.Update(ctx, "1", library)).To(Succeed()) Expect(repo.Update(ctx, "2", library)).To(Succeed())
Consistently(func() int { Consistently(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "200ms", "20ms").Should(Equal(0)) }, 200*time.Millisecond, 20*time.Millisecond).Should(Equal(0))
scanner.SetScanning(false) scanner.SetScanning(false)
Eventually(func() int { Eventually(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "3s", "20ms").Should(Equal(1)) }, 3*time.Second, 20*time.Millisecond).Should(Equal(1))
}) })
It("does not trigger scan when library creation fails", func() { It("does not trigger scan when library creation fails", func() {
@ -759,40 +707,36 @@ var _ = Describe("Library Service", func() {
// Ensure no scan was triggered since creation failed // Ensure no scan was triggered since creation failed
Consistently(func() int { Consistently(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
It("does not trigger scan when library update fails", func() { It("does not trigger scan when library update fails", func() {
// First create a library // First create a library
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir})
{ID: 1, Name: "Original Library", Path: tempDir},
})
// Try to update with invalid data (empty name) // Try to update with invalid data (empty name)
library := &model.Library{ID: 1, Name: "", Path: tempDir} library := &model.Library{ID: 2, Name: "", Path: tempDir}
err := repo.Update(ctx, "1", *library) err := repo.Update(ctx, "2", *library)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
// Ensure no scan was triggered since update failed // Ensure no scan was triggered since update failed
Consistently(func() int { Consistently(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
It("triggers scan when deleting a library", func() { It("triggers scan when deleting a library", func() {
// First create a library // First create a library
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Library to Delete", Path: tempDir})
{ID: 1, Name: "Library to Delete", Path: tempDir},
})
// Delete the library // Delete the library
err := repo.Delete(ctx, "1") err := repo.Delete(ctx, "2")
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
// Wait briefly for the goroutine to complete // Wait briefly for the goroutine to complete
Eventually(func() int { Eventually(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
// Verify scan was called with correct parameters // Verify scan was called with correct parameters
calls := scanner.GetScanAllCalls() calls := scanner.GetScanAllCalls()
@ -807,12 +751,12 @@ var _ = Describe("Library Service", func() {
// Ensure no scan was triggered since deletion failed // Ensure no scan was triggered since deletion failed
Consistently(func() int { Consistently(func() int {
return scanner.GetScanAllCallCount() return scanner.GetScanAllCallCount()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
Context("Watcher Integration", func() { Context("Watcher Integration", func() {
It("starts watcher when creating a new library", func() { It("starts watcher when creating a new library", func() {
library := &model.Library{ID: 1, Name: "New Library", Path: tempDir} library := &model.Library{ID: 2, Name: "New Library", Path: tempDir}
_, err := repo.Save(ctx, library) _, err := repo.Save(ctx, library)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
@ -820,21 +764,19 @@ var _ = Describe("Library Service", func() {
// Verify watcher was started // Verify watcher was started
Eventually(func() int { Eventually(func() int {
return watcherManager.lenStarted() return watcherManager.lenStarted()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
Expect(watcherManager.StartedWatchers[0].ID).To(Equal(1)) Expect(watcherManager.StartedWatchers[0].ID).To(Equal(2))
Expect(watcherManager.StartedWatchers[0].Name).To(Equal("New Library")) Expect(watcherManager.StartedWatchers[0].Name).To(Equal("New Library"))
Expect(watcherManager.StartedWatchers[0].Path).To(Equal(tempDir)) Expect(watcherManager.StartedWatchers[0].Path).To(Equal(tempDir))
}) })
It("restarts watcher when library path is updated", func() { It("restarts watcher when library path is updated", func() {
// First create a library // First create a library
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir})
{ID: 1, Name: "Original Library", Path: tempDir},
})
// Simulate that this library already has a watcher // Simulate that this library already has a watcher
watcherManager.simulateExistingLibrary(model.Library{ID: 1, Name: "Original Library", Path: tempDir}) watcherManager.simulateExistingLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir})
// Create a new temp directory for the update // Create a new temp directory for the update
newTempDir, err := os.MkdirTemp("", "navidrome-library-update-") newTempDir, err := os.MkdirTemp("", "navidrome-library-update-")
@ -842,58 +784,52 @@ var _ = Describe("Library Service", func() {
DeferCleanup(func() { os.RemoveAll(newTempDir) }) DeferCleanup(func() { os.RemoveAll(newTempDir) })
// Update library with new path // Update library with new path
library := &model.Library{ID: 1, Name: "Updated Library", Path: newTempDir} library := &model.Library{ID: 2, Name: "Updated Library", Path: newTempDir}
err = repo.Update(ctx, "1", *library) err = repo.Update(ctx, "2", *library)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
// Verify watcher was restarted // Verify watcher was restarted
Eventually(func() int { Eventually(func() int {
return watcherManager.lenRestarted() return watcherManager.lenRestarted()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
Expect(watcherManager.RestartedWatchers[0].ID).To(Equal(1)) Expect(watcherManager.RestartedWatchers[0].ID).To(Equal(2))
Expect(watcherManager.RestartedWatchers[0].Path).To(Equal(newTempDir)) Expect(watcherManager.RestartedWatchers[0].Path).To(Equal(newTempDir))
}) })
It("does not restart watcher when only library name is updated", func() { It("does not restart watcher when only library name is updated", func() {
// First create a library // First create a library
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir})
{ID: 1, Name: "Original Library", Path: tempDir},
})
// Update library with same path but different name // Update library with same path but different name
library := &model.Library{ID: 1, Name: "Updated Name", Path: tempDir} library := &model.Library{ID: 2, Name: "Updated Name", Path: tempDir}
err := repo.Update(ctx, "1", *library) err := repo.Update(ctx, "2", *library)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
// Verify watcher was NOT restarted (since path didn't change) // Verify watcher was NOT restarted (since path didn't change)
Consistently(func() int { Consistently(func() int {
return watcherManager.lenRestarted() return watcherManager.lenRestarted()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
It("stops watcher when library is deleted", func() { It("stops watcher when library is deleted", func() {
// Set up a library // Set up a library
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Test Library", Path: tempDir})
{ID: 1, Name: "Test Library", Path: tempDir},
})
err := repo.Delete(ctx, "1") err := repo.Delete(ctx, "2")
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
// Verify watcher was stopped // Verify watcher was stopped
Eventually(func() int { Eventually(func() int {
return watcherManager.lenStopped() return watcherManager.lenStopped()
}, "1s", "10ms").Should(Equal(1)) }, time.Second, 10*time.Millisecond).Should(Equal(1))
Expect(watcherManager.StoppedWatchers[0]).To(Equal(1)) Expect(watcherManager.StoppedWatchers[0]).To(Equal(2))
}) })
It("does not stop watcher when library deletion fails", func() { It("does not stop watcher when library deletion fails", func() {
// Set up a library // Set up a library
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Test Library", Path: tempDir})
{ID: 1, Name: "Test Library", Path: tempDir},
})
// Mock deletion to fail by trying to delete non-existent library // Mock deletion to fail by trying to delete non-existent library
err := repo.Delete(ctx, "999") err := repo.Delete(ctx, "999")
@ -902,7 +838,7 @@ var _ = Describe("Library Service", func() {
// Verify watcher was NOT stopped since deletion failed // Verify watcher was NOT stopped since deletion failed
Consistently(func() int { Consistently(func() int {
return watcherManager.lenStopped() return watcherManager.lenStopped()
}, "100ms", "10ms").Should(Equal(0)) }, 100*time.Millisecond, 10*time.Millisecond).Should(Equal(0))
}) })
}) })
}) })
@ -918,7 +854,7 @@ var _ = Describe("Library Service", func() {
}) })
It("sends refresh event when creating a library", func() { It("sends refresh event when creating a library", func() {
library := &model.Library{ID: 1, Name: "New Library", Path: tempDir} library := &model.Library{ID: 2, Name: "New Library", Path: tempDir}
_, err := repo.Save(ctx, library) _, err := repo.Save(ctx, library)
@ -928,12 +864,10 @@ var _ = Describe("Library Service", func() {
It("sends refresh event when updating a library", func() { It("sends refresh event when updating a library", func() {
// First create a library // First create a library
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir})
{ID: 1, Name: "Original Library", Path: tempDir},
})
library := &model.Library{ID: 1, Name: "Updated Library", Path: tempDir} library := &model.Library{ID: 2, Name: "Updated Library", Path: tempDir}
err := repo.Update(ctx, "1", *library) err := repo.Update(ctx, "2", *library)
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
Expect(broker.Events).To(HaveLen(1)) Expect(broker.Events).To(HaveLen(1))
@ -941,9 +875,7 @@ var _ = Describe("Library Service", func() {
It("sends refresh event when deleting a library", func() { It("sends refresh event when deleting a library", func() {
// First create a library // First create a library
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Library to Delete", Path: tempDir})
{ID: 2, Name: "Library to Delete", Path: tempDir},
})
err := repo.Delete(ctx, "2") err := repo.Delete(ctx, "2")
@ -963,9 +895,7 @@ var _ = Describe("Library Service", func() {
}) })
It("calls UnloadDisabledPlugins after successful library deletion", func() { It("calls UnloadDisabledPlugins after successful library deletion", func() {
libraryRepo.SetData(model.Libraries{ putLibrary(model.Library{ID: 2, Name: "Library to Delete", Path: tempDir})
{ID: 2, Name: "Library to Delete", Path: tempDir},
})
err := repo.Delete(ctx, "2") err := repo.Delete(ctx, "2")
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())

View file

@ -9,6 +9,7 @@ import (
"github.com/navidrome/navidrome/core/storage/local" "github.com/navidrome/navidrome/core/storage/local"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model/metadata" "github.com/navidrome/navidrome/model/metadata"
"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"
@ -17,11 +18,13 @@ import (
func TestLyrics(t *testing.T) { func TestLyrics(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, "Lyrics Suite") RunSpecs(t, "Lyrics Suite")
} }
var _ = configtest.RestoreAfterEachSpec() var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()
// core/storage/local calls log.Fatal if the default scanner extractor is unregistered // core/storage/local calls log.Fatal if the default scanner extractor is unregistered
// when constructing any localStorage. Register a no-op so storage.For("file://...") works // when constructing any localStorage. Register a no-op so storage.For("file://...") works

View file

@ -3,17 +3,25 @@ package lyrics_test
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"testing/fstest"
"time"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/lyrics" "github.com/navidrome/navidrome/core/lyrics"
"github.com/navidrome/navidrome/core/storage/storagetest"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
"github.com/navidrome/navidrome/utils" "github.com/navidrome/navidrome/utils"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"golang.org/x/text/unicode/norm"
) )
var _ = Describe("Lyrics", func() { var _ = Describe("Lyrics", func() {
@ -164,7 +172,7 @@ var _ = Describe("Lyrics", func() {
conf.Update(func(c *conf.Options) { c.LyricsPriority = priority }) conf.Update(func(c *conf.Options) { c.LyricsPriority = priority })
svc := lyrics.NewLyrics(nil, nil) svc := lyrics.NewLyrics(nil, nil)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(expected)) Expect(list).To(Equal(expected))
}, },
Entry("embedded > lrc > txt", "embedded,.lrc,.txt", embeddedLyrics), Entry("embedded > lrc > txt", "embedded,.lrc,.txt", embeddedLyrics),
@ -177,23 +185,16 @@ var _ = Describe("Lyrics", func() {
It("resolves source priority across duplicate media files", func() { It("resolves source priority across duplicate media files", func() {
conf.Update(func(c *conf.Options) { c.LyricsPriority = ".ttml,embedded" }) conf.Update(func(c *conf.Options) { c.LyricsPriority = ".ttml,embedded" })
embeddedJSON, err := json.Marshal(embeddedLyrics) embeddedJSON, err := json.Marshal(embeddedLyrics)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
repo := &tests.MockMediaFileRepo{} ds := persistence.New(db.Db())
repo.SetData(model.MediaFiles{ useRepoRootAsLibrary(ctx, ds)
{ putRickAstleySong(ctx, ds, "tests/fixtures/01 Invisible (RED) Edit Version.mp3", string(embeddedJSON))
Lyrics: string(embeddedJSON), putRickAstleySong(ctx, ds, "tests/fixtures/test.mp3", "[]")
Path: "tests/fixtures/01 Invisible (RED) Edit Version.mp3", svc := lyrics.NewLyrics(ds, nil)
},
{
Lyrics: "[]",
Path: "tests/fixtures/test.mp3",
},
})
svc := lyrics.NewLyrics(&tests.MockDataStore{MockedMediaFile: repo}, nil)
list, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up") list, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(ttmlLyrics)) Expect(list).To(Equal(ttmlLyrics))
}) })
@ -221,7 +222,7 @@ var _ = Describe("Lyrics", func() {
Path: "song.mp3", Path: "song.mp3",
}) })
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(HaveLen(1)) Expect(list).To(HaveLen(1))
Expect(list[0].Line).To(Equal([]model.Line{ Expect(list[0].Line).To(Equal([]model.Line{
{Start: new(int64(1000)), Value: "Upper suffix"}, {Start: new(int64(1000)), Value: "Upper suffix"},
@ -248,7 +249,7 @@ var _ = Describe("Lyrics", func() {
// ParseLyrics falls back to plain text for any suffix when the content // ParseLyrics falls back to plain text for any suffix when the content
// doesn't match the structured format, so the .yaml hit is non-empty and // doesn't match the structured format, so the .yaml hit is non-empty and
// shadows the lower-priority .lrc entirely. // shadows the lower-priority .lrc entirely.
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(HaveLen(1)) Expect(list).To(HaveLen(1))
Expect(list[0].Synced).To(BeFalse()) Expect(list[0].Synced).To(BeFalse())
Expect(list[0].Line).To(Equal([]model.Line{ Expect(list[0].Line).To(Equal([]model.Line{
@ -256,6 +257,35 @@ var _ = Describe("Lyrics", func() {
})) }))
}) })
It("resolves an external sidecar whose Unicode normalization differs from the track path", func() {
// An in-memory FS keeps the NFC/NFD mismatch byte-exact. The host filesystem
// may normalize names on lookup and hide the bug. See openSidecar.
const scheme = "fake-lyrics-e2e"
fsys := &storagetest.FakeFS{}
storagetest.Register(scheme, fsys)
const base = "03. 鬱P feat. 初音ミク - ガ"
modTime := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
fsys.SetFiles(fstest.MapFS{
norm.NFC.String(base) + ".flac": &fstest.MapFile{Data: []byte("audio"), ModTime: modTime},
norm.NFD.String(base) + ".lrc": &fstest.MapFile{Data: []byte("[00:18.80]We're no strangers to love"), ModTime: modTime},
})
// Default priority from the bug report: ".lrc,.txt,embedded".
conf.Update(func(c *conf.Options) { c.LyricsPriority = ".lrc,.txt,embedded" })
svc := lyrics.NewLyrics(nil, nil)
list, err := svc.GetLyrics(ctx, &model.MediaFile{
LibraryPath: scheme + ":///music",
Path: norm.NFC.String(base) + ".flac",
})
Expect(err).ToNot(HaveOccurred())
Expect(list).To(HaveLen(1))
Expect(list[0].Synced).To(BeTrue())
Expect(list[0].Line).To(HaveLen(1))
Expect(list[0].Line[0].Value).To(Equal("We're no strangers to love"))
})
Context("Errors", func() { Context("Errors", func() {
var RegularUserContext = XContext var RegularUserContext = XContext
var isRegularUser = os.Getuid() != 0 var isRegularUser = os.Getuid() != 0
@ -286,7 +316,7 @@ var _ = Describe("Lyrics", func() {
svc := lyrics.NewLyrics(nil, nil) svc := lyrics.NewLyrics(nil, nil)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(embeddedLyrics)) Expect(list).To(Equal(embeddedLyrics))
}) })
@ -295,7 +325,7 @@ var _ = Describe("Lyrics", func() {
svc := lyrics.NewLyrics(nil, nil) svc := lyrics.NewLyrics(nil, nil)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(BeEmpty()) Expect(list).To(BeEmpty())
}) })
}) })
@ -313,7 +343,7 @@ var _ = Describe("Lyrics", func() {
mockLoader.lyrics = unsyncedLyrics mockLoader.lyrics = unsyncedLyrics
svc := lyrics.NewLyrics(nil, mockLoader) svc := lyrics.NewLyrics(nil, mockLoader)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(unsyncedLyrics)) Expect(list).To(Equal(unsyncedLyrics))
}) })
@ -323,7 +353,7 @@ var _ = Describe("Lyrics", func() {
mockLoader.lyrics = unsyncedLyrics mockLoader.lyrics = unsyncedLyrics
svc := lyrics.NewLyrics(nil, mockLoader) svc := lyrics.NewLyrics(nil, mockLoader)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(unsyncedLyrics)) Expect(list).To(Equal(unsyncedLyrics))
}) })
@ -332,7 +362,7 @@ var _ = Describe("Lyrics", func() {
mockLoader.lyrics = unsyncedLyrics mockLoader.lyrics = unsyncedLyrics
svc := lyrics.NewLyrics(nil, mockLoader) svc := lyrics.NewLyrics(nil, mockLoader)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(embeddedLyrics)) // embedded wins Expect(list).To(Equal(embeddedLyrics)) // embedded wins
}) })
@ -341,7 +371,7 @@ var _ = Describe("Lyrics", func() {
mockLoader.notFound = true mockLoader.notFound = true
svc := lyrics.NewLyrics(nil, mockLoader) svc := lyrics.NewLyrics(nil, mockLoader)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(embeddedLyrics)) // falls through to embedded Expect(list).To(Equal(embeddedLyrics)) // falls through to embedded
}) })
@ -351,16 +381,16 @@ var _ = Describe("Lyrics", func() {
mockLoader.lyrics = unsyncedLyrics mockLoader.lyrics = unsyncedLyrics
svc := lyrics.NewLyrics(nil, mockLoader) svc := lyrics.NewLyrics(nil, mockLoader)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(unsyncedLyrics)) Expect(list).To(Equal(unsyncedLyrics))
}) })
It("should handle plugin error gracefully", func() { It("should handle plugin error gracefully", func() {
conf.Update(func(c *conf.Options) { c.LyricsPriority = "test-lyrics-plugin,embedded" }) conf.Update(func(c *conf.Options) { c.LyricsPriority = "test-lyrics-plugin,embedded" })
mockLoader.err = fmt.Errorf("plugin error") mockLoader.err = errors.New("plugin error")
svc := lyrics.NewLyrics(nil, mockLoader) svc := lyrics.NewLyrics(nil, mockLoader)
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(embeddedLyrics)) // falls through to embedded Expect(list).To(Equal(embeddedLyrics)) // falls through to embedded
}) })
}) })
@ -397,7 +427,7 @@ var _ = Describe("Lyrics", func() {
}) })
It("caches a plugin error as a miss, since some plugins report no lyrics as an error", func() { It("caches a plugin error as a miss, since some plugins report no lyrics as an error", func() {
mockLoader.err = fmt.Errorf("no lyrics found from any provider") mockLoader.err = errors.New("no lyrics found from any provider")
for range 2 { for range 2 {
list, err := svc.GetLyrics(ctx, &mf) list, err := svc.GetLyrics(ctx, &mf)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -438,26 +468,45 @@ var _ = Describe("Lyrics", func() {
var _ = Describe("GetLyricsByArtistTitle", func() { var _ = Describe("GetLyricsByArtistTitle", func() {
var svc lyrics.Lyrics var svc lyrics.Lyrics
var repo *tests.MockMediaFileRepo var ds model.DataStore
var ds *tests.MockDataStore
BeforeEach(func() { BeforeEach(func() {
conf.Update(func(c *conf.Options) { c.LyricsPriority = "embedded" }) conf.Update(func(c *conf.Options) { c.LyricsPriority = "embedded" })
repo = &tests.MockMediaFileRepo{} ds = persistence.New(db.Db())
ds = &tests.MockDataStore{MockedMediaFile: repo}
svc = lyrics.NewLyrics(ds, nil) svc = lyrics.NewLyrics(ds, nil)
}) })
It("bounds the query to a duplicate window", func() { It("bounds the query to a duplicate window", func() {
repo.SetData(model.MediaFiles{}) conf.Update(func(c *conf.Options) { c.LyricsPriority = ".lrc" })
_, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up") useRepoRootAsLibrary(ctx, ds)
var decoys []string
for i := range 10 {
decoys = append(decoys, putRickAstleySong(ctx, ds, fmt.Sprintf("missing/%02d.mp3", i), ""))
}
withSidecar := putRickAstleySong(ctx, ds, "tests/fixtures/test.mp3", "")
_, err := db.Db().Exec("UPDATE media_file SET updated_at = ? WHERE id = ?", time.Now().Add(-time.Hour), withSidecar)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(repo.Options.Max).To(Equal(10))
list, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up")
Expect(err).ToNot(HaveOccurred())
Expect(list).To(BeNil())
Expect(ds.MediaFile().Delete(ctx, decoys[0])).To(Succeed())
list, err = svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up")
Expect(err).ToNot(HaveOccurred())
Expect(list).To(Equal(syncedLyrics))
}) })
It("returns nil when no media file matches", func() { It("returns nil when no media file matches", func() {
repo.SetData(model.MediaFiles{}) lyricsJSON, err := json.Marshal(embeddedLyrics)
list, err := svc.GetLyricsByArtistTitle(ctx, "Nobody", "No Song") Expect(err).ToNot(HaveOccurred())
putRickAstleySong(ctx, ds, "song.mp3", string(lyricsJSON))
list, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "No Song")
Expect(err).ToNot(HaveOccurred())
Expect(list).To(BeNil())
list, err = svc.GetLyricsByArtistTitle(ctx, "Nobody", "Never Gonna Give You Up")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(list).To(BeNil()) Expect(list).To(BeNil())
}) })
@ -468,9 +517,7 @@ var _ = Describe("Lyrics", func() {
embedded, _ := embeddedList.Main() embedded, _ := embeddedList.Main()
embeddedJSON, err := json.Marshal(model.LyricList{embedded}) embeddedJSON, err := json.Marshal(model.LyricList{embedded})
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
repo.SetData(model.MediaFiles{ putRickAstleySong(ctx, ds, "song.mp3", string(embeddedJSON))
{ID: "1", Title: "Never Gonna Give You Up", Lyrics: string(embeddedJSON)},
})
list, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up") list, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -480,6 +527,30 @@ var _ = Describe("Lyrics", func() {
}) })
}) })
func useRepoRootAsLibrary(ctx context.Context, ds model.DataStore) {
GinkgoHelper()
root, err := os.Getwd()
Expect(err).ToNot(HaveOccurred())
persistencetest.SetLibraries(ctx, ds, root)
}
// putRickAstleySong stores "Never Gonna Give You Up" by Rick Astley at path and returns its ID.
func putRickAstleySong(ctx context.Context, ds model.DataStore, path, lyrics string) string {
GinkgoHelper()
artist := model.Artist{ID: "ar-rick", Name: "Rick Astley"}
Expect(ds.Artist().Put(ctx, &artist)).To(Succeed())
mf := &model.MediaFile{
LibraryID: model.DefaultLibraryID,
Path: path,
Title: "Never Gonna Give You Up",
Lyrics: lyrics,
UpdatedAt: time.Now(),
Participants: model.Participants{model.RoleArtist: {{Artist: artist}}},
}
Expect(ds.MediaFile().Put(ctx, mf)).To(Succeed())
return mf.ID
}
type mockPluginLoader struct { type mockPluginLoader struct {
lyrics model.LyricList lyrics model.LyricList
err error err error

View file

@ -13,6 +13,7 @@ import (
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils/ioutils" "github.com/navidrome/navidrome/utils/ioutils"
"golang.org/x/text/unicode/norm"
) )
func fromEmbedded(ctx context.Context, mf *model.MediaFile) (model.LyricList, error) { func fromEmbedded(ctx context.Context, mf *model.MediaFile) (model.LyricList, error) {
@ -40,7 +41,7 @@ func fromExternalFile(ctx context.Context, mf *model.MediaFile, suffix string) (
return nil, fmt.Errorf("opening library filesystem: %w", err) return nil, fmt.Errorf("opening library filesystem: %w", err)
} }
f, err := fsys.Open(sidecarRelPath) f, openedPath, err := openSidecar(fsys, sidecarRelPath)
if errors.Is(err, fs.ErrNotExist) { if errors.Is(err, fs.ErrNotExist) {
log.Trace(ctx, "no lyrics found at path") log.Trace(ctx, "no lyrics found at path")
return nil, nil return nil, nil
@ -48,6 +49,8 @@ func fromExternalFile(ctx context.Context, mf *model.MediaFile, suffix string) (
return nil, err return nil, err
} }
defer f.Close() defer f.Close()
// Log the name that is really on disk, so a parse error points at the right file.
ctx = log.NewContext(ctx, "file", openedPath)
contents, err := io.ReadAll(ioutils.UTF8Reader(f)) contents, err := io.ReadAll(ioutils.UTF8Reader(f))
if err != nil { if err != nil {
@ -69,6 +72,30 @@ func fromExternalFile(ctx context.Context, mf *model.MediaFile, suffix string) (
return list, nil return list, nil
} }
// openSidecar opens the sidecar lyrics file and returns the path it opened. When the
// exact path is missing, it retries with the NFD and NFC forms of the file name: the
// sidecar can be in another Unicode form than the stored track path (macOS often
// writes NFD, Linux and Windows keep NFC). The folders are kept as stored, because
// the scanner read them from disk.
func openSidecar(fsys fs.FS, relPath string) (fs.File, string, error) {
f, err := fsys.Open(relPath)
if !errors.Is(err, fs.ErrNotExist) {
return f, relPath, err
}
dir, base := path.Split(relPath)
for _, form := range []norm.Form{norm.NFD, norm.NFC} {
altPath := dir + form.String(base)
if altPath == relPath {
continue
}
if altFile, altErr := fsys.Open(altPath); !errors.Is(altErr, fs.ErrNotExist) {
return altFile, altPath, altErr
}
}
return f, relPath, err
}
// fromPlugin attempts to load lyrics from a plugin with the given name. Results are cached, // fromPlugin attempts to load lyrics from a plugin with the given name. Results are cached,
// misses included: clients ask for every track in a queue, and plugin lookups are slow. // misses included: clients ask for every track in a queue, and plugin lookups are slow.
func (l *lyricsService) fromPlugin(ctx context.Context, mf *model.MediaFile, pluginName string) (model.LyricList, error) { func (l *lyricsService) fromPlugin(ctx context.Context, mf *model.MediaFile, pluginName string) (model.LyricList, error) {

View file

@ -4,10 +4,17 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"path/filepath" "path/filepath"
"testing/fstest"
"time"
"github.com/navidrome/navidrome/core/storage/storagetest"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/test"
"golang.org/x/text/unicode/norm"
) )
var _ = Describe("sources", func() { var _ = Describe("sources", func() {
@ -22,8 +29,8 @@ var _ = Describe("sources", func() {
mf := model.MediaFile{} mf := model.MediaFile{}
lyrics, err := fromEmbedded(ctx, &mf) lyrics, err := fromEmbedded(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(0)) Expect(lyrics).To(BeEmpty())
}) })
It("should return lyrics for a media file with well-formatted lyrics", func() { It("should return lyrics for a media file with well-formatted lyrics", func() {
@ -45,7 +52,7 @@ var _ = Describe("sources", func() {
} }
lyrics, err := fromEmbedded(ctx, &mf) lyrics, err := fromEmbedded(ctx, &mf)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).ToNot(BeNil()) Expect(lyrics).ToNot(BeNil())
Expect(lyrics).To(Equal(expectedList)) Expect(lyrics).To(Equal(expectedList))
}) })
@ -54,8 +61,8 @@ var _ = Describe("sources", func() {
mf := model.MediaFile{Lyrics: "["} mf := model.MediaFile{Lyrics: "["}
lyrics, err := fromEmbedded(ctx, &mf) lyrics, err := fromEmbedded(ctx, &mf)
Expect(lyrics).To(HaveLen(0)) Expect(lyrics).To(BeEmpty())
Expect(err).ToNot(BeNil()) Expect(err).To(HaveOccurred())
}) })
}) })
@ -76,8 +83,8 @@ var _ = Describe("sources", func() {
It("should return nil for lyrics that don't exist", func() { It("should return nil for lyrics that don't exist", func() {
lyrics, err := fromExternalFile(ctx, mf("01 Invisible (RED) Edit Version.mp3"), ".lrc") lyrics, err := fromExternalFile(ctx, mf("01 Invisible (RED) Edit Version.mp3"), ".lrc")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(0)) Expect(lyrics).To(BeEmpty())
}) })
// fromExternalFile delegates format parsing to model.ParseLyrics; the // fromExternalFile delegates format parsing to model.ParseLyrics; the
@ -87,7 +94,7 @@ var _ = Describe("sources", func() {
func(name, suffix string, expectSynced bool) { func(name, suffix string, expectSynced bool) {
lyrics, err := fromExternalFile(ctx, mf(name), suffix) lyrics, err := fromExternalFile(ctx, mf(name), suffix)
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).ToNot(BeEmpty()) Expect(lyrics).ToNot(BeEmpty())
Expect(lyrics[0].Line).ToNot(BeEmpty()) Expect(lyrics[0].Line).ToNot(BeEmpty())
Expect(lyrics[0].Synced).To(Equal(expectSynced)) Expect(lyrics[0].Synced).To(Equal(expectSynced))
@ -103,7 +110,7 @@ var _ = Describe("sources", func() {
It("should handle LRC files with UTF-8 BOM marker (issue #4631)", func() { It("should handle LRC files with UTF-8 BOM marker (issue #4631)", func() {
lyrics, err := fromExternalFile(ctx, mf("bom-test.mp3"), ".lrc") lyrics, err := fromExternalFile(ctx, mf("bom-test.mp3"), ".lrc")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(1)) Expect(lyrics).To(HaveLen(1))
Expect(lyrics[0].Synced).To(BeTrue(), "Lyrics with BOM marker should be recognized as synced") Expect(lyrics[0].Synced).To(BeTrue(), "Lyrics with BOM marker should be recognized as synced")
Expect(lyrics[0].Line).To(HaveLen(1)) Expect(lyrics[0].Line).To(HaveLen(1))
@ -114,7 +121,7 @@ var _ = Describe("sources", func() {
It("should handle UTF-16 LE encoded LRC files", func() { It("should handle UTF-16 LE encoded LRC files", func() {
lyrics, err := fromExternalFile(ctx, mf("bom-utf16-test.mp3"), ".lrc") lyrics, err := fromExternalFile(ctx, mf("bom-utf16-test.mp3"), ".lrc")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(1)) Expect(lyrics).To(HaveLen(1))
Expect(lyrics[0].Synced).To(BeTrue(), "UTF-16 encoded lyrics should be recognized as synced") Expect(lyrics[0].Synced).To(BeTrue(), "UTF-16 encoded lyrics should be recognized as synced")
Expect(lyrics[0].Line).To(HaveLen(2)) Expect(lyrics[0].Line).To(HaveLen(2))
@ -127,7 +134,7 @@ var _ = Describe("sources", func() {
It("should handle TTML files with UTF-8 BOM marker", func() { It("should handle TTML files with UTF-8 BOM marker", func() {
lyrics, err := fromExternalFile(ctx, mf("bom-test.mp3"), ".ttml") lyrics, err := fromExternalFile(ctx, mf("bom-test.mp3"), ".ttml")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(1)) Expect(lyrics).To(HaveLen(1))
Expect(lyrics[0].Kind).To(Equal("main")) Expect(lyrics[0].Kind).To(Equal("main"))
Expect(lyrics[0].Synced).To(BeTrue()) Expect(lyrics[0].Synced).To(BeTrue())
@ -139,7 +146,7 @@ var _ = Describe("sources", func() {
It("should handle UTF-16 BE encoded TTML files", func() { It("should handle UTF-16 BE encoded TTML files", func() {
lyrics, err := fromExternalFile(ctx, mf("bom-utf16-test.mp3"), ".ttml") lyrics, err := fromExternalFile(ctx, mf("bom-utf16-test.mp3"), ".ttml")
Expect(err).To(BeNil()) Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(1)) Expect(lyrics).To(HaveLen(1))
Expect(lyrics[0].Kind).To(Equal("main")) Expect(lyrics[0].Kind).To(Equal("main"))
Expect(lyrics[0].Synced).To(BeTrue()) Expect(lyrics[0].Synced).To(BeTrue())
@ -150,4 +157,77 @@ var _ = Describe("sources", func() {
Expect(lyrics[0].Line[1].Value).To(Equal("UTF16 line two")) Expect(lyrics[0].Line[1].Value).To(Equal("UTF16 line two"))
}) })
}) })
// The sidecar's file name can be in another Unicode form than the track's. See openSidecar.
Describe("fromExternalFile with mismatched Unicode normalization", func() {
const scheme = "fake-lyrics-norm"
// "ガ" (katakana KA plus a dakuten) has distinct NFC and NFD forms.
const base = "03. 鬱P feat. 初音ミク - ガ"
const dir = "ビートルズ/Beyoncé/"
var fsys *storagetest.FakeFS
BeforeEach(func() {
fsys = &storagetest.FakeFS{}
storagetest.Register(scheme, fsys)
})
// lyricsFor stores the track and its sidecar under dir (kept byte-for-byte,
// as the scanner reads it from disk) with the file names in the given forms.
lyricsFor := func(dir string, trackForm, sidecarForm norm.Form) (model.LyricList, error) {
trackBase := dir + trackForm.String(base)
sidecarBase := dir + sidecarForm.String(base)
Expect(trackBase).ToNot(Equal(sidecarBase))
// A non-zero ModTime is required so the FakeFS directory-timestamp
// bookkeeping settles instead of looping.
modTime := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
fsys.SetFiles(fstest.MapFS{
trackBase + ".flac": &fstest.MapFile{Data: []byte("audio"), ModTime: modTime},
sidecarBase + ".lrc": &fstest.MapFile{Data: []byte("[00:18.80]We're no strangers to love"), ModTime: modTime},
})
mf := &model.MediaFile{LibraryPath: scheme + ":///music", Path: trackBase + ".flac"}
return fromExternalFile(ctx, mf, ".lrc")
}
// Only the sidecar's file name can differ in form: the folders come from the
// scanner, so they are correct as stored and must not be re-normalized.
DescribeTable("finds a sidecar stored in the other normalization form",
func(dir string, trackForm, sidecarForm norm.Form) {
lyrics, err := lyricsFor(dir, trackForm, sidecarForm)
Expect(err).ToNot(HaveOccurred())
Expect(lyrics).To(HaveLen(1))
Expect(lyrics[0].Synced).To(BeTrue())
},
Entry("no folder, NFC track, NFD sidecar", "", norm.NFC, norm.NFD),
Entry("no folder, NFD track, NFC sidecar", "", norm.NFD, norm.NFC),
Entry("NFC folder, NFC track, NFD sidecar", norm.NFC.String(dir), norm.NFC, norm.NFD),
Entry("NFC folder, NFD track, NFC sidecar", norm.NFC.String(dir), norm.NFD, norm.NFC),
Entry("NFD folder, NFD track, NFC sidecar", norm.NFD.String(dir), norm.NFD, norm.NFC),
Entry("NFD folder, NFC track, NFD sidecar", norm.NFD.String(dir), norm.NFC, norm.NFD),
)
It("logs the sidecar path that is really on disk", func() {
l, hook := test.NewNullLogger()
prevLevel := log.CurrentLevel()
// Swap the logger before raising the level, so Trace entries reach the hook.
prevLogger := log.SetDefaultLogger(l)
log.SetLevel(log.LevelTrace)
DeferCleanup(func() {
log.SetDefaultLogger(prevLogger)
log.SetLevel(prevLevel)
})
_, err := lyricsFor("", norm.NFC, norm.NFD)
Expect(err).ToNot(HaveOccurred())
entry := hook.LastEntry()
Expect(entry).ToNot(BeNil())
Expect(entry.Level).To(Equal(logrus.TraceLevel))
Expect(entry.Message).To(Equal("retrieved lyrics from external file"))
Expect(entry.Data).To(HaveKeyWithValue("file", norm.NFD.String(base)+".lrc"))
})
})
}) })

View file

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

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