mirror of
https://github.com/navidrome/navidrome.git
synced 2026-11-20 09:08:50 +01:00
Compare commits
183 commits
pglite-spi
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ced5acbb3b |
||
|
|
8eb2131e7b |
||
|
|
bc8e5df565 |
||
|
|
90ae2b6640 |
||
|
|
a0c0992b4a |
||
|
|
ba717b7130 |
||
|
|
6789f278c4 |
||
|
|
ebdf2dc693 |
||
|
|
2f85c631bf |
||
|
|
a40f7b870f |
||
|
|
3a9e88a0dd |
||
|
|
798305ef09 |
||
|
|
110567aaca |
||
|
|
1286fdfc9c |
||
|
|
3fca50b808 |
||
|
|
986000db44 |
||
|
|
e9c0efa446 |
||
|
|
232a598e75 |
||
|
|
f3e520d380 |
||
|
|
644ecf88ee |
||
|
|
35948d566d |
||
|
|
9b959c5404 |
||
|
|
2ae6defbc4 |
||
|
|
1f0238ce4b |
||
|
|
a4be9224db |
||
|
|
a8872b413b |
||
|
|
2e7e24a023 |
||
|
|
3679b6215d |
||
|
|
a6f3b91f87 |
||
|
|
dfe90ba384 |
||
|
|
69377527bc |
||
|
|
97df50888e |
||
|
|
84af2760ce |
||
|
|
01e4ef3e3b |
||
|
|
690a234388 |
||
|
|
a21d5b020a |
||
|
|
7bea40a25f |
||
|
|
2ce7ef53ca |
||
|
|
88adc02f74 |
||
|
|
3a40f29aa5 |
||
|
|
55e52b7ce4 |
||
|
|
6177c92e32 |
||
|
|
4ee78867c9 |
||
|
|
94a6e59fee |
||
|
|
a7f19c7c7a |
||
|
|
ff58ca5d1f |
||
|
|
2fecb718c0 | ||
|
|
514207faf1 |
||
|
|
d22a31aee0 |
||
|
|
1efd5c467b |
||
|
|
64cf86fae9 |
||
|
|
27d041486c |
||
|
|
9f0441352c |
||
|
|
ecbd4b7d55 |
||
|
|
818603436c |
||
|
|
93cead9b16 |
||
|
|
e40d54fd40 |
||
|
|
93e01f390e |
||
|
|
f5b6805b31 |
||
|
|
97ae17cab3 | ||
|
|
a4f75cf6c4 |
||
|
|
6a38dc988b |
||
|
|
7c1e68a1e4 |
||
|
|
755da3ea59 |
||
|
|
c9c70c952b |
||
|
|
563c5c72a1 |
||
|
|
2a57570e90 |
||
|
|
ec2e0a9ea9 |
||
|
|
56cc32aede |
||
|
|
df77c462e8 |
||
|
|
a45adbbb2e |
||
|
|
be201a2d79 |
||
|
|
30663f7d4f |
||
|
|
8e306b1f61 |
||
|
|
4ae97ab59e |
||
|
|
803b2da8ee | ||
|
|
74e96a2bb7 | ||
|
|
497dfe2586 |
||
|
|
b70ba3a49e | ||
|
|
d5a2e1e813 | ||
|
|
b4d2c3e4af | ||
|
|
22ce85e5d5 | ||
|
|
aea60c6e99 | ||
|
|
b78c963931 |
||
|
|
52135913d4 |
||
|
|
caa2f8a0c0 |
||
|
|
95f67d2c4e |
||
|
|
758e64c999 |
||
|
|
0e1893530b |
||
|
|
e03ce87177 |
||
|
|
3a31f702b5 |
||
|
|
a62d1629f0 |
||
|
|
612c8290f9 |
||
|
|
ab5869123d |
||
|
|
4cdffd5633 |
||
|
|
ce484083bf |
||
|
|
46c432719f |
||
|
|
c22ce9ebb2 |
||
|
|
bb7d81a5ea |
||
|
|
4113d954ca |
||
|
|
6b05189190 | ||
|
|
b293b96256 |
||
|
|
83fff44c82 |
||
|
|
659d067aba |
||
|
|
336fa482f8 |
||
|
|
3f89baaec8 |
||
|
|
a0c4160376 | ||
|
|
69b496383d |
||
|
|
101145742f |
||
|
|
ee6dd1bc03 |
||
|
|
27483a46dc |
||
|
|
39028f65c8 |
||
|
|
a3f41fb422 |
||
|
|
961ee8c413 |
||
|
|
9e3deb4330 | ||
|
|
285dc4f391 |
||
|
|
cb7b042e36 |
||
|
|
07c756db3c |
||
|
|
00bb120288 |
||
|
|
6b3938b5b6 | ||
|
|
c3b9b4ecb3 |
||
|
|
cabfd16f9f |
||
|
|
9e8811e4c5 |
||
|
|
237276efcd |
||
|
|
0429fb3d40 |
||
|
|
8b4125267e |
||
|
|
8e784b6af7 |
||
|
|
a5334ee46b |
||
|
|
2913c13cdf |
||
|
|
49f626c00a |
||
|
|
672c0af580 | ||
|
|
fb45ad7b9c |
||
|
|
b76ae14286 |
||
|
|
be8ec15168 |
||
|
|
fed35e08de |
||
|
|
549dfa7f30 |
||
|
|
16567f147b |
||
|
|
ded4f47d93 |
||
|
|
5bd14da65c | ||
|
|
decac50f60 |
||
|
|
18205366c8 |
||
|
|
97270d44e1 |
||
|
|
3f4b6a642c |
||
|
|
dd71f1c57f | ||
|
|
d00c84716b | ||
|
|
1072e9f7eb |
||
|
|
276d767ce5 |
||
|
|
1a8463f7de |
||
|
|
4168377b65 |
||
|
|
2d09ebc676 |
||
|
|
c6732e1fdf |
||
|
|
2802c05a66 |
||
|
|
d9d38f842a |
||
|
|
d0d5403708 |
||
|
|
9e950cb63d |
||
|
|
2dc0983629 |
||
|
|
2aa7a5c466 |
||
|
|
4067e36a06 |
||
|
|
964d3c778b | ||
|
|
c14b598a01 |
||
|
|
25e7b5b20d |
||
|
|
bb386b13bf |
||
|
|
08eb46c8ad |
||
|
|
055fbde3cf | ||
|
|
72975a95fb |
||
|
|
e7b449b805 |
||
|
|
8d77a49b31 | ||
|
|
02c9816aec |
||
|
|
fe1c87c190 |
||
|
|
043de7a86c |
||
|
|
bea9715001 | ||
|
|
89026012ab | ||
|
|
404837799b | ||
|
|
48af781b82 | ||
|
|
1ceb25c6c1 |
||
|
|
97e1f73cc8 |
||
|
|
9198bde34a |
||
|
|
8a2135f076 |
||
|
|
8568010524 | ||
|
|
072331078d | ||
|
|
c534aedd0c |
||
|
|
546302576a |
||
|
|
330da83eff |
933 changed files with 37044 additions and 15531 deletions
100
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
100
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
|
|
@ -1,98 +1,74 @@
|
||||||
name: Bug Report
|
name: Bug report
|
||||||
description: Before opening a new issue, please search to see if an issue already exists for the bug you encountered.
|
description: Report something that is not working as expected. You do not need to know the cause or how to fix it.
|
||||||
title: "[Bug]: "
|
title: "[Bug]: "
|
||||||
labels: ["bug", "triage"]
|
labels: ["triage"]
|
||||||
#assignees:
|
#assignees:
|
||||||
# - deluan
|
# - deluan
|
||||||
body:
|
body:
|
||||||
- type: markdown
|
- type: markdown
|
||||||
attributes:
|
attributes:
|
||||||
value: |
|
value: |
|
||||||
### Thanks for taking the time to fill out this bug report!
|
Thanks for reporting a problem. For a possible security vulnerability, use [private reporting](https://github.com/navidrome/navidrome/security/advisories/new).
|
||||||
- type: checkboxes
|
- type: checkboxes
|
||||||
id: requirements
|
id: requirements
|
||||||
attributes:
|
attributes:
|
||||||
label: "I confirm that:"
|
label: "I confirm that:"
|
||||||
options:
|
options:
|
||||||
- label: I have searched the existing [open AND closed issues](https://github.com/navidrome/navidrome/issues?q=is%3Aissue) to see if an issue already exists for the bug I've encountered
|
- label: I have searched the existing [open and closed issues](https://github.com/navidrome/navidrome/issues?q=is%3Aissue) and found no matching open report.
|
||||||
|
required: true
|
||||||
|
- label: I'm using the latest Navidrome release and can reproduce the issue on it.
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: what-happened
|
||||||
|
attributes:
|
||||||
|
label: What happened
|
||||||
|
description: Describe what you observed and how it affected you. Include any error message you saw. You do not need to diagnose the cause or suggest code changes. If a closed issue matches, link it here.
|
||||||
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- label: I'm using the latest version (your issue may have been fixed already)
|
|
||||||
required: false
|
|
||||||
- type: input
|
- type: input
|
||||||
id: version
|
id: version
|
||||||
attributes:
|
attributes:
|
||||||
label: Version
|
label: Navidrome version
|
||||||
description: What version of Navidrome are you running? (please try upgrading first, as your issue may have been fixed already).
|
description: Which Navidrome version or build are you using? If you cannot find it, enter 'not sure'. If you tried another version, mention whether the behavior changed.
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: textarea
|
- type: textarea
|
||||||
|
id: expected
|
||||||
attributes:
|
attributes:
|
||||||
label: Current Behavior
|
label: Expected behavior and why
|
||||||
description: A concise description of what you're experiencing.
|
description: What did you expect, and why? If available, link documentation, an applicable API contract, or a previously working version. A personal expectation is useful context too; it does not by itself establish that the product should change. If you are unsure, say so.
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: false
|
||||||
- type: textarea
|
- type: textarea
|
||||||
|
id: steps
|
||||||
attributes:
|
attributes:
|
||||||
label: Expected Behavior
|
label: Steps to reproduce
|
||||||
description: A concise description of what you expected to happen.
|
description: List the steps, relevant settings, and how often the problem occurs. If it happens only sometimes, describe what was happening when you noticed it and what you have already tried.
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Steps To Reproduce
|
|
||||||
description: Steps to reproduce the behavior.
|
|
||||||
placeholder: |
|
|
||||||
1. In this scenario...
|
|
||||||
2. With this config...
|
|
||||||
3. Click (or Execute) '...'
|
|
||||||
4. See error...
|
|
||||||
validations:
|
validations:
|
||||||
required: false
|
required: false
|
||||||
- type: textarea
|
- type: textarea
|
||||||
id: env
|
id: env
|
||||||
attributes:
|
attributes:
|
||||||
label: Environment
|
label: Relevant environment
|
||||||
description: |
|
description: >-
|
||||||
examples:
|
Include only details relevant to this problem: server operating system, installation method, and the browser or client app with its version, if involved. Leave out details you do not know. Examples of installation methods: Docker, downloaded binary, package, or source build.
|
||||||
- **OS**: Ubuntu 20.04
|
|
||||||
- **Browser**: Chrome 110.0.5481.177 on Windows 11
|
|
||||||
- **Client**: DSub 5.5.1
|
|
||||||
value: |
|
|
||||||
- OS:
|
|
||||||
- Browser:
|
|
||||||
- Client:
|
|
||||||
render: markdown
|
|
||||||
- type: dropdown
|
|
||||||
id: distribution
|
|
||||||
attributes:
|
|
||||||
label: How Navidrome is installed?
|
|
||||||
multiple: false
|
|
||||||
options:
|
|
||||||
- Docker
|
|
||||||
- Binary (from downloads page)
|
|
||||||
- Package
|
|
||||||
- Built from sources
|
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: false
|
||||||
- type: textarea
|
- type: textarea
|
||||||
id: config
|
id: config-logs
|
||||||
attributes:
|
attributes:
|
||||||
label: Configuration
|
label: Relevant configuration and logs
|
||||||
description: Please copy and paste your `navidrome.toml` (and/or `docker-compose.yml`) configuration. This will be automatically formatted into code, so no need for backticks.
|
description: >-
|
||||||
render: toml
|
Paste only the configuration settings or log excerpt related to this problem. Remove passwords, tokens, API keys, session cookies, private URLs, and identifying information before submitting. Debug logs are optional. If you cannot safely share an excerpt, explain what it shows instead. [Log guidance](https://www.navidrome.org/docs/faq/#-where-are-the-logs).
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
- type: textarea
|
- type: textarea
|
||||||
id: logs
|
id: additional-context
|
||||||
attributes:
|
attributes:
|
||||||
label: Relevant log output
|
label: Screenshots or additional context
|
||||||
description: Please copy and paste any relevant log output (change your `LogLevel` (`ND_LOGLEVEL`) to debug). This will be automatically formatted into code, so no need for backticks. ([Where I can find the logs?](https://www.navidrome.org/docs/faq/#where-are-the-logs))
|
description: Add screenshots, recordings, links, or other observations that help explain the problem. Remove private information from attachments as well.
|
||||||
render: shell
|
validations:
|
||||||
- type: textarea
|
required: false
|
||||||
attributes:
|
|
||||||
label: Anything else?
|
|
||||||
description: |
|
|
||||||
Links? References? Anything that will give us more context about the issue you are encountering!
|
|
||||||
|
|
||||||
Tip: You can attach screenshots by clicking this area to highlight it and then dragging files in.
|
|
||||||
- type: checkboxes
|
- type: checkboxes
|
||||||
id: terms
|
id: terms
|
||||||
attributes:
|
attributes:
|
||||||
|
|
|
||||||
6
.github/ISSUE_TEMPLATE/config.yml
vendored
6
.github/ISSUE_TEMPLATE/config.yml
vendored
|
|
@ -1,8 +1,8 @@
|
||||||
blank_issues_enabled: false
|
blank_issues_enabled: false
|
||||||
contact_links:
|
contact_links:
|
||||||
- name: Ideas for new features
|
- name: Ideas and behavior changes
|
||||||
url: https://github.com/navidrome/navidrome/discussions/categories/ideas
|
url: https://github.com/navidrome/navidrome/discussions/categories/ideas
|
||||||
about: This is the place to share and discuss new ideas and potentially new features.
|
about: Describe the problem, intended outcome, and use case before starting an implementation.
|
||||||
- name: Support requests
|
- name: Support requests
|
||||||
url: https://github.com/navidrome/navidrome/discussions/categories/q-a
|
url: https://github.com/navidrome/navidrome/discussions/categories/q-a
|
||||||
about: This is the place to ask questions.
|
about: Ask for help with setup, configuration, or using Navidrome.
|
||||||
|
|
|
||||||
21
.github/pull_request_template.md
vendored
21
.github/pull_request_template.md
vendored
|
|
@ -1,8 +1,13 @@
|
||||||
### Description
|
### Description
|
||||||
<!-- Please provide a clear and concise description of what this PR does and why it is needed. -->
|
<!-- Please provide a clear and concise description of what this PR does and why it is needed. AI tools may help you draft, edit, or translate it, but review the final text and make sure you agree with it. Please be mindful of the maintainer's time. -->
|
||||||
|
|
||||||
|
**AI use** (check one):
|
||||||
|
- [ ] Yes, AI helped generate or modify code or tests, draft substantive PR text, or create this PR
|
||||||
|
- [ ] No
|
||||||
|
<!-- Tool names and prompts are not required. -->
|
||||||
|
|
||||||
### Related Issues
|
### Related Issues
|
||||||
<!-- List any related issues, e.g., "Fixes #123" or "Related to #456". -->
|
<!-- List related issues, such as "Fixes #123" or "Related to #456". When prior agreement is required, link the maintainer's agreement on the intended behavior and scope. Otherwise, explain why agreement is not needed, such as the small-change exception or a translation update. For a larger change, link the agreed design and identify this phase. -->
|
||||||
|
|
||||||
### Type of Change
|
### Type of Change
|
||||||
- [ ] Bug fix
|
- [ ] Bug fix
|
||||||
|
|
@ -12,27 +17,29 @@
|
||||||
- [ ] Other (please describe):
|
- [ ] Other (please describe):
|
||||||
|
|
||||||
### Checklist
|
### Checklist
|
||||||
Please review and check all that apply:
|
Please review and check all that apply. Leave unverified items unchecked and explain them under How to Test.
|
||||||
|
|
||||||
- [ ] My code follows the project’s coding style
|
- [ ] My code follows the project’s coding style
|
||||||
- [ ] I have tested the changes locally
|
- [ ] I have tested the changes locally
|
||||||
- [ ] I have added or updated documentation as needed
|
- [ ] I have added or updated documentation as needed
|
||||||
- [ ] I have added tests that prove my fix/feature works (or explain why not)
|
- [ ] I have added tests that prove my fix/feature works (or explain why not)
|
||||||
- [ ] All existing and new tests pass
|
- [ ] All existing and new tests pass
|
||||||
|
- [ ] I personally read and reviewed the entire diff and relevant code before opening this PR, and have done the same for every subsequent update, if any.
|
||||||
|
- [ ] For code changes, I have the development knowledge to understand, test, and maintain the implementation, assess its security and performance implications, and answer review questions.
|
||||||
|
|
||||||
### How to Test
|
### How to Test
|
||||||
<!-- Describe the steps to test your changes. Include setup, commands, and expected results. -->
|
<!-- Describe the steps to test your changes. Include setup, commands actually run, and results actually observed before and after the change. State how you personally checked the affected functionality. List failed or unrun checks, untested cases, and limitations. -->
|
||||||
|
|
||||||
### Screenshots / Demos (if applicable)
|
### Screenshots / Demos (if applicable)
|
||||||
<!-- Add screenshots, GIFs, or links to demos if your change includes UI updates or visual changes. -->
|
<!-- Add screenshots, GIFs, or links to demos if your change includes UI updates or visual changes. -->
|
||||||
|
|
||||||
### Additional Notes
|
### Additional Notes
|
||||||
<!-- Anything else the maintainer should know? Potential side effects, breaking changes, or areas of concern? -->
|
<!-- Anything else the maintainer should know? Potential side effects, breaking changes, or areas of concern? Where relevant, explain important tradeoffs, new dependencies or ongoing maintenance costs, and simpler alternatives considered. -->
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
**Tips for Contributors:**
|
**Tips for Contributors:**
|
||||||
- Be concise but thorough.
|
- Be concise but thorough.
|
||||||
- If your PR is large, consider breaking it into smaller PRs.
|
- If your PR is large, consider breaking it into smaller PRs within the agreed design and scope.
|
||||||
- Tag the maintainer if you need a prompt review.
|
- Review timing depends on maintainer availability; please do not tag the maintainer for faster review.
|
||||||
- Avoid force pushing to the branch after opening the PR, as it can complicate the review process.
|
- Avoid force pushing to the branch after opening the PR, as it can complicate the review process.
|
||||||
-->
|
-->
|
||||||
48
.github/workflows/check-new-nolint.sh
vendored
Executable file
48
.github/workflows/check-new-nolint.sh
vendored
Executable file
|
|
@ -0,0 +1,48 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# Fails when a PR adds a //nolint directive to a Go file; a directive kept on an edited line is not new.
|
||||||
|
# Compares HEAD against $BASE_REF (default origin/master) and needs full history (fetch-depth: 0 in CI).
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
BASE_REF="${BASE_REF:-origin/master}"
|
||||||
|
|
||||||
|
git diff --unified=0 --no-color "$BASE_REF"...HEAD -- '*.go' | awk '
|
||||||
|
function directives(s, out) {
|
||||||
|
out = ""
|
||||||
|
while (match(s, /\/\/nolint(:[A-Za-z0-9_,-]+)?/)) {
|
||||||
|
out = out " " substr(s, RSTART, RLENGTH)
|
||||||
|
s = substr(s, RSTART + RLENGTH)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
/^diff --git / { header = 1; next }
|
||||||
|
/^@@/ {
|
||||||
|
split($3, pos, ",")
|
||||||
|
line = substr(pos[1], 2)
|
||||||
|
header = 0
|
||||||
|
delete removed
|
||||||
|
next
|
||||||
|
}
|
||||||
|
header && /^\+\+\+ / { file = substr($0, 7); next }
|
||||||
|
header { next }
|
||||||
|
/^-/ {
|
||||||
|
n = split(directives($0), ds, " ")
|
||||||
|
for (i = 1; i <= n; i++) removed[ds[i]]++
|
||||||
|
next
|
||||||
|
}
|
||||||
|
/^\+/ {
|
||||||
|
n = split(directives($0), ds, " ")
|
||||||
|
for (i = 1; i <= n; i++) {
|
||||||
|
if (removed[ds[i]] > 0) { removed[ds[i]]--; continue }
|
||||||
|
found++
|
||||||
|
printf "%s:%d: new %s directive\n", file, line, ds[i]
|
||||||
|
if (ENVIRON["GITHUB_ACTIONS"] == "true")
|
||||||
|
printf "::error file=%s,line=%d::New %s directive. Fix the lint issue instead. If this is a real exception, a maintainer can add the allow-nolint label.\n", file, line, ds[i]
|
||||||
|
}
|
||||||
|
line++
|
||||||
|
}
|
||||||
|
END {
|
||||||
|
if (found) {
|
||||||
|
printf "\n%d new //nolint directive(s). Fix the lint issues instead; a maintainer can approve real exceptions with the allow-nolint label.\n", found
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
}'
|
||||||
31
.github/workflows/nolint-gate.yml
vendored
Normal file
31
.github/workflows/nolint-gate.yml
vendored
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
name: New nolint gate
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
types: [opened, synchronize, reopened, labeled, unlabeled]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check-new-nolint:
|
||||||
|
name: Check for new //nolint directives
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Allowed by label
|
||||||
|
if: contains(github.event.pull_request.labels.*.name, 'allow-nolint')
|
||||||
|
run: echo "::notice::The allow-nolint label is set, so new //nolint directives are allowed."
|
||||||
|
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
if: "!contains(github.event.pull_request.labels.*.name, 'allow-nolint')"
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Fetch latest base branch
|
||||||
|
if: "!contains(github.event.pull_request.labels.*.name, 'allow-nolint')"
|
||||||
|
run: git fetch --no-tags origin "+refs/heads/${{ github.event.pull_request.base.ref }}:refs/remotes/origin/${{ github.event.pull_request.base.ref }}"
|
||||||
|
|
||||||
|
- name: Fail on new //nolint directives
|
||||||
|
if: "!contains(github.event.pull_request.labels.*.name, 'allow-nolint')"
|
||||||
|
env:
|
||||||
|
BASE_REF: origin/${{ github.event.pull_request.base.ref }}
|
||||||
|
run: ./.github/workflows/check-new-nolint.sh
|
||||||
38
.github/workflows/pipeline.yml
vendored
38
.github/workflows/pipeline.yml
vendored
|
|
@ -79,7 +79,7 @@ jobs:
|
||||||
with:
|
with:
|
||||||
version: ${{ steps.golangci-version.outputs.version }}
|
version: ${{ steps.golangci-version.outputs.version }}
|
||||||
problem-matchers: true
|
problem-matchers: true
|
||||||
args: --timeout 2m
|
args: --timeout 3m
|
||||||
|
|
||||||
- name: Run go goimports
|
- name: Run go goimports
|
||||||
run: go run golang.org/x/tools/cmd/goimports@latest -w `find . -name '*.go' | grep -v '_gen.go$' | grep -v '.pb.go$'`
|
run: go run golang.org/x/tools/cmd/goimports@latest -w `find . -name '*.go' | grep -v '_gen.go$' | grep -v '.pb.go$'`
|
||||||
|
|
@ -92,8 +92,23 @@ jobs:
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
- name: Resolve OpenAPI tool versions
|
||||||
|
id: api-tools
|
||||||
|
run: echo "key=$(grep -E '^(VACUUM|OAPI_CODEGEN|OASDIFF)_VERSION' Makefile | tr -d ' \n')" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Cache OpenAPI tools
|
||||||
|
uses: actions/cache@v6
|
||||||
|
with:
|
||||||
|
path: bin
|
||||||
|
key: api-tools-${{ runner.os }}-${{ steps.api-tools.outputs.key }}
|
||||||
|
|
||||||
|
- name: Lint OpenAPI spec
|
||||||
|
run: make api-lint
|
||||||
|
|
||||||
- name: Run go generate
|
- name: Run go generate
|
||||||
run: go generate ./...
|
run: |
|
||||||
|
make api-gen
|
||||||
|
go generate ./...
|
||||||
- name: Verify no changes from go generate
|
- name: Verify no changes from go generate
|
||||||
run: |
|
run: |
|
||||||
git status --porcelain
|
git status --porcelain
|
||||||
|
|
@ -102,6 +117,12 @@ jobs:
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
- name: Check for breaking OpenAPI changes
|
||||||
|
if: github.event_name == 'pull_request'
|
||||||
|
run: |
|
||||||
|
git fetch --no-tags --depth=1 origin ${{ github.event.pull_request.base.sha }}
|
||||||
|
make api-diff API_DIFF_BASE=${{ github.event.pull_request.base.sha }}
|
||||||
|
|
||||||
validate-migrations:
|
validate-migrations:
|
||||||
name: Validate DB migrations
|
name: Validate DB migrations
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
@ -498,13 +519,18 @@ jobs:
|
||||||
docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.docker.outputs.version }}
|
docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.docker.outputs.version }}
|
||||||
|
|
||||||
push-manifest-dockerhub:
|
push-manifest-dockerhub:
|
||||||
name: Push to Docker Hub
|
name: Push to Docker Hub (${{ matrix.repository }})
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
needs: [build, check-push-enabled]
|
needs: [build, check-push-enabled]
|
||||||
if: needs.check-push-enabled.outputs.is_enabled == 'true' && vars.DOCKER_HUB_REPO != ''
|
if: needs.check-push-enabled.outputs.is_enabled == 'true' && vars.DOCKER_HUB_REPO != ''
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
# Always push to DOCKER_HUB_REPO. The upstream repository also pushes to the navidrome/navidrome org repository.
|
||||||
|
repository: ${{ fromJSON(github.repository == 'navidrome/navidrome' && format('["{0}","navidrome/navidrome"]', vars.DOCKER_HUB_REPO) || format('["{0}"]', vars.DOCKER_HUB_REPO)) }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
|
|
@ -520,7 +546,7 @@ jobs:
|
||||||
id: docker
|
id: docker
|
||||||
with:
|
with:
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
hub_repository: ${{ vars.DOCKER_HUB_REPO }}
|
hub_repository: ${{ matrix.repository }}
|
||||||
hub_username: ${{ secrets.DOCKER_HUB_USERNAME }}
|
hub_username: ${{ secrets.DOCKER_HUB_USERNAME }}
|
||||||
hub_password: ${{ secrets.DOCKER_HUB_PASSWORD }}
|
hub_password: ${{ secrets.DOCKER_HUB_PASSWORD }}
|
||||||
|
|
||||||
|
|
@ -537,7 +563,7 @@ jobs:
|
||||||
|
|
||||||
- name: Inspect image in Docker Hub
|
- name: Inspect image in Docker Hub
|
||||||
run: |
|
run: |
|
||||||
docker buildx imagetools inspect ${{ vars.DOCKER_HUB_REPO }}:${{ steps.docker.outputs.version }}
|
docker buildx imagetools inspect ${{ matrix.repository }}:${{ steps.docker.outputs.version }}
|
||||||
|
|
||||||
cleanup-digests:
|
cleanup-digests:
|
||||||
name: Cleanup digest artifacts
|
name: Cleanup digest artifacts
|
||||||
|
|
@ -549,7 +575,7 @@ jobs:
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ github.token }}
|
GH_TOKEN: ${{ github.token }}
|
||||||
run: |
|
run: |
|
||||||
for artifact in $(gh api repos/${{ github.repository }}/actions/artifacts | jq -r '.artifacts[] | select(.name | startswith("digests-")) | .id'); do
|
for artifact in $(gh api repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts | jq -r '.artifacts[] | select(.name | startswith("digests-")) | .id'); do
|
||||||
gh api --method DELETE repos/${{ github.repository }}/actions/artifacts/$artifact
|
gh api --method DELETE repos/${{ github.repository }}/actions/artifacts/$artifact
|
||||||
done
|
done
|
||||||
|
|
||||||
|
|
|
||||||
160
.golangci.yml
160
.golangci.yml
|
|
@ -9,27 +9,144 @@ linters:
|
||||||
- asciicheck
|
- asciicheck
|
||||||
- bidichk
|
- bidichk
|
||||||
- bodyclose
|
- bodyclose
|
||||||
|
- containedctx
|
||||||
- copyloopvar
|
- copyloopvar
|
||||||
|
- depguard
|
||||||
- dogsled
|
- dogsled
|
||||||
- durationcheck
|
- durationcheck
|
||||||
|
- errchkjson
|
||||||
- errorlint
|
- errorlint
|
||||||
|
- exhaustive
|
||||||
- forbidigo
|
- forbidigo
|
||||||
|
- ginkgolinter
|
||||||
- gocritic
|
- gocritic
|
||||||
- gocyclo
|
- gocyclo
|
||||||
|
- godoclint
|
||||||
- goprintffuncname
|
- goprintffuncname
|
||||||
- gosec
|
- gosec
|
||||||
- misspell
|
- misspell
|
||||||
|
- modernize
|
||||||
- nakedret
|
- nakedret
|
||||||
- nilerr
|
- nilerr
|
||||||
|
- nolintlint
|
||||||
|
- perfsprint
|
||||||
- rowserrcheck
|
- rowserrcheck
|
||||||
- unconvert
|
|
||||||
- whitespace
|
|
||||||
disable:
|
|
||||||
- staticcheck
|
- staticcheck
|
||||||
|
- thelper
|
||||||
|
- unconvert
|
||||||
|
- usestdlibvars
|
||||||
|
- usetesting
|
||||||
|
- whitespace
|
||||||
settings:
|
settings:
|
||||||
|
depguard:
|
||||||
|
rules:
|
||||||
|
api-subsonic:
|
||||||
|
list-mode: lax
|
||||||
|
files:
|
||||||
|
- "**/server/subsonic/**"
|
||||||
|
- "!$test"
|
||||||
|
deny:
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/nativeapi
|
||||||
|
desc: &api_isolation "API packages must not import each other. Move shared code to a neutral package (for example server/filter or core/publicurl)."
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/jellyfin
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/apiv1
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/public
|
||||||
|
desc: *api_isolation
|
||||||
|
api-nativeapi:
|
||||||
|
list-mode: lax
|
||||||
|
files:
|
||||||
|
- "**/server/nativeapi/**"
|
||||||
|
- "!$test"
|
||||||
|
deny:
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/subsonic
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/jellyfin
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/apiv1
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/public
|
||||||
|
desc: *api_isolation
|
||||||
|
api-jellyfin:
|
||||||
|
list-mode: lax
|
||||||
|
files:
|
||||||
|
- "**/server/jellyfin/**"
|
||||||
|
- "!$test"
|
||||||
|
deny:
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/subsonic
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/nativeapi
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/apiv1
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/public
|
||||||
|
desc: *api_isolation
|
||||||
|
api-apiv1:
|
||||||
|
list-mode: lax
|
||||||
|
files:
|
||||||
|
- "**/server/apiv1/**"
|
||||||
|
- "!$test"
|
||||||
|
deny:
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/subsonic
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/nativeapi
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/jellyfin
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/public
|
||||||
|
desc: *api_isolation
|
||||||
|
api-public:
|
||||||
|
list-mode: lax
|
||||||
|
files:
|
||||||
|
- "**/server/public/**"
|
||||||
|
- "!$test"
|
||||||
|
deny:
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/subsonic
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/nativeapi
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/jellyfin
|
||||||
|
desc: *api_isolation
|
||||||
|
- pkg: github.com/navidrome/navidrome/server/apiv1
|
||||||
|
desc: *api_isolation
|
||||||
|
persistence-layer:
|
||||||
|
list-mode: lax
|
||||||
|
files:
|
||||||
|
- "**/persistence/**"
|
||||||
|
- "!$test"
|
||||||
|
deny:
|
||||||
|
- pkg: github.com/navidrome/navidrome/core
|
||||||
|
desc: &persistence_layer "persistence implements the model repositories. Do not depend on business logic or HTTP layers; move the logic to core."
|
||||||
|
- pkg: github.com/navidrome/navidrome/server
|
||||||
|
desc: *persistence_layer
|
||||||
|
- pkg: github.com/navidrome/navidrome/scanner
|
||||||
|
desc: *persistence_layer
|
||||||
|
- pkg: github.com/navidrome/navidrome/plugins
|
||||||
|
desc: *persistence_layer
|
||||||
|
- pkg: github.com/navidrome/navidrome/adapters
|
||||||
|
desc: *persistence_layer
|
||||||
|
- pkg: github.com/navidrome/navidrome/cmd
|
||||||
|
desc: *persistence_layer
|
||||||
errcheck:
|
errcheck:
|
||||||
exclude-functions:
|
exclude-functions:
|
||||||
- (*github.com/zeebo/xxh3.Hasher).Write
|
- (*github.com/zeebo/xxh3.Hasher).Write
|
||||||
|
errchkjson:
|
||||||
|
report-no-exported: true
|
||||||
|
ginkgolinter:
|
||||||
|
forbid-focus-container: true
|
||||||
|
force-expect-to: true
|
||||||
|
force-succeed: true
|
||||||
|
force-tonot: true
|
||||||
|
validate-async-intervals: true
|
||||||
|
godoclint:
|
||||||
|
# a doc comment that names another symbol (left behind by a move or a paste) is a bug
|
||||||
|
default: none
|
||||||
|
enable:
|
||||||
|
- start-with-name
|
||||||
|
options:
|
||||||
|
start-with-name:
|
||||||
|
include-unexported: true
|
||||||
gocritic:
|
gocritic:
|
||||||
disable-all: true
|
disable-all: true
|
||||||
enabled-checks:
|
enabled-checks:
|
||||||
|
|
@ -40,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$'
|
||||||
|
|
@ -48,18 +168,52 @@ linters:
|
||||||
msg: "use tx.QueryContext(ctx, ...) in migrations to propagate context"
|
msg: "use tx.QueryContext(ctx, ...) in migrations to propagate context"
|
||||||
- pattern: 'tx\.QueryRow$'
|
- pattern: 'tx\.QueryRow$'
|
||||||
msg: "use tx.QueryRowContext(ctx, ...) in migrations to propagate context"
|
msg: "use tx.QueryRowContext(ctx, ...) in migrations to propagate context"
|
||||||
|
- pattern: '^context\.(Background|TODO)$'
|
||||||
|
msg: "in tests use the spec's ctx (from GinkgoT().Context()), t.Context() or b.Context()"
|
||||||
|
- pattern: '^panic$'
|
||||||
|
msg: "don't panic: return an error, or Expect(...)/Fail(...) in tests; log.Fatal only for startup failures that must stop the server"
|
||||||
|
nolintlint:
|
||||||
|
require-specific: true
|
||||||
|
allow-unused: false
|
||||||
govet:
|
govet:
|
||||||
enable:
|
enable:
|
||||||
- nilness
|
- nilness
|
||||||
|
staticcheck:
|
||||||
|
dot-import-whitelist:
|
||||||
|
- github.com/Masterminds/squirrel
|
||||||
|
thelper:
|
||||||
|
# Helper() is what fixes failure line numbers; the t/tb/b/f parameter name does not
|
||||||
|
test:
|
||||||
|
name: false
|
||||||
|
benchmark:
|
||||||
|
name: false
|
||||||
|
tb:
|
||||||
|
name: false
|
||||||
|
fuzz:
|
||||||
|
name: false
|
||||||
exclusions:
|
exclusions:
|
||||||
rules:
|
rules:
|
||||||
- linters:
|
- linters:
|
||||||
- gosec
|
- gosec
|
||||||
path: _test\.go
|
path: _test\.go
|
||||||
text: "G703"
|
text: "G703"
|
||||||
|
- path: _test\.go
|
||||||
|
linters:
|
||||||
|
- containedctx
|
||||||
|
# forbidigo rules are scoped by their msg: "in migrations" or "in tests use"
|
||||||
- path-except: 'db/migrations/'
|
- path-except: 'db/migrations/'
|
||||||
linters:
|
linters:
|
||||||
- forbidigo
|
- forbidigo
|
||||||
|
text: "in migrations"
|
||||||
|
- path-except: '(_test\.go|^tests/)'
|
||||||
|
linters:
|
||||||
|
- forbidigo
|
||||||
|
text: "in tests use"
|
||||||
|
# the host must keep reading and writing these deprecated fields for older plugins
|
||||||
|
- path: ^plugins/
|
||||||
|
linters:
|
||||||
|
- staticcheck
|
||||||
|
text: 'SA1019: \(github\.com/navidrome/navidrome/plugins/types\.SongRef\)\.(Artist|ArtistMBID|Duration) is deprecated'
|
||||||
generated: lax
|
generated: lax
|
||||||
presets:
|
presets:
|
||||||
- comments
|
- comments
|
||||||
|
|
|
||||||
111
CONTRIBUTING.md
111
CONTRIBUTING.md
|
|
@ -1,93 +1,66 @@
|
||||||
# Navidrome Contribution Guide
|
# Navidrome Contribution Guide
|
||||||
|
|
||||||
Navidrome is a streaming service which allows you to enjoy your music collection from anywhere. We'd welcome you to contribute to our open source project and make Navidrome even better. There are some basic guidelines which you need to follow if you like to contribute to Navidrome.
|
Navidrome has one maintainer and limited review capacity. We welcome contributions that fit the project and remain practical to maintain. A smaller number of focused, well-understood contributions is more useful than a large volume of code that needs extensive rework.
|
||||||
|
|
||||||
- [Asking Support Questions](#asking-support-questions)
|
## Support and conduct
|
||||||
- [Code of Conduct](#code-of-conduct)
|
|
||||||
- [Issues](#issues)
|
|
||||||
- [Pull Requests](#pull-requests)
|
|
||||||
|
|
||||||
|
Use [Discussions → Q&A](https://github.com/navidrome/navidrome/discussions/categories/q-a) for support. Please follow the [Code of Conduct](CODE_OF_CONDUCT.md).
|
||||||
|
|
||||||
## Asking Support Questions
|
## Issues and ideas
|
||||||
We have an active [discussion forum](https://github.com/navidrome/navidrome/discussions) where users and developers can ask questions. Please don't use the GitHub issue tracker to ask questions.
|
|
||||||
|
|
||||||
## Code of Conduct
|
Anyone may report a suspected bug. Search existing [open and closed issues](https://github.com/navidrome/navidrome/issues?q=is%3Aissue) and [discussions](https://github.com/navidrome/navidrome/discussions), and check the [documentation](https://www.navidrome.org/docs/) and [FAQ](https://www.navidrome.org/docs/faq/) first. Use the [bug report form](https://github.com/navidrome/navidrome/issues/new?template=bug_report.yml) for suspected defects and [Discussions → Ideas](https://github.com/navidrome/navidrome/discussions/categories/ideas) for new features or changes to intended behavior.
|
||||||
Please read the following [Code of Conduct](https://github.com/navidrome/navidrome/blob/master/CODE_OF_CONDUCT.md).
|
|
||||||
|
|
||||||
## Issues
|
Describe what happened, what you expected, and why that expectation should hold. Include reproduction steps where possible, with a reference to documentation, an applicable API contract, or a previously working version. If the problem is intermittent, explain what you observed and tried. Remove credentials and private information from logs and configuration.
|
||||||
Found any issue or bug in our codebase? Have a great idea you want to propose or discuss with
|
|
||||||
the developers? You can help by submitting an [issue](https://github.com/navidrome/navidrome/issues/new/choose)
|
|
||||||
to the GitHub repository.
|
|
||||||
|
|
||||||
**Before opening a new issue, please check if the issue has not been already made by searching
|
A reported problem may involve intended behavior, configuration, or a product decision. An open issue or a label does not establish that a change has been accepted. Report security vulnerabilities [privately through GitHub](https://github.com/navidrome/navidrome/security/advisories/new).
|
||||||
the [issues](https://github.com/navidrome/navidrome/issues)**
|
|
||||||
|
|
||||||
## Pull requests
|
## Agree on the change before implementation
|
||||||
Before submitting a pull request, ensure that you go through the following:
|
|
||||||
- Open a corresponding issue for the Pull Request, if not existing. The issue can be opened following [these guidelines](#issues)
|
|
||||||
- Ensure that there is no open or closed Pull Request corresponding to your submission to avoid duplication of effort.
|
|
||||||
- Setup the [development environment](https://www.navidrome.org/docs/developers/dev-environment/)
|
|
||||||
- Create a new branch on your forked repo and make the changes in it. Naming conventions for branch are: `<Issue Title>/<Issue Number>`. Example:
|
|
||||||
```
|
|
||||||
git checkout -b adding-docs/834 master
|
|
||||||
```
|
|
||||||
- The commits should follow a [specific convention](#commit-conventions)
|
|
||||||
- Ensure that a DCO sign-off for commits is provided via `--signoff` option of git commit
|
|
||||||
- Provide a link to the issue that will be closed via your Pull request.
|
|
||||||
|
|
||||||
### Commit Conventions
|
For code contributions beyond the small exceptions below, explain the problem, intended behavior, and smallest proposed scope in an existing issue or discussion. Wait for an explicit maintainer comment agreeing that the change should be pursued. Keep the discussion in one place. Silence, community support, and previous merged contributions do not replace that agreement.
|
||||||
Each commit message must adhere to the following format:
|
|
||||||
```
|
|
||||||
<type>(scope): <description>
|
|
||||||
|
|
||||||
[optional body]
|
Small documentation corrections and small, unambiguous fixes that restore established behavior may be submitted directly. Provide evidence of the defect. These exceptions do not cover disputed behavior, new product choices, dependencies, or broader refactoring. If the intended behavior is unclear, discuss it first.
|
||||||
```
|
|
||||||
This improves the readability of the messages
|
|
||||||
|
|
||||||
#### Type
|
For large or cross-cutting changes, agree on the design and a sequence of small, reviewable phases before implementation. Explain why the change belongs in the core, what new complexity or dependencies it introduces, and which simpler alternatives you considered. Consider existing configuration, APIs, plugins, or external tools where appropriate. Splitting a change into PRs does not remove the need to agree on the overall design and scope.
|
||||||
It can be one of the following:
|
|
||||||
1. **feat**: Addition of a new feature
|
|
||||||
2. **fix**: Bug fix
|
|
||||||
3. **sec**: Fixing security issues
|
|
||||||
4. **docs**: Documentation Changes
|
|
||||||
5. **style**: Changes to styling
|
|
||||||
6. **refactor**: Refactoring of code
|
|
||||||
7. **perf**: Code that affects performance
|
|
||||||
8. **test**: Updating or improving the current tests
|
|
||||||
9. **build**: Changes to Build process
|
|
||||||
10. **revert**: Reverting to a previous commit
|
|
||||||
11. **chore** : updating grunt tasks etc
|
|
||||||
|
|
||||||
If there is a breaking change in your Pull Request, please add `BREAKING CHANGE` in the optional body section
|
## Review your work before opening a PR
|
||||||
|
|
||||||
#### Scope
|
Before opening any pull request, including a draft, you must personally read and review the entire diff and the relevant surrounding code, understand the implementation, and verify the affected behavior. This applies when an AI agent writes the code or creates the PR for you. An agent's summary or review does not satisfy this requirement. Personally review each subsequent update and verify its effects before pushing it or asking an agent to push it.
|
||||||
The file or folder where the changes are made. If there are more than one, you can mention any
|
|
||||||
|
|
||||||
#### Description
|
Check the assumptions behind the change. Explain the implementation and important tradeoffs in your own words. For code changes, personally test the affected functionality, add regression tests where practical, and report the commands run and results actually observed. Identify failures, untested cases, and limitations. If an automated test is impractical, explain why and provide manual verification steps.
|
||||||
A short description of the issue
|
|
||||||
|
|
||||||
#### Issue number
|
Stay involved during review: answer questions, investigate feedback, and revise the work. If you need more time or cannot continue, say so. The maintainer is not committing to finish an abandoned implementation.
|
||||||
The issue fixed by this Pull Request.
|
|
||||||
|
|
||||||
The body is optional. It may contain short description of changes made.
|
## AI Disclosure
|
||||||
|
|
||||||
Following all the guidelines an ideal commit will look like:
|
AI tools may assist professional and hobbyist contributors. All code contributors must be able to personally understand, review, test, and maintain their changes, including security and performance implications; no diploma, job title, or employment is required. If you cannot assess the code yourself, report the problem instead of submitting AI-generated code. Bug reports, documentation improvements, and translations remain welcome.
|
||||||
```
|
|
||||||
git commit --signoff -m "feat(themes): New-theme - #834"
|
|
||||||
```
|
|
||||||
|
|
||||||
After committing, push your commits to your forked branch and create a Pull Request from there.
|
AI-assisted work must meet the personal full-diff review and functional testing requirements above before any PR is opened, including drafts or agent-created PRs. You remain responsible for explaining the implementation, addressing feedback, and correcting the code.
|
||||||
The Pull Request Title can be the same as `<type>(scope): <description> - <issue number>`
|
|
||||||
A demo layout of how the Pull request body can look:
|
|
||||||
```
|
|
||||||
Closes <Issue number along with link>
|
|
||||||
|
|
||||||
Description (What does the pull request do)
|
Declare whether AI was used to generate or modify submitted code or tests, draft substantive PR text, or create the PR. A simple Yes or No in the PR description is enough. Tool names, prompts, and transcripts are not required.
|
||||||
|
|
||||||
Changes (What changes were made )
|
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.
|
||||||
|
|
||||||
Screenshots or Videos
|
## Keep the result maintainable
|
||||||
|
|
||||||
Related Issues and Pull Requests(if any)
|
Prefer existing patterns and the smallest clear solution. Justify new abstractions, dependencies, configuration, and compatibility obligations. Include the documentation and tests needed to understand the behavior and change it safely later.
|
||||||
|
|
||||||
```
|
The maintainer must be able to understand and maintain the result without depending on your future availability. An offer to provide ongoing support does not replace this requirement. A working implementation may still be declined if its benefit does not justify its complexity or maintenance cost.
|
||||||
|
|
||||||
|
<a id="pull-requests"></a>
|
||||||
|
|
||||||
|
## Submitting and review
|
||||||
|
|
||||||
|
- Check existing [open and closed PRs](https://github.com/navidrome/navidrome/pulls?q=is%3Apr) to avoid duplicate work. If the issue author or another contributor has offered to submit a fix, ask in the issue before you start.
|
||||||
|
- Use the [development environment instructions](https://www.navidrome.org/docs/developers/dev-environment/). Work on a branch in your fork.
|
||||||
|
- Complete the [PR template](.github/pull_request_template.md) with the scope agreement or why agreement is not needed, verification evidence, and maintenance implications. Keep each PR focused.
|
||||||
|
- Follow the [commit conventions and DCO requirements](#commit-conventions-and-dco) below.
|
||||||
|
|
||||||
|
Review and merge are discretionary. Proposals may be declined, simplified, split, or deferred. PRs that do not fit Navidrome's direction, the agreed scope, or the maintainer's capacity to maintain them may be closed without detailed code review or prolonged discussion. PRs lacking evidence or left with unresolved questions may also be closed. Agreement to pursue work does not guarantee review or merge. Please do not tag the maintainer, send private messages, or post status requests to obtain faster review.
|
||||||
|
|
||||||
|
## Commit conventions and DCO
|
||||||
|
|
||||||
|
Use this commit format: `<type>(scope): <description>`, with an optional body.
|
||||||
|
|
||||||
|
Allowed types: `feat`, `fix`, `sec`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `revert`, `chore`.
|
||||||
|
|
||||||
|
Use a relevant file or folder as the scope and a concise description. Reference the related issue when one exists, and include `BREAKING CHANGE` in the body for breaking changes. Sign off every commit using `git commit --signoff`. These requirements apply equally to AI-assisted work.
|
||||||
|
|
|
||||||
|
|
@ -187,7 +187,7 @@ LABEL org.opencontainers.image.source="https://github.com/navidrome/navidrome"
|
||||||
# - libwebp + symlinks: enables native WebP encoding via purego/dlopen
|
# - libwebp + symlinks: enables native WebP encoding via purego/dlopen
|
||||||
# The mesa/LLVM stack mpv pulls in for video output is dropped in this same layer,
|
# The mesa/LLVM stack mpv pulls in for video output is dropped in this same layer,
|
||||||
# otherwise the deleted bytes still ship in the image.
|
# otherwise the deleted bytes still ship in the image.
|
||||||
RUN apk add -U --no-cache ffmpeg mpv sqlite libwebp libwebpdemux libwebpmux && \
|
RUN apk add -U --no-cache curl ffmpeg mpv sqlite libwebp libwebpdemux libwebpmux && \
|
||||||
for lib in libwebp libwebpdemux libwebpmux; do \
|
for lib in libwebp libwebpdemux libwebpmux; do \
|
||||||
target=$(ls /usr/lib/$lib.so.* 2>/dev/null | head -1) && \
|
target=$(ls /usr/lib/$lib.so.* 2>/dev/null | head -1) && \
|
||||||
[ -n "$target" ] && ln -sf "$target" /usr/lib/$lib.so; \
|
[ -n "$target" ] && ln -sf "$target" /usr/lib/$lib.so; \
|
||||||
|
|
|
||||||
51
Makefile
51
Makefile
|
|
@ -18,9 +18,13 @@ endif
|
||||||
SUPPORTED_PLATFORMS ?= linux/amd64,linux/arm64,linux/arm/v5,linux/arm/v6,linux/arm/v7,linux/386,linux/riscv64,darwin/amd64,darwin/arm64,windows/amd64,windows/386
|
SUPPORTED_PLATFORMS ?= linux/amd64,linux/arm64,linux/arm/v5,linux/arm/v6,linux/arm/v7,linux/386,linux/riscv64,darwin/amd64,darwin/arm64,windows/amd64,windows/386
|
||||||
IMAGE_PLATFORMS ?= $(shell echo $(SUPPORTED_PLATFORMS) | tr ',' '\n' | grep "linux" | grep -v "arm/v5" | tr '\n' ',' | sed 's/,$$//')
|
IMAGE_PLATFORMS ?= $(shell echo $(SUPPORTED_PLATFORMS) | tr ',' '\n' | grep "linux" | grep -v "arm/v5" | tr '\n' ',' | sed 's/,$$//')
|
||||||
PLATFORMS ?= $(SUPPORTED_PLATFORMS)
|
PLATFORMS ?= $(SUPPORTED_PLATFORMS)
|
||||||
DOCKER_TAG ?= deluan/navidrome:develop
|
DOCKER_TAG ?= navidrome/navidrome:develop
|
||||||
|
|
||||||
GOLANGCI_LINT_VERSION ?= v2.13.2
|
GOLANGCI_LINT_VERSION ?= v2.14.0
|
||||||
|
VACUUM_VERSION ?= v0.30.6
|
||||||
|
OAPI_CODEGEN_VERSION ?= v2.8.0
|
||||||
|
OASDIFF_VERSION ?= v1.32.1
|
||||||
|
API_DIFF_BASE ?= origin/master
|
||||||
|
|
||||||
UI_SRC_FILES := $(shell find ui -type f -not -path "ui/build/*" -not -path "ui/node_modules/*")
|
UI_SRC_FILES := $(shell find ui -type f -not -path "ui/build/*" -not -path "ui/node_modules/*")
|
||||||
|
|
||||||
|
|
@ -92,6 +96,45 @@ install-golangci-lint: ##@Development Install golangci-lint if not present
|
||||||
fi
|
fi
|
||||||
.PHONY: install-golangci-lint
|
.PHONY: install-golangci-lint
|
||||||
|
|
||||||
|
install-api-tools: ##@Development Install OpenAPI tools (vacuum, oapi-codegen, oasdiff) into ./bin
|
||||||
|
@STAMP=bin/.api-tools-$(VACUUM_VERSION)-$(OAPI_CODEGEN_VERSION)-$(OASDIFF_VERSION); \
|
||||||
|
if [ ! -f $$STAMP ] || [ ! -x bin/vacuum ] || [ ! -x bin/oapi-codegen ] || [ ! -x bin/oasdiff ]; then \
|
||||||
|
echo "Installing OpenAPI tools..."; \
|
||||||
|
GOBIN=$(CURDIR)/bin go install github.com/daveshanley/vacuum@$(VACUUM_VERSION) && \
|
||||||
|
GOBIN=$(CURDIR)/bin go install github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@$(OAPI_CODEGEN_VERSION) && \
|
||||||
|
GOBIN=$(CURDIR)/bin go install github.com/oasdiff/oasdiff@$(OASDIFF_VERSION) && \
|
||||||
|
rm -f bin/.api-tools-* && touch $$STAMP; \
|
||||||
|
fi
|
||||||
|
.PHONY: install-api-tools
|
||||||
|
|
||||||
|
api-lint: install-api-tools ##@Development Lint the OpenAPI spec
|
||||||
|
./bin/vacuum lint -r api/.vacuum.yaml -d -q -b --fail-severity error api/openapi/openapi.yaml
|
||||||
|
.PHONY: api-lint
|
||||||
|
|
||||||
|
api-bundle: install-api-tools ##@Development Bundle the multi-file OpenAPI spec into api/bundled
|
||||||
|
./bin/vacuum bundle -q --composed -p api/openapi api/openapi/openapi.yaml api/bundled/openapi.yaml
|
||||||
|
./bin/vacuum bundle -q --composed --format json -p api/openapi api/openapi/openapi.yaml api/bundled/openapi.json
|
||||||
|
.PHONY: api-bundle
|
||||||
|
|
||||||
|
api-gen: api-bundle ##@Development Generate the API v1 server code from the bundled spec
|
||||||
|
./bin/oapi-codegen -config server/apiv1/oapi-codegen.yaml api/bundled/openapi.json
|
||||||
|
.PHONY: api-gen
|
||||||
|
|
||||||
|
api-diff: api-bundle ##@Development Fail on breaking OpenAPI changes against the merge-base with $(API_DIFF_BASE)
|
||||||
|
@git rev-parse --verify --quiet $(API_DIFF_BASE)^{commit} >/dev/null || { echo "Base ref $(API_DIFF_BASE) not found; set API_DIFF_BASE"; exit 1; }; \
|
||||||
|
BASE="$$(git merge-base HEAD $(API_DIFF_BASE) 2>/dev/null)"; \
|
||||||
|
if [ -z "$$BASE" ]; then \
|
||||||
|
echo "No merge-base with $(API_DIFF_BASE); falling back to its tip"; \
|
||||||
|
BASE=$(API_DIFF_BASE); \
|
||||||
|
fi; \
|
||||||
|
if git cat-file -e $$BASE:api/bundled/openapi.json 2>/dev/null; then \
|
||||||
|
git show $$BASE:api/bundled/openapi.json > $(CURDIR)/bin/api-base.json && \
|
||||||
|
./bin/oasdiff breaking $(CURDIR)/bin/api-base.json api/bundled/openapi.json --fail-on ERR --severity-levels api/.oasdiff-levels.txt; \
|
||||||
|
else \
|
||||||
|
echo "No bundled spec at $$BASE; skipping breaking-change check"; \
|
||||||
|
fi
|
||||||
|
.PHONY: api-diff
|
||||||
|
|
||||||
lint: install-golangci-lint ##@Development Lint Go code
|
lint: install-golangci-lint ##@Development Lint Go code
|
||||||
PATH=./bin:$$PATH golangci-lint run --timeout 5m
|
PATH=./bin:$$PATH golangci-lint run --timeout 5m
|
||||||
.PHONY: lint
|
.PHONY: lint
|
||||||
|
|
@ -111,7 +154,7 @@ wire: check_go_env ##@Development Update Dependency Injection
|
||||||
go tool wire gen -tags="$$(echo '$(GO_BUILD_TAGS)' | tr ',' ' ')" ./...
|
go tool wire gen -tags="$$(echo '$(GO_BUILD_TAGS)' | tr ',' ' ')" ./...
|
||||||
.PHONY: wire
|
.PHONY: wire
|
||||||
|
|
||||||
gen: check_go_env ##@Development Run go generate for code generation
|
gen: check_go_env api-gen ##@Development Run go generate for code generation
|
||||||
go generate ./...
|
go generate ./...
|
||||||
cd plugins/cmd/ndpgen && go run . -shared-types -input=../../types -output=../../pdk -go -rust
|
cd plugins/cmd/ndpgen && go run . -shared-types -input=../../types -output=../../pdk -go -rust
|
||||||
cd plugins/cmd/ndpgen && go run . -host-wrappers -input=../../host -package=host -shared=../../types
|
cd plugins/cmd/ndpgen && go run . -host-wrappers -input=../../host -package=host -shared=../../types
|
||||||
|
|
@ -180,7 +223,7 @@ docker-build: ##@Cross_Compilation Cross-compile for any supported platform (che
|
||||||
--output "./binaries" --target binary .
|
--output "./binaries" --target binary .
|
||||||
.PHONY: docker-build
|
.PHONY: docker-build
|
||||||
|
|
||||||
docker-image: ##@Cross_Compilation Build Docker image, tagged as `deluan/navidrome:develop`, override with DOCKER_TAG var. Use IMAGE_PLATFORMS to specify target platforms
|
docker-image: ##@Cross_Compilation Build Docker image, tagged as `navidrome/navidrome:develop`, override with DOCKER_TAG var. Use IMAGE_PLATFORMS to specify target platforms
|
||||||
@echo $(IMAGE_PLATFORMS) | grep -q "windows" && echo "ERROR: Windows is not supported for Docker builds" && exit 1 || true
|
@echo $(IMAGE_PLATFORMS) | grep -q "windows" && echo "ERROR: Windows is not supported for Docker builds" && exit 1 || true
|
||||||
@echo $(IMAGE_PLATFORMS) | grep -q "darwin" && echo "ERROR: macOS is not supported for Docker builds" && exit 1 || true
|
@echo $(IMAGE_PLATFORMS) | grep -q "darwin" && echo "ERROR: macOS is not supported for Docker builds" && exit 1 || true
|
||||||
@echo $(IMAGE_PLATFORMS) | grep -q "arm/v5" && echo "ERROR: Linux ARMv5 is not supported for Docker builds" && exit 1 || true
|
@echo $(IMAGE_PLATFORMS) | grep -q "arm/v5" && echo "ERROR: Linux ARMv5 is not supported for Docker builds" && exit 1 || true
|
||||||
|
|
|
||||||
25
README.md
25
README.md
|
|
@ -5,7 +5,7 @@
|
||||||
[](https://github.com/navidrome/navidrome/releases)
|
[](https://github.com/navidrome/navidrome/releases)
|
||||||
[](https://nightly.link/navidrome/navidrome/workflows/pipeline/master)
|
[](https://nightly.link/navidrome/navidrome/workflows/pipeline/master)
|
||||||
[](https://github.com/navidrome/navidrome/releases/latest)
|
[](https://github.com/navidrome/navidrome/releases/latest)
|
||||||
[](https://hub.docker.com/r/deluan/navidrome)
|
[](https://hub.docker.com/r/navidrome/navidrome)
|
||||||
[](https://discord.gg/xh7j7yF)
|
[](https://discord.gg/xh7j7yF)
|
||||||
[](https://www.reddit.com/r/navidrome/)
|
[](https://www.reddit.com/r/navidrome/)
|
||||||
[](CODE_OF_CONDUCT.md)
|
[](CODE_OF_CONDUCT.md)
|
||||||
|
|
@ -21,9 +21,11 @@ the `master` branch in order to get a stable set of binaries.
|
||||||
|
|
||||||
## [Check out our Live Demo!](https://www.navidrome.org/demo/)
|
## [Check out our Live Demo!](https://www.navidrome.org/demo/)
|
||||||
|
|
||||||
__Any feedback is welcome!__ If you need/want a new feature, find a bug or think of any way to improve Navidrome,
|
__Any feedback is welcome!__ If you find a bug, please file a [GitHub issue](https://github.com/navidrome/navidrome/issues/new/choose).
|
||||||
please file a [GitHub issue](https://github.com/navidrome/navidrome/issues) or join the discussion in our
|
If you need/want a new feature or think of any way to improve Navidrome, please share it in
|
||||||
[Subreddit](https://www.reddit.com/r/navidrome/). If you want to contribute to the project in any other way
|
[Discussions](https://github.com/navidrome/navidrome/discussions/categories/ideas) or join the discussion in our
|
||||||
|
[Subreddit](https://www.reddit.com/r/navidrome/). Before contributing code, please read the
|
||||||
|
[Contribution Guide](CONTRIBUTING.md). If you want to contribute to the project in any other way
|
||||||
([ui/backend dev](https://www.navidrome.org/docs/developers/),
|
([ui/backend dev](https://www.navidrome.org/docs/developers/),
|
||||||
[translations](https://www.navidrome.org/docs/developers/translations/),
|
[translations](https://www.navidrome.org/docs/developers/translations/),
|
||||||
[themes](https://www.navidrome.org/docs/developers/creating-themes)), please join the chat in our
|
[themes](https://www.navidrome.org/docs/developers/creating-themes)), please join the chat in our
|
||||||
|
|
@ -35,11 +37,18 @@ See instructions on the [project's website](https://www.navidrome.org/docs/insta
|
||||||
|
|
||||||
## Cloud Hosting
|
## Cloud Hosting
|
||||||
|
|
||||||
[PikaPods](https://www.pikapods.com) has partnered with us to offer you an
|
Several cloud hosting providers partner with us to offer [officially supported, cloud-hosted solutions](https://www.navidrome.org/docs/installation/managed). If you sign up with any of these providers, a share of the revenue funds the development of Navidrome at no additional cost for you.
|
||||||
[officially supported, cloud-hosted solution](https://www.navidrome.org/docs/installation/managed/#pikapods).
|
|
||||||
A share of the revenue helps fund the development of Navidrome at no additional cost for you.
|
<a href="https://www.pikapods.com/pods?run=navidrome"><img src="resources/hosting/pikapods.svg" alt="Run on PikaPods" width="200" height="40"></a>
|
||||||
|
<br>
|
||||||
|
<a href="https://zenith.hosting/host/navidrome?ref=navidrome"><img src="resources/hosting/zenith.svg" alt="Deploy with Zenith" width="200" height="40"></a>
|
||||||
|
<br>
|
||||||
|
<a href="https://store.elfhosted.com/product/navidrome/"><img src="resources/hosting/elfhosted.svg" alt="Deploy on ElfHosted" width="200" height="40"></a>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[](https://www.pikapods.com/pods?run=navidrome)
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -43,7 +43,7 @@ func (c *client) getJWT(ctx context.Context) (string, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch a new anonymous token
|
// Fetch a new anonymous token
|
||||||
req, err := http.NewRequestWithContext(ctx, "GET", authBaseURL+"/login/anonymous?jo=p&rto=c", nil)
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, authBaseURL+"/login/anonymous?jo=p&rto=c", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
@ -55,7 +55,7 @@ func (c *client) getJWT(ctx context.Context) (string, error) {
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if resp.StatusCode != 200 {
|
if resp.StatusCode != http.StatusOK {
|
||||||
return "", fmt.Errorf("deezer: failed to get JWT token: %s", resp.Status)
|
return "", fmt.Errorf("deezer: failed to get JWT token: %s", resp.Status)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -65,7 +65,7 @@ func (c *client) getJWT(ctx context.Context) (string, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
type authResponse struct {
|
type authResponse struct {
|
||||||
JWT string `json:"jwt"` //nolint:gosec
|
JWT string `json:"jwt"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var result authResponse
|
var result authResponse
|
||||||
|
|
|
||||||
|
|
@ -20,9 +20,9 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
var ctx context.Context
|
var ctx context.Context
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
httpClient = &fakeHttpClient{}
|
httpClient = &fakeHttpClient{}
|
||||||
client = newClient(httpClient)
|
client = newClient(httpClient)
|
||||||
ctx = context.Background()
|
|
||||||
})
|
})
|
||||||
|
|
||||||
Describe("getJWT", func() {
|
Describe("getJWT", func() {
|
||||||
|
|
@ -30,32 +30,32 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
It("successfully fetches and caches a JWT token", func() {
|
It("successfully fetches and caches a JWT token", func() {
|
||||||
testJWT := createTestJWT(5 * time.Minute)
|
testJWT := createTestJWT(5 * time.Minute)
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
|
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
|
||||||
})
|
})
|
||||||
|
|
||||||
token, err := client.getJWT(ctx)
|
token, err := client.getJWT(ctx)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(token).To(Equal(testJWT))
|
Expect(token).To(Equal(testJWT))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("returns the cached token on subsequent calls", func() {
|
It("returns the cached token on subsequent calls", func() {
|
||||||
testJWT := createTestJWT(5 * time.Minute)
|
testJWT := createTestJWT(5 * time.Minute)
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
|
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
|
||||||
})
|
})
|
||||||
|
|
||||||
// First call should fetch from API
|
// First call should fetch from API
|
||||||
token1, err := client.getJWT(ctx)
|
token1, err := client.getJWT(ctx)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(token1).To(Equal(testJWT))
|
Expect(token1).To(Equal(testJWT))
|
||||||
Expect(httpClient.lastRequest.URL.Path).To(Equal("/login/anonymous"))
|
Expect(httpClient.lastRequest.URL.Path).To(Equal("/login/anonymous"))
|
||||||
|
|
||||||
// Second call should return cached token without hitting API
|
// Second call should return cached token without hitting API
|
||||||
httpClient.lastRequest = nil // Clear last request to verify no new request is made
|
httpClient.lastRequest = nil // Clear last request to verify no new request is made
|
||||||
token2, err := client.getJWT(ctx)
|
token2, err := client.getJWT(ctx)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(token2).To(Equal(testJWT))
|
Expect(token2).To(Equal(testJWT))
|
||||||
Expect(httpClient.lastRequest).To(BeNil()) // No new request made
|
Expect(httpClient.lastRequest).To(BeNil()) // No new request made
|
||||||
})
|
})
|
||||||
|
|
@ -65,17 +65,17 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
testToken, err := jwt.NewBuilder().
|
testToken, err := jwt.NewBuilder().
|
||||||
Expiration(expectedExpiration).
|
Expiration(expectedExpiration).
|
||||||
Build()
|
Build()
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
|
testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))),
|
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))),
|
||||||
})
|
})
|
||||||
|
|
||||||
token, err := client.getJWT(ctx)
|
token, err := client.getJWT(ctx)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(token).ToNot(BeEmpty())
|
Expect(token).ToNot(BeEmpty())
|
||||||
|
|
||||||
// Verify the token is cached until close to expiration
|
// Verify the token is cached until close to expiration
|
||||||
|
|
@ -90,7 +90,7 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
// Create a token that expires in 30 seconds (less than 1-minute buffer)
|
// Create a token that expires in 30 seconds (less than 1-minute buffer)
|
||||||
testJWT := createTestJWT(30 * time.Second)
|
testJWT := createTestJWT(30 * time.Second)
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
|
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -103,7 +103,7 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
// Create a token that expired 1 minute ago
|
// Create a token that expired 1 minute ago
|
||||||
testJWT := createTestJWT(-1 * time.Minute)
|
testJWT := createTestJWT(-1 * time.Minute)
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
|
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -116,12 +116,12 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
// Create a token that expires in 2 minutes (just over the 1-minute buffer)
|
// Create a token that expires in 2 minutes (just over the 1-minute buffer)
|
||||||
testJWT := createTestJWT(2 * time.Minute)
|
testJWT := createTestJWT(2 * time.Minute)
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
|
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, testJWT))),
|
||||||
})
|
})
|
||||||
|
|
||||||
token, err := client.getJWT(ctx)
|
token, err := client.getJWT(ctx)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(token).ToNot(BeEmpty())
|
Expect(token).ToNot(BeEmpty())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
@ -129,7 +129,7 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
Context("with invalid responses", func() {
|
Context("with invalid responses", func() {
|
||||||
It("handles HTTP error responses", func() {
|
It("handles HTTP error responses", func() {
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 500,
|
StatusCode: http.StatusInternalServerError,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -140,7 +140,7 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
|
|
||||||
It("handles malformed JSON responses", func() {
|
It("handles malformed JSON responses", func() {
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{invalid json}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{invalid json}`)),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -151,7 +151,7 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
|
|
||||||
It("handles responses with empty JWT field", func() {
|
It("handles responses with empty JWT field", func() {
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"jwt":""}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"jwt":""}`)),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -162,7 +162,7 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
|
|
||||||
It("handles invalid JWT tokens", func() {
|
It("handles invalid JWT tokens", func() {
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"jwt":"not-a-valid-jwt"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"jwt":"not-a-valid-jwt"}`)),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -176,17 +176,17 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
testToken, err := jwt.NewBuilder().
|
testToken, err := jwt.NewBuilder().
|
||||||
Claim("custom", "value").
|
Claim("custom", "value").
|
||||||
Build()
|
Build()
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
||||||
// Verify token has no expiration
|
// Verify token has no expiration
|
||||||
_, hasExp := testToken.Expiration()
|
_, hasExp := testToken.Expiration()
|
||||||
Expect(hasExp).To(BeFalse())
|
Expect(hasExp).To(BeFalse())
|
||||||
|
|
||||||
testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
|
testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))),
|
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, string(testJWT)))),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -201,12 +201,12 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
// First token expires in 5 minutes
|
// First token expires in 5 minutes
|
||||||
firstJWT := createTestJWT(5 * time.Minute)
|
firstJWT := createTestJWT(5 * time.Minute)
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, firstJWT))),
|
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, firstJWT))),
|
||||||
})
|
})
|
||||||
|
|
||||||
token1, err := client.getJWT(ctx)
|
token1, err := client.getJWT(ctx)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(token1).To(Equal(firstJWT))
|
Expect(token1).To(Equal(firstJWT))
|
||||||
|
|
||||||
// Manually expire the cached token
|
// Manually expire the cached token
|
||||||
|
|
@ -215,12 +215,12 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
// Second token with different expiration (10 minutes)
|
// Second token with different expiration (10 minutes)
|
||||||
secondJWT := createTestJWT(10 * time.Minute)
|
secondJWT := createTestJWT(10 * time.Minute)
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, secondJWT))),
|
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s"}`, secondJWT))),
|
||||||
})
|
})
|
||||||
|
|
||||||
token2, err := client.getJWT(ctx)
|
token2, err := client.getJWT(ctx)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(token2).To(Equal(secondJWT))
|
Expect(token2).To(Equal(secondJWT))
|
||||||
Expect(token2).ToNot(Equal(token1))
|
Expect(token2).ToNot(Equal(token1))
|
||||||
})
|
})
|
||||||
|
|
@ -280,15 +280,12 @@ var _ = Describe("JWT Authentication", func() {
|
||||||
|
|
||||||
// createTestJWT creates a valid JWT token for testing purposes
|
// createTestJWT creates a valid JWT token for testing purposes
|
||||||
func createTestJWT(expiresIn time.Duration) string {
|
func createTestJWT(expiresIn time.Duration) string {
|
||||||
|
GinkgoHelper()
|
||||||
token, err := jwt.NewBuilder().
|
token, err := jwt.NewBuilder().
|
||||||
Expiration(time.Now().Add(expiresIn)).
|
Expiration(time.Now().Add(expiresIn)).
|
||||||
Build()
|
Build()
|
||||||
if err != nil {
|
Expect(err).ToNot(HaveOccurred())
|
||||||
panic(fmt.Sprintf("failed to create test JWT: %v", err))
|
|
||||||
}
|
|
||||||
signed, err := jwt.Sign(token, jwt.WithInsecureNoSignature())
|
signed, err := jwt.Sign(token, jwt.WithInsecureNoSignature())
|
||||||
if err != nil {
|
Expect(err).ToNot(HaveOccurred())
|
||||||
panic(fmt.Sprintf("failed to sign test JWT: %v", err))
|
|
||||||
}
|
|
||||||
return string(signed)
|
return string(signed)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -26,11 +26,11 @@ var _ = Describe("client", func() {
|
||||||
Describe("ArtistImages", func() {
|
Describe("ArtistImages", func() {
|
||||||
It("returns artist images from a successful request", func() {
|
It("returns artist images from a successful request", func() {
|
||||||
f, err := os.Open("tests/fixtures/deezer.search.artist.json")
|
f, err := os.Open("tests/fixtures/deezer.search.artist.json")
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: 200})
|
httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: http.StatusOK})
|
||||||
|
|
||||||
artists, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20)
|
artists, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(artists).To(HaveLen(17))
|
Expect(artists).To(HaveLen(17))
|
||||||
Expect(artists[0].Name).To(Equal("Michael Jackson"))
|
Expect(artists[0].Name).To(Equal("Michael Jackson"))
|
||||||
Expect(artists[0].PictureXl).To(Equal("https://cdn-images.dzcdn.net/images/artist/97fae13b2b30e4aec2e8c9e0c7839d92/1000x1000-000000-80-0-0.jpg"))
|
Expect(artists[0].PictureXl).To(Equal("https://cdn-images.dzcdn.net/images/artist/97fae13b2b30e4aec2e8c9e0c7839d92/1000x1000-000000-80-0-0.jpg"))
|
||||||
|
|
@ -38,7 +38,7 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("fails if artist was not found", func() {
|
It("fails if artist was not found", func() {
|
||||||
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -49,7 +49,7 @@ var _ = Describe("client", func() {
|
||||||
// Deezer answers 200 with no rate-limit headers when throttling, so this body is the only signal.
|
// Deezer answers 200 with no rate-limit headers when throttling, so this body is the only signal.
|
||||||
It("reports an exhausted quota as a retryable error, not as a missing artist", func() {
|
It("reports an exhausted quota as a retryable error, not as a missing artist", func() {
|
||||||
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(
|
Body: io.NopCloser(bytes.NewBufferString(
|
||||||
`{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)),
|
`{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)),
|
||||||
})
|
})
|
||||||
|
|
@ -64,7 +64,7 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("reports a non-quota body error as a plain error", func() {
|
It("reports a non-quota body error as a plain error", func() {
|
||||||
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(
|
Body: io.NopCloser(bytes.NewBufferString(
|
||||||
`{"error":{"type":"Exception","message":"Invalid query","code":100}}`)),
|
`{"error":{"type":"Exception","message":"Invalid query","code":100}}`)),
|
||||||
})
|
})
|
||||||
|
|
@ -80,11 +80,11 @@ var _ = Describe("client", func() {
|
||||||
Describe("TopTracks", func() {
|
Describe("TopTracks", func() {
|
||||||
It("returns top tracks with artist and album info from a successful request", func() {
|
It("returns top tracks with artist and album info from a successful request", func() {
|
||||||
f, err := os.Open("tests/fixtures/deezer.artist.top.json")
|
f, err := os.Open("tests/fixtures/deezer.artist.top.json")
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: 200})
|
httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: http.StatusOK})
|
||||||
|
|
||||||
tracks, err := client.getTopTracks(GinkgoT().Context(), 27, 5)
|
tracks, err := client.getTopTracks(GinkgoT().Context(), 27, 5)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(tracks).To(HaveLen(5))
|
Expect(tracks).To(HaveLen(5))
|
||||||
|
|
||||||
// Verify first track has all expected fields
|
// Verify first track has all expected fields
|
||||||
|
|
@ -104,18 +104,18 @@ var _ = Describe("client", func() {
|
||||||
// Mock the JWT token endpoint with a valid JWT that expires in 5 minutes
|
// Mock the JWT token endpoint with a valid JWT that expires in 5 minutes
|
||||||
testJWT := createTestJWT(5 * time.Minute)
|
testJWT := createTestJWT(5 * time.Minute)
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))),
|
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))),
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
It("returns artist bio from a successful request", func() {
|
It("returns artist bio from a successful request", func() {
|
||||||
f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json")
|
f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json")
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
|
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
|
||||||
|
|
||||||
bio, err := client.getArtistBio(GinkgoT().Context(), 27, "en")
|
bio, err := client.getArtistBio(GinkgoT().Context(), 27, "en")
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(bio).To(ContainSubstring("Schoolmates Thomas and Guy-Manuel"))
|
Expect(bio).To(ContainSubstring("Schoolmates Thomas and Guy-Manuel"))
|
||||||
Expect(bio).ToNot(ContainSubstring("<p>"))
|
Expect(bio).ToNot(ContainSubstring("<p>"))
|
||||||
Expect(bio).ToNot(ContainSubstring("</p>"))
|
Expect(bio).ToNot(ContainSubstring("</p>"))
|
||||||
|
|
@ -123,21 +123,21 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("uses the provided language", func() {
|
It("uses the provided language", func() {
|
||||||
f, err := os.Open("tests/fixtures/deezer.artist.bio.fr.json")
|
f, err := os.Open("tests/fixtures/deezer.artist.bio.fr.json")
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
|
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
|
||||||
|
|
||||||
_, err = client.getArtistBio(GinkgoT().Context(), 27, "fr")
|
_, err = client.getArtistBio(GinkgoT().Context(), 27, "fr")
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(httpClient.lastRequest.Header.Get("Accept-Language")).To(Equal("fr"))
|
Expect(httpClient.lastRequest.Header.Get("Accept-Language")).To(Equal("fr"))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("includes the JWT token in the request", func() {
|
It("includes the JWT token in the request", func() {
|
||||||
f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json")
|
f, err := os.Open("tests/fixtures/deezer.artist.bio.en.json")
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
|
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK})
|
||||||
|
|
||||||
_, err = client.getArtistBio(GinkgoT().Context(), 27, "en")
|
_, err = client.getArtistBio(GinkgoT().Context(), 27, "en")
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
// Verify that the Authorization header has the Bearer token format
|
// Verify that the Authorization header has the Bearer token format
|
||||||
authHeader := httpClient.lastRequest.Header.Get("Authorization")
|
authHeader := httpClient.lastRequest.Header.Get("Authorization")
|
||||||
Expect(authHeader).To(HavePrefix("Bearer "))
|
Expect(authHeader).To(HavePrefix("Bearer "))
|
||||||
|
|
@ -163,7 +163,7 @@ var _ = Describe("client", func() {
|
||||||
]
|
]
|
||||||
}`
|
}`
|
||||||
httpClient.mock("https://pipe.deezer.com/api", http.Response{
|
httpClient.mock("https://pipe.deezer.com/api", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(errorResponse)),
|
Body: io.NopCloser(bytes.NewBufferString(errorResponse)),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -185,7 +185,7 @@ var _ = Describe("client", func() {
|
||||||
}
|
}
|
||||||
}`
|
}`
|
||||||
httpClient.mock("https://pipe.deezer.com/api", http.Response{
|
httpClient.mock("https://pipe.deezer.com/api", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(emptyBioResponse)),
|
Body: io.NopCloser(bytes.NewBufferString(emptyBioResponse)),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -195,7 +195,7 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("handles JWT token fetch failure", func() {
|
It("handles JWT token fetch failure", func() {
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 500,
|
StatusCode: http.StatusInternalServerError,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -208,7 +208,7 @@ var _ = Describe("client", func() {
|
||||||
// Create a JWT that expires in 30 seconds (less than the 1-minute buffer)
|
// Create a JWT that expires in 30 seconds (less than the 1-minute buffer)
|
||||||
expiredJWT := createTestJWT(30 * time.Second)
|
expiredJWT := createTestJWT(30 * time.Second)
|
||||||
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, expiredJWT))),
|
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, expiredJWT))),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -238,5 +238,6 @@ func (c *fakeHttpClient) Do(req *http.Request) (*http.Response, error) {
|
||||||
if resp, ok := c.responses[u.String()]; ok {
|
if resp, ok := c.responses[u.String()]; ok {
|
||||||
return resp, nil
|
return resp, nil
|
||||||
}
|
}
|
||||||
panic("URL not mocked: " + u.String())
|
Fail("URL not mocked: " + u.String())
|
||||||
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -34,7 +34,7 @@ type deezerAgent struct {
|
||||||
func deezerConstructor(dataStore model.DataStore) agents.Interface {
|
func deezerConstructor(dataStore model.DataStore) agents.Interface {
|
||||||
agent := &deezerAgent{
|
agent := &deezerAgent{
|
||||||
dataStore: dataStore,
|
dataStore: dataStore,
|
||||||
languages: conf.Server.Deezer.Languages,
|
languages: conf.Server().Deezer.Languages,
|
||||||
}
|
}
|
||||||
httpClient := httpclient.New(consts.DefaultHttpClientTimeOut)
|
httpClient := httpclient.New(consts.DefaultHttpClientTimeOut)
|
||||||
cachedHttpClient := cache.NewHTTPClient(httpClient, consts.DefaultHttpClientTimeOut)
|
cachedHttpClient := cache.NewHTTPClient(httpClient, consts.DefaultHttpClientTimeOut)
|
||||||
|
|
@ -192,7 +192,7 @@ func (s *deezerAgent) GetArtistBiography(ctx context.Context, _, name, _ string)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
conf.AddHook(func() {
|
conf.AddHook(func() {
|
||||||
if conf.Server.Deezer.Enabled {
|
if conf.Server().Deezer.Enabled {
|
||||||
agents.Register(deezerAgentName, deezerConstructor)
|
agents.Register(deezerAgentName, deezerConstructor)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ package deezer
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/conf/configtest"
|
||||||
"github.com/navidrome/navidrome/log"
|
"github.com/navidrome/navidrome/log"
|
||||||
"github.com/navidrome/navidrome/tests"
|
"github.com/navidrome/navidrome/tests"
|
||||||
. "github.com/onsi/ginkgo/v2"
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
|
@ -15,3 +16,5 @@ func TestDeezer(t *testing.T) {
|
||||||
RegisterFailHandler(Fail)
|
RegisterFailHandler(Fail)
|
||||||
RunSpecs(t, "Deezer Test Suite")
|
RunSpecs(t, "Deezer Test Suite")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ = configtest.RestoreAfterEachSpec()
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,6 @@ import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/conf"
|
"github.com/navidrome/navidrome/conf"
|
||||||
"github.com/navidrome/navidrome/conf/configtest"
|
|
||||||
"github.com/navidrome/navidrome/core/agents"
|
"github.com/navidrome/navidrome/core/agents"
|
||||||
"github.com/navidrome/navidrome/tests"
|
"github.com/navidrome/navidrome/tests"
|
||||||
. "github.com/onsi/ginkgo/v2"
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
|
@ -22,14 +21,13 @@ var _ = Describe("deezerAgent", func() {
|
||||||
var ctx context.Context
|
var ctx context.Context
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
ctx = context.Background()
|
ctx = GinkgoT().Context()
|
||||||
DeferCleanup(configtest.SetupConfig())
|
conf.Update(func(c *conf.Options) { c.Deezer.Enabled = true })
|
||||||
conf.Server.Deezer.Enabled = true
|
|
||||||
})
|
})
|
||||||
|
|
||||||
Describe("deezerConstructor", func() {
|
Describe("deezerConstructor", func() {
|
||||||
It("uses configured languages", func() {
|
It("uses configured languages", func() {
|
||||||
conf.Server.Deezer.Languages = []string{"pt", "en"}
|
conf.Update(func(c *conf.Options) { c.Deezer.Languages = []string{"pt", "en"} })
|
||||||
agent := deezerConstructor(&tests.MockDataStore{}).(*deezerAgent)
|
agent := deezerConstructor(&tests.MockDataStore{}).(*deezerAgent)
|
||||||
Expect(agent.languages).To(Equal([]string{"pt", "en"}))
|
Expect(agent.languages).To(Equal([]string{"pt", "en"}))
|
||||||
})
|
})
|
||||||
|
|
@ -50,7 +48,7 @@ var _ = Describe("deezerAgent", func() {
|
||||||
It("picks the exact-name match with the most fans when several share the name", func() {
|
It("picks the exact-name match with the most fans when several share the name", func() {
|
||||||
// Deezer RANKING order returns a low-popularity homonym first (see issue #5802)
|
// Deezer RANKING order returns a low-popularity homonym first (see issue #5802)
|
||||||
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"data":[
|
Body: io.NopCloser(bytes.NewBufferString(`{"data":[
|
||||||
{"id":61045802,"name":"Queen","nb_fan":75},
|
{"id":61045802,"name":"Queen","nb_fan":75},
|
||||||
{"id":141954732,"name":"Queen","nb_fan":397},
|
{"id":141954732,"name":"Queen","nb_fan":397},
|
||||||
|
|
@ -68,7 +66,7 @@ var _ = Describe("deezerAgent", func() {
|
||||||
|
|
||||||
It("matches the name case-insensitively", func() {
|
It("matches the name case-insensitively", func() {
|
||||||
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"data":[
|
Body: io.NopCloser(bytes.NewBufferString(`{"data":[
|
||||||
{"id":1,"name":"QUEEN","nb_fan":10},
|
{"id":1,"name":"QUEEN","nb_fan":10},
|
||||||
{"id":2,"name":"queen","nb_fan":20}
|
{"id":2,"name":"queen","nb_fan":20}
|
||||||
|
|
@ -85,7 +83,7 @@ var _ = Describe("deezerAgent", func() {
|
||||||
// lookup reaching that here would record a permanent absence.
|
// lookup reaching that here would record a permanent absence.
|
||||||
It("surfaces an exhausted quota instead of reporting the artist as not found", func() {
|
It("surfaces an exhausted quota instead of reporting the artist as not found", func() {
|
||||||
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(
|
Body: io.NopCloser(bytes.NewBufferString(
|
||||||
`{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)),
|
`{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)),
|
||||||
})
|
})
|
||||||
|
|
@ -99,7 +97,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}`)),
|
||||||
|
|
@ -125,7 +123,7 @@ var _ = Describe("deezerAgent", func() {
|
||||||
|
|
||||||
It("returns the real images when the artist has a picture", func() {
|
It("returns the real images when the artist has a picture", func() {
|
||||||
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"data":[
|
Body: io.NopCloser(bytes.NewBufferString(`{"data":[
|
||||||
{"id":412,"name":"Queen","nb_fan":12744378,
|
{"id":412,"name":"Queen","nb_fan":12744378,
|
||||||
"picture_xl":"https://cdn-images.dzcdn.net/images/artist/abc/1000x1000-000000-80-0-0.jpg",
|
"picture_xl":"https://cdn-images.dzcdn.net/images/artist/abc/1000x1000-000000-80-0-0.jpg",
|
||||||
|
|
@ -142,7 +140,7 @@ var _ = Describe("deezerAgent", func() {
|
||||||
|
|
||||||
It("returns ErrNotFound when the artist only has empty-id placeholder pictures", func() {
|
It("returns ErrNotFound when the artist only has empty-id placeholder pictures", func() {
|
||||||
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"data":[
|
Body: io.NopCloser(bytes.NewBufferString(`{"data":[
|
||||||
{"id":412,"name":"Queen","nb_fan":12744378,
|
{"id":412,"name":"Queen","nb_fan":12744378,
|
||||||
"picture_xl":"https://cdn-images.dzcdn.net/images/artist//1000x1000-000000-80-0-0.jpg",
|
"picture_xl":"https://cdn-images.dzcdn.net/images/artist//1000x1000-000000-80-0-0.jpg",
|
||||||
|
|
@ -168,18 +166,18 @@ var _ = Describe("deezerAgent", func() {
|
||||||
|
|
||||||
// Mock search artist (returns Michael Jackson)
|
// Mock search artist (returns Michael Jackson)
|
||||||
fSearch, _ := os.Open("tests/fixtures/deezer.search.artist.json")
|
fSearch, _ := os.Open("tests/fixtures/deezer.search.artist.json")
|
||||||
httpClient.searchResponse = &http.Response{Body: fSearch, StatusCode: 200}
|
httpClient.searchResponse = &http.Response{Body: fSearch, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
// Mock JWT token
|
// Mock JWT token
|
||||||
testJWT := createTestJWT(5 * time.Minute)
|
testJWT := createTestJWT(5 * time.Minute)
|
||||||
httpClient.jwtResponse = &http.Response{
|
httpClient.jwtResponse = &http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))),
|
Body: io.NopCloser(bytes.NewBufferString(fmt.Sprintf(`{"jwt":"%s","refresh_token":""}`, testJWT))),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
setupAgent := func(languages []string) {
|
setupAgent := func(languages []string) {
|
||||||
conf.Server.Deezer.Languages = languages
|
conf.Update(func(c *conf.Options) { c.Deezer.Languages = languages })
|
||||||
agent = &deezerAgent{
|
agent = &deezerAgent{
|
||||||
dataStore: &tests.MockDataStore{},
|
dataStore: &tests.MockDataStore{},
|
||||||
client: newClient(httpClient),
|
client: newClient(httpClient),
|
||||||
|
|
@ -192,7 +190,7 @@ var _ = Describe("deezerAgent", func() {
|
||||||
|
|
||||||
// French biography available
|
// French biography available
|
||||||
fFr, _ := os.Open("tests/fixtures/deezer.artist.bio.fr.json")
|
fFr, _ := os.Open("tests/fixtures/deezer.artist.bio.fr.json")
|
||||||
httpClient.bioResponses["fr"] = &http.Response{Body: fFr, StatusCode: 200}
|
httpClient.bioResponses["fr"] = &http.Response{Body: fFr, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
|
bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
|
||||||
|
|
||||||
|
|
@ -207,10 +205,10 @@ var _ = Describe("deezerAgent", func() {
|
||||||
|
|
||||||
// Japanese returns empty biography
|
// Japanese returns empty biography
|
||||||
fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
|
fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
|
||||||
httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: 200}
|
httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: http.StatusOK}
|
||||||
// English returns full biography
|
// English returns full biography
|
||||||
fEn, _ := os.Open("tests/fixtures/deezer.artist.bio.en.json")
|
fEn, _ := os.Open("tests/fixtures/deezer.artist.bio.en.json")
|
||||||
httpClient.bioResponses["en"] = &http.Response{Body: fEn, StatusCode: 200}
|
httpClient.bioResponses["en"] = &http.Response{Body: fEn, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
|
bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
|
||||||
|
|
||||||
|
|
@ -226,9 +224,9 @@ var _ = Describe("deezerAgent", func() {
|
||||||
|
|
||||||
// Both languages return empty biography
|
// Both languages return empty biography
|
||||||
fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
|
fJa, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
|
||||||
httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: 200}
|
httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: http.StatusOK}
|
||||||
fXx, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
|
fXx, _ := os.Open("tests/fixtures/deezer.artist.bio.empty.json")
|
||||||
httpClient.bioResponses["xx"] = &http.Response{Body: fXx, StatusCode: 200}
|
httpClient.bioResponses["xx"] = &http.Response{Body: fXx, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
_, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
|
_, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
|
||||||
|
|
||||||
|
|
@ -261,7 +259,7 @@ func (c *langAwareHttpClient) Do(req *http.Request) (*http.Response, error) {
|
||||||
return c.searchResponse, nil
|
return c.searchResponse, nil
|
||||||
}
|
}
|
||||||
return &http.Response{
|
return &http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
@ -272,7 +270,7 @@ func (c *langAwareHttpClient) Do(req *http.Request) (*http.Response, error) {
|
||||||
return c.jwtResponse, nil
|
return c.jwtResponse, nil
|
||||||
}
|
}
|
||||||
return &http.Response{
|
return &http.Response{
|
||||||
StatusCode: 500,
|
StatusCode: http.StatusInternalServerError,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"error":"no mock"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"error":"no mock"}`)),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
@ -287,10 +285,11 @@ func (c *langAwareHttpClient) Do(req *http.Request) (*http.Response, error) {
|
||||||
}
|
}
|
||||||
// Return empty bio by default
|
// Return empty bio by default
|
||||||
return &http.Response{
|
return &http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"data":{"artist":{"bio":{"full":""}}}}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"data":{"artist":{"bio":{"full":""}}}}`)),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
panic("URL not mocked: " + req.URL.String())
|
Fail("URL not mocked: " + req.URL.String())
|
||||||
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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]
|
||||||
|
|
|
||||||
|
|
@ -20,13 +20,13 @@ func (t testFileInfo) BirthTime() time.Time {
|
||||||
if ts := times.Get(t.FileInfo); ts.HasBirthTime() {
|
if ts := times.Get(t.FileInfo); ts.HasBirthTime() {
|
||||||
return ts.BirthTime()
|
return ts.BirthTime()
|
||||||
}
|
}
|
||||||
return t.FileInfo.ModTime()
|
return t.ModTime()
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ = Describe("Extractor", func() {
|
var _ = Describe("Extractor", func() {
|
||||||
toP := func(name, sortName, mbid string) model.Participant {
|
toP := func(name, sortName, mbid string) model.Participant {
|
||||||
return model.Participant{
|
return model.Participant{
|
||||||
Artist: model.Artist{Name: name, SortArtistName: sortName, MbzArtistID: mbid},
|
Name: name, SortArtistName: sortName, MbzArtistID: mbid,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -90,7 +90,7 @@ var _ = Describe("Extractor", func() {
|
||||||
info.FileInfo = testFileInfo{FileInfo: fileInfo}
|
info.FileInfo = testFileInfo{FileInfo: fileInfo}
|
||||||
|
|
||||||
metadata := metadata.New(path, info)
|
metadata := metadata.New(path, info)
|
||||||
return new(metadata.ToMediaFile(1, "folderID"))
|
return new(metadata.ToMediaFile(model.Library{ID: 1}, "folderID"))
|
||||||
}
|
}
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
|
|
@ -156,7 +156,7 @@ var _ = Describe("Extractor", func() {
|
||||||
mf := parseTestFile("tests/fixtures/" + file)
|
mf := parseTestFile("tests/fixtures/" + file)
|
||||||
|
|
||||||
lyrics, err := mf.StructuredLyrics()
|
lyrics, err := mf.StructuredLyrics()
|
||||||
Expect(err).To(Not(HaveOccurred()))
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(lyrics).To(HaveLen(2))
|
Expect(lyrics).To(HaveLen(2))
|
||||||
|
|
||||||
unspec := makeLyrics("xxx", "unspecified")
|
unspec := makeLyrics("xxx", "unspecified")
|
||||||
|
|
@ -250,7 +250,7 @@ var _ = Describe("Extractor", func() {
|
||||||
|
|
||||||
// WMA has no Arranger role
|
// WMA has no Arranger role
|
||||||
if role == model.RoleArranger {
|
if role == model.RoleArranger {
|
||||||
Expect(actual).To(HaveLen(0))
|
Expect(actual).To(BeEmpty())
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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",
|
||||||
|
|
|
||||||
|
|
@ -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.
|
||||||
|
|
|
||||||
|
|
@ -49,15 +49,16 @@ type lastfmAgent struct {
|
||||||
getInfoMutex sync.Mutex
|
getInfoMutex sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func lastFMEnabled() bool {
|
||||||
|
return conf.Server().LastFM.Enabled && conf.Server().LastFM.ApiKey != "" && conf.Server().LastFM.Secret != ""
|
||||||
|
}
|
||||||
|
|
||||||
func lastFMConstructor(ds model.DataStore) *lastfmAgent {
|
func lastFMConstructor(ds model.DataStore) *lastfmAgent {
|
||||||
if !conf.Server.LastFM.Enabled || conf.Server.LastFM.ApiKey == "" || conf.Server.LastFM.Secret == "" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
l := &lastfmAgent{
|
l := &lastfmAgent{
|
||||||
ds: ds,
|
ds: ds,
|
||||||
languages: conf.Server.LastFM.Languages,
|
languages: conf.Server().LastFM.Languages,
|
||||||
apiKey: conf.Server.LastFM.ApiKey,
|
apiKey: conf.Server().LastFM.ApiKey,
|
||||||
secret: conf.Server.LastFM.Secret,
|
secret: conf.Server().LastFM.Secret,
|
||||||
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
|
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
|
||||||
}
|
}
|
||||||
hc := httpclient.New(consts.DefaultHttpClientTimeOut)
|
hc := httpclient.New(consts.DefaultHttpClientTimeOut)
|
||||||
|
|
@ -241,6 +242,10 @@ func (l *lastfmAgent) GetSimilarSongsByTrack(ctx context.Context, id, name, arti
|
||||||
var (
|
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
|
||||||
|
|
||||||
|
// errNoArtistPage is not a RetryLaterError on purpose: parking the agent would also stall its
|
||||||
|
// API-backed methods, which the page block does not affect.
|
||||||
|
errNoArtistPage = errors.New("no artist image in Last.fm page")
|
||||||
)
|
)
|
||||||
|
|
||||||
func (l *lastfmAgent) GetArtistImages(ctx context.Context, _, name, mbid string) ([]agents.ExternalImage, error) {
|
func (l *lastfmAgent) GetArtistImages(ctx context.Context, _, name, mbid string) ([]agents.ExternalImage, error) {
|
||||||
|
|
@ -267,7 +272,9 @@ func (l *lastfmAgent) GetArtistImages(ctx context.Context, _, name, mbid string)
|
||||||
var res []agents.ExternalImage
|
var res []agents.ExternalImage
|
||||||
n := cascadia.Query(node, artistOpenGraphQuery)
|
n := cascadia.Query(node, artistOpenGraphQuery)
|
||||||
if n == nil {
|
if n == nil {
|
||||||
return res, nil
|
// A real artist page always has og:image; its absence means a bot challenge or a redesign.
|
||||||
|
log.Warn(ctx, "Last.fm did not return a usable artist page", "name", name, "url", a.URL)
|
||||||
|
return nil, errNoArtistPage
|
||||||
}
|
}
|
||||||
for _, attr := range n.Attr {
|
for _, attr := range n.Attr {
|
||||||
if attr.Key != "content" {
|
if attr.Key != "content" {
|
||||||
|
|
@ -348,7 +355,7 @@ func (l *lastfmAgent) callTrackGetSimilar(ctx context.Context, name, artist stri
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *lastfmAgent) getArtistForScrobble(track *model.MediaFile, role model.Role, displayName string) string {
|
func (l *lastfmAgent) getArtistForScrobble(track *model.MediaFile, role model.Role, displayName string) string {
|
||||||
if conf.Server.LastFM.ScrobbleFirstArtistOnly && len(track.Participants[role]) > 0 {
|
if conf.Server().LastFM.ScrobbleFirstArtistOnly && len(track.Participants[role]) > 0 {
|
||||||
return track.Participants[role][0].Name
|
return track.Participants[role][0].Name
|
||||||
}
|
}
|
||||||
return displayName
|
return displayName
|
||||||
|
|
@ -382,10 +389,11 @@ func (l *lastfmAgent) Scrobble(ctx context.Context, userId string, s scrobbler.S
|
||||||
return errors.Join(err, scrobbler.ErrNotAuthorized)
|
return errors.Join(err, scrobbler.ErrNotAuthorized)
|
||||||
}
|
}
|
||||||
|
|
||||||
if s.Duration <= 30 {
|
if s.Duration <= float32(conf.Server().LastFM.MinScrobbleDuration.Seconds()) {
|
||||||
log.Debug(ctx, "Skipping Last.fm scrobble for short song", "track", s.Title, "duration", s.Duration)
|
log.Debug(ctx, "Skipping Last.fm scrobble for short song", "track", s.Title, "duration", s.Duration)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
err = l.client.scrobble(ctx, sk, ScrobbleInfo{
|
err = l.client.scrobble(ctx, sk, ScrobbleInfo{
|
||||||
artist: l.getArtistForScrobble(&s.MediaFile, model.RoleArtist, s.Artist),
|
artist: l.getArtistForScrobble(&s.MediaFile, model.RoleArtist, s.Artist),
|
||||||
track: s.Title,
|
track: s.Title,
|
||||||
|
|
@ -424,22 +432,16 @@ func (l *lastfmAgent) PlaybackReport(context.Context, scrobbler.PlaybackSession)
|
||||||
func init() {
|
func init() {
|
||||||
conf.AddHook(func() {
|
conf.AddHook(func() {
|
||||||
agents.Register(lastFMAgentName, func(ds model.DataStore) agents.Interface {
|
agents.Register(lastFMAgentName, func(ds model.DataStore) agents.Interface {
|
||||||
// This is a workaround for the fact that a (Interface)(nil) is not the same as a (*lastfmAgent)(nil)
|
if !lastFMEnabled() {
|
||||||
// See https://go.dev/doc/faq#nil_error
|
|
||||||
a := lastFMConstructor(ds)
|
|
||||||
if a != nil {
|
|
||||||
return a
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
|
}
|
||||||
|
return lastFMConstructor(ds)
|
||||||
})
|
})
|
||||||
scrobbler.Register(lastFMAgentName, func(ds model.DataStore) scrobbler.Scrobbler {
|
scrobbler.Register(lastFMAgentName, func(ds model.DataStore) scrobbler.Scrobbler {
|
||||||
// Same as above - this is a workaround for the fact that a (Scrobbler)(nil) is not the same as a (*lastfmAgent)(nil)
|
if !lastFMEnabled() {
|
||||||
// See https://go.dev/doc/faq#nil_error
|
|
||||||
a := lastFMConstructor(ds)
|
|
||||||
if a != nil {
|
|
||||||
return a
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
|
}
|
||||||
|
return lastFMConstructor(ds)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,6 @@ import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/conf"
|
"github.com/navidrome/navidrome/conf"
|
||||||
"github.com/navidrome/navidrome/conf/configtest"
|
|
||||||
"github.com/navidrome/navidrome/core/agents"
|
"github.com/navidrome/navidrome/core/agents"
|
||||||
"github.com/navidrome/navidrome/core/scrobbler"
|
"github.com/navidrome/navidrome/core/scrobbler"
|
||||||
"github.com/navidrome/navidrome/model"
|
"github.com/navidrome/navidrome/model"
|
||||||
|
|
@ -30,41 +29,39 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
var ds model.DataStore
|
var ds model.DataStore
|
||||||
var ctx context.Context
|
var ctx context.Context
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
ds = &tests.MockDataStore{}
|
ds = &tests.MockDataStore{}
|
||||||
ctx = context.Background()
|
conf.Update(func(c *conf.Options) {
|
||||||
DeferCleanup(configtest.SetupConfig())
|
c.LastFM.Enabled = true
|
||||||
conf.Server.LastFM.Enabled = true
|
c.LastFM.ApiKey = "123"
|
||||||
conf.Server.LastFM.ApiKey = "123"
|
c.LastFM.Secret = "secret"
|
||||||
conf.Server.LastFM.Secret = "secret"
|
})
|
||||||
})
|
})
|
||||||
Describe("lastFMConstructor", func() {
|
Describe("lastFMConstructor", func() {
|
||||||
When("Agent is properly configured", func() {
|
When("Agent is properly configured", func() {
|
||||||
It("uses configured api key and languages", func() {
|
It("uses configured api key and languages", func() {
|
||||||
conf.Server.LastFM.Languages = []string{"pt", "en"}
|
conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"pt", "en"} })
|
||||||
agent := lastFMConstructor(ds)
|
agent := lastFMConstructor(ds)
|
||||||
Expect(agent.apiKey).To(Equal("123"))
|
Expect(agent.apiKey).To(Equal("123"))
|
||||||
Expect(agent.secret).To(Equal("secret"))
|
Expect(agent.secret).To(Equal("secret"))
|
||||||
Expect(agent.languages).To(Equal([]string{"pt", "en"}))
|
Expect(agent.languages).To(Equal([]string{"pt", "en"}))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
When("Agent is disabled", func() {
|
|
||||||
It("returns nil", func() {
|
|
||||||
conf.Server.LastFM.Enabled = false
|
|
||||||
Expect(lastFMConstructor(ds)).To(BeNil())
|
|
||||||
})
|
|
||||||
})
|
|
||||||
When("ApiKey is empty", func() {
|
|
||||||
It("returns nil", func() {
|
|
||||||
conf.Server.LastFM.ApiKey = ""
|
|
||||||
Expect(lastFMConstructor(ds)).To(BeNil())
|
|
||||||
})
|
|
||||||
})
|
|
||||||
When("Secret is empty", func() {
|
|
||||||
It("returns nil", func() {
|
|
||||||
conf.Server.LastFM.Secret = ""
|
|
||||||
Expect(lastFMConstructor(ds)).To(BeNil())
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
Describe("lastFMEnabled", func() {
|
||||||
|
It("is true when enabled with an api key and secret", func() {
|
||||||
|
Expect(lastFMEnabled()).To(BeTrue())
|
||||||
})
|
})
|
||||||
|
DescribeTable("is false when the configuration is incomplete",
|
||||||
|
func(change func(*conf.Options)) {
|
||||||
|
conf.Update(change)
|
||||||
|
Expect(lastFMEnabled()).To(BeFalse())
|
||||||
|
},
|
||||||
|
Entry("disabled", func(c *conf.Options) { c.LastFM.Enabled = false }),
|
||||||
|
Entry("no api key", func(c *conf.Options) { c.LastFM.ApiKey = "" }),
|
||||||
|
Entry("no secret", func(c *conf.Options) { c.LastFM.Secret = "" }),
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
Describe("GetArtistBiography", func() {
|
Describe("GetArtistBiography", func() {
|
||||||
|
|
@ -79,7 +76,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
|
|
||||||
It("returns the biography", func() {
|
It("returns the biography", func() {
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
|
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
Expect(agent.GetArtistBiography(ctx, "123", "U2", "")).To(Equal("U2 é uma das mais importantes bandas de rock de todos os tempos. Formada em 1976 em Dublin, composta por Bono (vocalista e guitarrista), The Edge (guitarrista, pianista e backing vocal), Adam Clayton (baixista), Larry Mullen, Jr. (baterista e percussionista).\n\nDesde a década de 80, U2 é uma das bandas mais populares no mundo. Seus shows são únicos e um verdadeiro festival de efeitos especiais, além de serem um dos que mais arrecadam anualmente."))
|
Expect(agent.GetArtistBiography(ctx, "123", "U2", "")).To(Equal("U2 é uma das mais importantes bandas de rock de todos os tempos. Formada em 1976 em Dublin, composta por Bono (vocalista e guitarrista), The Edge (guitarrista, pianista e backing vocal), Adam Clayton (baixista), Larry Mullen, Jr. (baterista e percussionista).\n\nDesde a década de 80, U2 é uma das bandas mais populares no mundo. Seus shows são únicos e um verdadeiro festival de efeitos especiais, além de serem um dos que mais arrecadam anualmente."))
|
||||||
Expect(httpClient.RequestCount).To(Equal(1))
|
Expect(httpClient.RequestCount).To(Equal(1))
|
||||||
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("U2"))
|
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("U2"))
|
||||||
|
|
@ -94,7 +91,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("returns an error if Last.fm call returns an error", func() {
|
It("returns an error if Last.fm call returns an error", func() {
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
|
||||||
_, err := agent.GetArtistBiography(ctx, "123", "U2", "")
|
_, err := agent.GetArtistBiography(ctx, "123", "U2", "")
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
Expect(httpClient.RequestCount).To(Equal(1))
|
Expect(httpClient.RequestCount).To(Equal(1))
|
||||||
|
|
@ -104,7 +101,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() {
|
It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)),
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
}
|
}
|
||||||
_, err := agent.GetArtistBiography(ctx, "123", "U2", "")
|
_, err := agent.GetArtistBiography(ctx, "123", "U2", "")
|
||||||
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
||||||
|
|
@ -121,13 +118,13 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("returns content in first language when available (1 API call)", func() {
|
It("returns content in first language when available (1 API call)", func() {
|
||||||
conf.Server.LastFM.Languages = []string{"pt", "en"}
|
conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"pt", "en"} })
|
||||||
agent = lastFMConstructor(ds)
|
agent = lastFMConstructor(ds)
|
||||||
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
||||||
|
|
||||||
// Portuguese biography available
|
// Portuguese biography available
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
|
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
|
||||||
httpClient.responses["pt"] = http.Response{Body: f, StatusCode: 200}
|
httpClient.responses["pt"] = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
bio, err := agent.GetArtistBiography(ctx, "123", "U2", "")
|
bio, err := agent.GetArtistBiography(ctx, "123", "U2", "")
|
||||||
|
|
||||||
|
|
@ -138,16 +135,16 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("falls back to second language when first returns empty (2 API calls)", func() {
|
It("falls back to second language when first returns empty (2 API calls)", func() {
|
||||||
conf.Server.LastFM.Languages = []string{"ja", "en"}
|
conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "en"} })
|
||||||
agent = lastFMConstructor(ds)
|
agent = lastFMConstructor(ds)
|
||||||
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
||||||
|
|
||||||
// Japanese returns empty/ignored biography (actual Last.fm response with just "Read more" link)
|
// Japanese returns empty/ignored biography (actual Last.fm response with just "Read more" link)
|
||||||
fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
|
fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
|
||||||
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
|
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: http.StatusOK}
|
||||||
// English returns full biography
|
// English returns full biography
|
||||||
fEn, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.en.json")
|
fEn, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.en.json")
|
||||||
httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: 200}
|
httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
bio, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "")
|
bio, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "")
|
||||||
|
|
||||||
|
|
@ -159,16 +156,16 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("returns ErrNotFound when all languages return empty", func() {
|
It("returns ErrNotFound when all languages return empty", func() {
|
||||||
conf.Server.LastFM.Languages = []string{"ja", "xx"}
|
conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "xx"} })
|
||||||
agent = lastFMConstructor(ds)
|
agent = lastFMConstructor(ds)
|
||||||
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
||||||
|
|
||||||
// Both languages return empty/ignored biography (using actual Last.fm response format)
|
// Both languages return empty/ignored biography (using actual Last.fm response format)
|
||||||
fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
|
fJa, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
|
||||||
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
|
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: http.StatusOK}
|
||||||
// Second language also returns empty
|
// Second language also returns empty
|
||||||
fXx, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
|
fXx, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.empty.json")
|
||||||
httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: 200}
|
httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
_, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "")
|
_, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "")
|
||||||
|
|
||||||
|
|
@ -186,16 +183,16 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("falls back to second language when first returns empty description (2 API calls)", func() {
|
It("falls back to second language when first returns empty description (2 API calls)", func() {
|
||||||
conf.Server.LastFM.Languages = []string{"ja", "en"}
|
conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "en"} })
|
||||||
agent = lastFMConstructor(ds)
|
agent = lastFMConstructor(ds)
|
||||||
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
||||||
|
|
||||||
// Japanese returns album without wiki/description (actual Last.fm response)
|
// Japanese returns album without wiki/description (actual Last.fm response)
|
||||||
fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
|
fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
|
||||||
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
|
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: http.StatusOK}
|
||||||
// English returns album with description
|
// English returns album with description
|
||||||
fEn, _ := os.Open("tests/fixtures/lastfm.album.getinfo.en.json")
|
fEn, _ := os.Open("tests/fixtures/lastfm.album.getinfo.en.json")
|
||||||
httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: 200}
|
httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "")
|
albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "")
|
||||||
|
|
||||||
|
|
@ -208,15 +205,15 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("returns album without description when all languages return empty", func() {
|
It("returns album without description when all languages return empty", func() {
|
||||||
conf.Server.LastFM.Languages = []string{"ja", "xx"}
|
conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "xx"} })
|
||||||
agent = lastFMConstructor(ds)
|
agent = lastFMConstructor(ds)
|
||||||
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
agent.client = newClient("API_KEY", "SECRET", httpClient)
|
||||||
|
|
||||||
// Both languages return album without description
|
// Both languages return album without description
|
||||||
fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
|
fJa, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
|
||||||
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
|
httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: http.StatusOK}
|
||||||
fXx, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
|
fXx, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty.json")
|
||||||
httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: 200}
|
httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "")
|
albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "")
|
||||||
|
|
||||||
|
|
@ -240,7 +237,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
|
|
||||||
It("returns similar artists", func() {
|
It("returns similar artists", func() {
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
|
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
Expect(agent.GetSimilarArtists(ctx, "123", "U2", "", 2)).To(Equal([]agents.Artist{
|
Expect(agent.GetSimilarArtists(ctx, "123", "U2", "", 2)).To(Equal([]agents.Artist{
|
||||||
{Name: "Passengers", MBID: "e110c11f-1c94-4471-a350-c38f46b29389"},
|
{Name: "Passengers", MBID: "e110c11f-1c94-4471-a350-c38f46b29389"},
|
||||||
{Name: "INXS", MBID: "481bf5f9-2e7c-4c44-b08a-05b32bc7c00d"},
|
{Name: "INXS", MBID: "481bf5f9-2e7c-4c44-b08a-05b32bc7c00d"},
|
||||||
|
|
@ -258,7 +255,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("returns an error if Last.fm call returns an error", func() {
|
It("returns an error if Last.fm call returns an error", func() {
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
|
||||||
_, err := agent.GetSimilarArtists(ctx, "123", "U2", "", 2)
|
_, err := agent.GetSimilarArtists(ctx, "123", "U2", "", 2)
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
Expect(httpClient.RequestCount).To(Equal(1))
|
Expect(httpClient.RequestCount).To(Equal(1))
|
||||||
|
|
@ -278,7 +275,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
|
|
||||||
It("returns top songs", func() {
|
It("returns top songs", func() {
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
|
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
Expect(agent.GetArtistTopSongs(ctx, "123", "U2", "", 2)).To(Equal([]agents.Song{
|
Expect(agent.GetArtistTopSongs(ctx, "123", "U2", "", 2)).To(Equal([]agents.Song{
|
||||||
{Name: "Beautiful Day", MBID: "f7f264d0-a89b-4682-9cd7-a4e7c37637af"},
|
{Name: "Beautiful Day", MBID: "f7f264d0-a89b-4682-9cd7-a4e7c37637af"},
|
||||||
{Name: "With or Without You", MBID: "6b9a509f-6907-4a6e-9345-2f12da09ba4b"},
|
{Name: "With or Without You", MBID: "6b9a509f-6907-4a6e-9345-2f12da09ba4b"},
|
||||||
|
|
@ -296,7 +293,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("returns an error if Last.fm call returns an error", func() {
|
It("returns an error if Last.fm call returns an error", func() {
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
|
||||||
_, err := agent.GetArtistTopSongs(ctx, "123", "U2", "", 2)
|
_, err := agent.GetArtistTopSongs(ctx, "123", "U2", "", 2)
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
Expect(httpClient.RequestCount).To(Equal(1))
|
Expect(httpClient.RequestCount).To(Equal(1))
|
||||||
|
|
@ -316,7 +313,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
|
|
||||||
It("returns similar songs", func() {
|
It("returns similar songs", func() {
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
|
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
Expect(agent.GetSimilarSongsByTrack(ctx, "123", "Just Can't Get Enough", "Depeche Mode", "", 5)).To(Equal([]agents.Song{
|
Expect(agent.GetSimilarSongsByTrack(ctx, "123", "Just Can't Get Enough", "Depeche Mode", "", 5)).To(Equal([]agents.Song{
|
||||||
{Name: "Dreaming of Me", MBID: "027b553e-7c74-3ed4-a95e-1d4fea51f174", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"}}},
|
{Name: "Dreaming of Me", MBID: "027b553e-7c74-3ed4-a95e-1d4fea51f174", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"}}},
|
||||||
{Name: "Everything Counts", MBID: "5a5a3ca4-bdb8-4641-a674-9b54b9b319a6", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"}}},
|
{Name: "Everything Counts", MBID: "5a5a3ca4-bdb8-4641-a674-9b54b9b319a6", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "8538e728-ca0b-4321-b7e5-cff6565dd4c0"}}},
|
||||||
|
|
@ -331,7 +328,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
|
|
||||||
It("returns ErrNotFound when no similar songs found", func() {
|
It("returns ErrNotFound when no similar songs found", func() {
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json")
|
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
_, err := agent.GetSimilarSongsByTrack(ctx, "123", "UnknownTrack", "UnknownArtist", "", 3)
|
_, err := agent.GetSimilarSongsByTrack(ctx, "123", "UnknownTrack", "UnknownArtist", "", 3)
|
||||||
Expect(err).To(MatchError(agents.ErrNotFound))
|
Expect(err).To(MatchError(agents.ErrNotFound))
|
||||||
Expect(httpClient.RequestCount).To(Equal(1))
|
Expect(httpClient.RequestCount).To(Equal(1))
|
||||||
|
|
@ -345,7 +342,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("returns an error if Last.fm call returns an error", func() {
|
It("returns an error if Last.fm call returns an error", func() {
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
|
||||||
_, err := agent.GetSimilarSongsByTrack(ctx, "123", "Believe", "Cher", "", 3)
|
_, err := agent.GetSimilarSongsByTrack(ctx, "123", "Believe", "Cher", "", 3)
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
Expect(httpClient.RequestCount).To(Equal(1))
|
Expect(httpClient.RequestCount).To(Equal(1))
|
||||||
|
|
@ -357,7 +354,7 @@ 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(ctx).Put("user-1", sessionKeyProperty, "SK-1")
|
_ = ds.UserProps().Put(ctx, "user-1", sessionKeyProperty, "SK-1")
|
||||||
httpClient = &tests.FakeHttpClient{}
|
httpClient = &tests.FakeHttpClient{}
|
||||||
client := newClient("API_KEY", "SECRET", httpClient)
|
client := newClient("API_KEY", "SECRET", httpClient)
|
||||||
agent = lastFMConstructor(ds)
|
agent = lastFMConstructor(ds)
|
||||||
|
|
@ -373,12 +370,12 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
MbzRecordingID: "mbz-123",
|
MbzRecordingID: "mbz-123",
|
||||||
Participants: map[model.Role]model.ParticipantList{
|
Participants: map[model.Role]model.ParticipantList{
|
||||||
model.RoleArtist: []model.Participant{
|
model.RoleArtist: []model.Participant{
|
||||||
{Artist: model.Artist{ID: "ar-1", Name: "First Artist"}},
|
{ID: "ar-1", Name: "First Artist"},
|
||||||
{Artist: model.Artist{ID: "ar-2", Name: "Second Artist"}},
|
{ID: "ar-2", Name: "Second Artist"},
|
||||||
},
|
},
|
||||||
model.RoleAlbumArtist: []model.Participant{
|
model.RoleAlbumArtist: []model.Participant{
|
||||||
{Artist: model.Artist{ID: "ar-1", Name: "First Album Artist"}},
|
{ID: "ar-1", Name: "First Album Artist"},
|
||||||
{Artist: model.Artist{ID: "ar-2", Name: "Second Album Artist"}},
|
{ID: "ar-2", Name: "Second Album Artist"},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
@ -386,7 +383,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
|
|
||||||
Describe("NowPlaying", func() {
|
Describe("NowPlaying", func() {
|
||||||
It("calls Last.fm with correct params", func() {
|
It("calls Last.fm with correct params", func() {
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
|
||||||
|
|
||||||
err := agent.NowPlaying(ctx, "user-1", track, 0)
|
err := agent.NowPlaying(ctx, "user-1", track, 0)
|
||||||
|
|
||||||
|
|
@ -412,11 +409,11 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
|
|
||||||
When("ScrobbleFirstArtistOnly is true", func() {
|
When("ScrobbleFirstArtistOnly is true", func() {
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
conf.Server.LastFM.ScrobbleFirstArtistOnly = true
|
conf.Update(func(c *conf.Options) { c.LastFM.ScrobbleFirstArtistOnly = true })
|
||||||
})
|
})
|
||||||
|
|
||||||
It("uses only the first artist", func() {
|
It("uses only the first artist", func() {
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
|
||||||
|
|
||||||
err := agent.NowPlaying(ctx, "user-1", track, 0)
|
err := agent.NowPlaying(ctx, "user-1", track, 0)
|
||||||
|
|
||||||
|
|
@ -432,7 +429,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
Describe("scrobble", func() {
|
Describe("scrobble", func() {
|
||||||
It("calls Last.fm with correct params", func() {
|
It("calls Last.fm with correct params", func() {
|
||||||
ts := time.Now()
|
ts := time.Now()
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: ts})
|
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: ts})
|
||||||
|
|
||||||
|
|
@ -454,12 +451,12 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
|
|
||||||
When("ScrobbleFirstArtistOnly is true", func() {
|
When("ScrobbleFirstArtistOnly is true", func() {
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
conf.Server.LastFM.ScrobbleFirstArtistOnly = true
|
conf.Update(func(c *conf.Options) { c.LastFM.ScrobbleFirstArtistOnly = true })
|
||||||
})
|
})
|
||||||
|
|
||||||
It("uses only the first artist", func() {
|
It("uses only the first artist", func() {
|
||||||
ts := time.Now()
|
ts := time.Now()
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: ts})
|
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: ts})
|
||||||
|
|
||||||
|
|
@ -471,9 +468,9 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
It("skips songs with less than 31 seconds", func() {
|
It("skips songs at the 30-second minimum", func() {
|
||||||
track.Duration = 29
|
track.Duration = 30
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||||
|
|
||||||
|
|
@ -481,6 +478,46 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
Expect(httpClient.SavedRequest).To(BeNil())
|
Expect(httpClient.SavedRequest).To(BeNil())
|
||||||
})
|
})
|
||||||
|
|
||||||
|
It("sends the duration parameter for a 30.5-second song", func() {
|
||||||
|
track.Duration = 30.5
|
||||||
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"scrobbles":{"scrobble":{"ignoredMessage":{"code":"0"}},"@attr":{"accepted":1}}}`)), StatusCode: http.StatusOK}
|
||||||
|
|
||||||
|
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||||
|
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
||||||
|
body, _ := io.ReadAll(httpClient.SavedRequest.Body)
|
||||||
|
sentParams, _ := url.ParseQuery(string(body))
|
||||||
|
Expect(sentParams.Has("duration")).To(BeTrue())
|
||||||
|
Expect(sentParams.Get("duration")).To(Equal("30"))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("skips songs according to the configured minimum duration", func() {
|
||||||
|
conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 60 * time.Second })
|
||||||
|
track.Duration = 59
|
||||||
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
|
||||||
|
|
||||||
|
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||||
|
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
Expect(httpClient.SavedRequest).To(BeNil())
|
||||||
|
})
|
||||||
|
|
||||||
|
It("does not skip short songs when the minimum duration is disabled", func() {
|
||||||
|
conf.Update(func(c *conf.Options) { c.LastFM.MinScrobbleDuration = 0 })
|
||||||
|
track.Duration = 29
|
||||||
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
|
||||||
|
|
||||||
|
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||||
|
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
Expect(httpClient.SavedRequest).ToNot(BeNil())
|
||||||
|
|
||||||
|
body, _ := io.ReadAll(httpClient.SavedRequest.Body)
|
||||||
|
sentParams, _ := url.ParseQuery(string(body))
|
||||||
|
Expect(sentParams.Has("duration")).To(BeFalse())
|
||||||
|
})
|
||||||
|
|
||||||
It("returns ErrNotAuthorized if user is not linked", func() {
|
It("returns ErrNotAuthorized if user is not linked", func() {
|
||||||
err := agent.Scrobble(ctx, "user-2", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
err := agent.Scrobble(ctx, "user-2", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||||
Expect(err).To(MatchError(scrobbler.ErrNotAuthorized))
|
Expect(err).To(MatchError(scrobbler.ErrNotAuthorized))
|
||||||
|
|
@ -489,7 +526,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
It("returns ErrRetryLater on error 11", func() {
|
It("returns ErrRetryLater on error 11", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"error":11,"message":"Service Offline - This service is temporarily offline. Try again later."}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"error":11,"message":"Service Offline - This service is temporarily offline. Try again later."}`)),
|
||||||
StatusCode: 400,
|
StatusCode: http.StatusBadRequest,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||||
|
|
@ -499,7 +536,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
It("returns ErrRetryLater on error 16", func() {
|
It("returns ErrRetryLater on error 16", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"error":16,"message":"There was a temporary error processing your request. Please try again"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"error":16,"message":"There was a temporary error processing your request. Please try again"}`)),
|
||||||
StatusCode: 400,
|
StatusCode: http.StatusBadRequest,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||||
|
|
@ -509,7 +546,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() {
|
It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)),
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||||
|
|
@ -519,7 +556,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
It("returns ErrRetryLater on http errors", func() {
|
It("returns ErrRetryLater on http errors", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`internal server error`)),
|
Body: io.NopCloser(bytes.NewBufferString(`internal server error`)),
|
||||||
StatusCode: 500,
|
StatusCode: http.StatusInternalServerError,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||||
|
|
@ -529,7 +566,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
It("returns ErrUnrecoverable on other errors", func() {
|
It("returns ErrUnrecoverable on other errors", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"error":8,"message":"Operation failed - Something else went wrong"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"error":8,"message":"Operation failed - Something else went wrong"}`)),
|
||||||
StatusCode: 400,
|
StatusCode: http.StatusBadRequest,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
|
||||||
|
|
@ -550,7 +587,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
|
|
||||||
It("returns the biography", func() {
|
It("returns the biography", func() {
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
|
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
Expect(agent.GetAlbumInfo(ctx, "Believe", "Cher", "03c91c40-49a6-44a7-90e7-a700edf97a62")).To(Equal(&agents.AlbumInfo{
|
Expect(agent.GetAlbumInfo(ctx, "Believe", "Cher", "03c91c40-49a6-44a7-90e7-a700edf97a62")).To(Equal(&agents.AlbumInfo{
|
||||||
Name: "Believe",
|
Name: "Believe",
|
||||||
MBID: "03c91c40-49a6-44a7-90e7-a700edf97a62",
|
MBID: "03c91c40-49a6-44a7-90e7-a700edf97a62",
|
||||||
|
|
@ -566,7 +603,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
|
|
||||||
It("returns empty images if no images are available", func() {
|
It("returns empty images if no images are available", func() {
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty_urls.json")
|
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.empty_urls.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
Expect(agent.GetAlbumInfo(ctx, "The Definitive Less Damage And More Joy", "The Jesus and Mary Chain", "")).To(Equal(&agents.AlbumInfo{
|
Expect(agent.GetAlbumInfo(ctx, "The Definitive Less Damage And More Joy", "The Jesus and Mary Chain", "")).To(Equal(&agents.AlbumInfo{
|
||||||
Name: "The Definitive Less Damage And More Joy",
|
Name: "The Definitive Less Damage And More Joy",
|
||||||
URL: "https://www.last.fm/music/The+Jesus+and+Mary+Chain/The+Definitive+Less+Damage+And+More+Joy",
|
URL: "https://www.last.fm/music/The+Jesus+and+Mary+Chain/The+Definitive+Less+Damage+And+More+Joy",
|
||||||
|
|
@ -584,7 +621,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("returns an error if Last.fm call returns an error", func() {
|
It("returns an error if Last.fm call returns an error", func() {
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: http.StatusOK}
|
||||||
_, err := agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234")
|
_, err := agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234")
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
Expect(httpClient.RequestCount).To(Equal(1))
|
Expect(httpClient.RequestCount).To(Equal(1))
|
||||||
|
|
@ -592,7 +629,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("returns an error when Last.fm returns an error 6 (album not found)", func() {
|
It("returns an error when Last.fm returns an error 6 (album not found)", func() {
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: http.StatusOK}
|
||||||
_, err := agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234")
|
_, err := agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234")
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
// A definitive not-found must satisfy the sentinel, or the artwork worker retries it.
|
// A definitive not-found must satisfy the sentinel, or the artwork worker retries it.
|
||||||
|
|
@ -618,10 +655,10 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
|
|
||||||
It("returns the artist image from the page", func() {
|
It("returns the artist image from the page", func() {
|
||||||
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
|
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
|
||||||
apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
|
apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.html")
|
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.html")
|
||||||
httpClient.Res = http.Response{Body: fScraper, StatusCode: 200}
|
httpClient.Res = http.Response{Body: fScraper, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
images, err := agent.GetArtistImages(ctx, "123", "U2", "")
|
images, err := agent.GetArtistImages(ctx, "123", "U2", "")
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
@ -630,7 +667,7 @@ var _ = Describe("lastfmAgent", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("maps a Last.fm error 6 (artist not found) to the shared not-found sentinel", func() {
|
It("maps a Last.fm error 6 (artist not found) to the shared not-found sentinel", func() {
|
||||||
apiClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: 200}
|
apiClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: http.StatusOK}
|
||||||
_, err := agent.GetArtistImages(ctx, "123", "Nonexistent Artist", "")
|
_, err := agent.GetArtistImages(ctx, "123", "Nonexistent Artist", "")
|
||||||
// Not a fault: runs of missing artists must not trip the worker's circuit breaker.
|
// Not a fault: runs of missing artists must not trip the worker's circuit breaker.
|
||||||
Expect(errors.Is(err, agents.ErrNotFound)).To(BeTrue())
|
Expect(errors.Is(err, agents.ErrNotFound)).To(BeTrue())
|
||||||
|
|
@ -638,28 +675,51 @@ 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())
|
||||||
Expect(images).To(BeEmpty())
|
Expect(images).To(BeEmpty())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("returns empty list if 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", "")
|
||||||
|
Expect(err).To(MatchError(errNoArtistPage))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("errors when Last.fm serves a bot challenge page", func() {
|
||||||
|
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
|
||||||
|
apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
|
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.challenge.html")
|
||||||
|
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).To(MatchError(errNoArtistPage))
|
||||||
Expect(images).To(BeEmpty())
|
Expect(images).To(BeEmpty())
|
||||||
})
|
})
|
||||||
|
|
||||||
|
It("does not park the agent: the failure is not a retry-later", func() {
|
||||||
|
// A RetryLaterError would cool down the agent's API-backed methods too.
|
||||||
|
fApi, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
|
||||||
|
apiClient.Res = http.Response{Body: fApi, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
|
fScraper, _ := os.Open("tests/fixtures/lastfm.artist.page.challenge.html")
|
||||||
|
httpClient.Res = http.Response{Body: fScraper, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
|
_, err := agent.GetArtistImages(ctx, "123", "U2", "")
|
||||||
|
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeFalse())
|
||||||
|
})
|
||||||
|
|
||||||
It("returns error if API call fails", func() {
|
It("returns error if API call fails", func() {
|
||||||
apiClient.Err = errors.New("api error")
|
apiClient.Err = errors.New("api error")
|
||||||
_, err := agent.GetArtistImages(ctx, "123", "U2", "")
|
_, err := agent.GetArtistImages(ctx, "123", "U2", "")
|
||||||
|
|
@ -669,7 +729,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", "")
|
||||||
|
|
@ -702,7 +762,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
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -37,8 +37,8 @@ type Router struct {
|
||||||
func NewRouter(ds model.DataStore) *Router {
|
func NewRouter(ds model.DataStore) *Router {
|
||||||
r := &Router{
|
r := &Router{
|
||||||
ds: ds,
|
ds: ds,
|
||||||
apiKey: conf.Server.LastFM.ApiKey,
|
apiKey: conf.Server().LastFM.ApiKey,
|
||||||
secret: conf.Server.LastFM.Secret,
|
secret: conf.Server().LastFM.Secret,
|
||||||
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
|
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
|
||||||
}
|
}
|
||||||
r.Handler = r.routes()
|
r.Handler = r.routes()
|
||||||
|
|
@ -122,7 +122,7 @@ func (s *Router) callback(w http.ResponseWriter, r *http.Request) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
_, _ = w.Write([]byte("An error occurred while authorizing with Last.fm. \n\nRequest ID: " + middleware.GetReqID(ctx))) //nolint:gosec
|
_, _ = w.Write([]byte("An error occurred while authorizing with Last.fm. \n\nRequest ID: " + middleware.GetReqID(ctx)))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -132,7 +132,7 @@ func (s *Router) callback(w http.ResponseWriter, r *http.Request) {
|
||||||
func (s *Router) fetchSessionKey(ctx context.Context, uid, token string) error {
|
func (s *Router) fetchSessionKey(ctx context.Context, uid, token string) error {
|
||||||
sessionKey, err := s.client.getSession(ctx, token)
|
sessionKey, err := s.client.getSession(ctx, token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error(ctx, "Could not fetch LastFM session key", "userId", uid, "token", token,
|
log.Error(ctx, "Could not fetch LastFM session key", "userId", uid,
|
||||||
"requestId", middleware.GetReqID(ctx), err)
|
"requestId", middleware.GetReqID(ctx), err)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -50,14 +50,14 @@ var _ = Describe("auth_router", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
storedSessionKey := func(userID string) string {
|
storedSessionKey := func(userID string) string {
|
||||||
key, _ := userProps.Get(userID, sessionKeyProperty)
|
key, _ := 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 +74,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())
|
||||||
|
|
|
||||||
|
|
@ -49,6 +49,12 @@ type client struct {
|
||||||
hc httpDoer
|
hc httpDoer
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// escapePlus works around Last.fm decoding artist.* and track.* params twice, turning "+" into a space.
|
||||||
|
// album.getInfo decodes only once, so it must not use this.
|
||||||
|
func escapePlus(s string) string {
|
||||||
|
return strings.ReplaceAll(s, "+", "%2B")
|
||||||
|
}
|
||||||
|
|
||||||
func (c *client) albumGetInfo(ctx context.Context, name string, artist string, mbid string, lang string) (*Album, error) {
|
func (c *client) albumGetInfo(ctx context.Context, name string, artist string, mbid string, lang string) (*Album, error) {
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Add("method", "album.getInfo")
|
params.Add("method", "album.getInfo")
|
||||||
|
|
@ -66,7 +72,7 @@ func (c *client) albumGetInfo(ctx context.Context, name string, artist string, m
|
||||||
func (c *client) artistGetInfo(ctx context.Context, name string, lang string) (*Artist, error) {
|
func (c *client) artistGetInfo(ctx context.Context, name string, lang string) (*Artist, error) {
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Add("method", "artist.getInfo")
|
params.Add("method", "artist.getInfo")
|
||||||
params.Add("artist", name)
|
params.Add("artist", escapePlus(name))
|
||||||
params.Add("lang", lang)
|
params.Add("lang", lang)
|
||||||
response, err := c.makeRequest(ctx, http.MethodGet, params, false)
|
response, err := c.makeRequest(ctx, http.MethodGet, params, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -78,7 +84,7 @@ func (c *client) artistGetInfo(ctx context.Context, name string, lang string) (*
|
||||||
func (c *client) artistGetSimilar(ctx context.Context, name string, limit int) (*SimilarArtists, error) {
|
func (c *client) artistGetSimilar(ctx context.Context, name string, limit int) (*SimilarArtists, error) {
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Add("method", "artist.getSimilar")
|
params.Add("method", "artist.getSimilar")
|
||||||
params.Add("artist", name)
|
params.Add("artist", escapePlus(name))
|
||||||
params.Add("limit", strconv.Itoa(limit))
|
params.Add("limit", strconv.Itoa(limit))
|
||||||
response, err := c.makeRequest(ctx, http.MethodGet, params, false)
|
response, err := c.makeRequest(ctx, http.MethodGet, params, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -90,7 +96,7 @@ func (c *client) artistGetSimilar(ctx context.Context, name string, limit int) (
|
||||||
func (c *client) artistGetTopTracks(ctx context.Context, name string, limit int) (*TopTracks, error) {
|
func (c *client) artistGetTopTracks(ctx context.Context, name string, limit int) (*TopTracks, error) {
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Add("method", "artist.getTopTracks")
|
params.Add("method", "artist.getTopTracks")
|
||||||
params.Add("artist", name)
|
params.Add("artist", escapePlus(name))
|
||||||
params.Add("limit", strconv.Itoa(limit))
|
params.Add("limit", strconv.Itoa(limit))
|
||||||
response, err := c.makeRequest(ctx, http.MethodGet, params, false)
|
response, err := c.makeRequest(ctx, http.MethodGet, params, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -102,8 +108,8 @@ func (c *client) artistGetTopTracks(ctx context.Context, name string, limit int)
|
||||||
func (c *client) trackGetSimilar(ctx context.Context, name, artist string, limit int) (*SimilarTracks, error) {
|
func (c *client) trackGetSimilar(ctx context.Context, name, artist string, limit int) (*SimilarTracks, error) {
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Add("method", "track.getSimilar")
|
params.Add("method", "track.getSimilar")
|
||||||
params.Add("track", name)
|
params.Add("track", escapePlus(name))
|
||||||
params.Add("artist", artist)
|
params.Add("artist", escapePlus(artist))
|
||||||
params.Add("limit", strconv.Itoa(limit))
|
params.Add("limit", strconv.Itoa(limit))
|
||||||
response, err := c.makeRequest(ctx, http.MethodGet, params, false)
|
response, err := c.makeRequest(ctx, http.MethodGet, params, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -176,7 +182,14 @@ func (c *client) scrobble(ctx context.Context, sessionKey string, info ScrobbleI
|
||||||
params.Add("album", info.album)
|
params.Add("album", info.album)
|
||||||
params.Add("trackNumber", strconv.Itoa(info.trackNumber))
|
params.Add("trackNumber", strconv.Itoa(info.trackNumber))
|
||||||
params.Add("mbid", info.mbid)
|
params.Add("mbid", info.mbid)
|
||||||
|
|
||||||
|
// Last.fm requires a minimum duration of 30 seconds to scrobble a track. To circumvent this, only send the duration if it is greater than or equal to 30 seconds.
|
||||||
|
if info.duration >= 30 {
|
||||||
params.Add("duration", strconv.Itoa(info.duration))
|
params.Add("duration", strconv.Itoa(info.duration))
|
||||||
|
} else {
|
||||||
|
log.Debug(ctx, "LastFM: scrobble duration is less than 30 seconds, duration will not be transmitted", "duration", info.duration)
|
||||||
|
}
|
||||||
|
|
||||||
params.Add("albumArtist", info.albumArtist)
|
params.Add("albumArtist", info.albumArtist)
|
||||||
params.Add("sk", sessionKey)
|
params.Add("sk", sessionKey)
|
||||||
resp, err := c.makeRequest(ctx, http.MethodPost, params, true)
|
resp, err := c.makeRequest(ctx, http.MethodPost, params, true)
|
||||||
|
|
@ -223,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 {
|
||||||
|
|
|
||||||
|
|
@ -19,8 +19,10 @@ import (
|
||||||
var _ = Describe("client", func() {
|
var _ = Describe("client", func() {
|
||||||
var httpClient *tests.FakeHttpClient
|
var httpClient *tests.FakeHttpClient
|
||||||
var client *client
|
var client *client
|
||||||
|
var ctx context.Context
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
httpClient = &tests.FakeHttpClient{}
|
httpClient = &tests.FakeHttpClient{}
|
||||||
client = newClient("API_KEY", "SECRET", httpClient)
|
client = newClient("API_KEY", "SECRET", httpClient)
|
||||||
})
|
})
|
||||||
|
|
@ -28,70 +30,88 @@ var _ = Describe("client", func() {
|
||||||
Describe("albumGetInfo", func() {
|
Describe("albumGetInfo", func() {
|
||||||
It("returns an album on successful response", func() {
|
It("returns an album on successful response", func() {
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
|
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
album, err := client.albumGetInfo(context.Background(), "Believe", "U2", "mbid-1234", "pt")
|
album, err := client.albumGetInfo(ctx, "Believe", "U2", "mbid-1234", "pt")
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(album.Name).To(Equal("Believe"))
|
Expect(album.Name).To(Equal("Believe"))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?album=Believe&api_key=API_KEY&artist=U2&format=json&lang=pt&mbid=mbid-1234&method=album.getInfo"))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?album=Believe&api_key=API_KEY&artist=U2&format=json&lang=pt&mbid=mbid-1234&method=album.getInfo"))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
It("does not double-encode plus signs", func() {
|
||||||
|
f, _ := os.Open("tests/fixtures/lastfm.album.getinfo.json")
|
||||||
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
|
_, err := client.albumGetInfo(ctx, "Lungs", "Florence + the Machine", "", "en")
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("Florence + the Machine"))
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
Describe("artistGetInfo", func() {
|
Describe("artistGetInfo", func() {
|
||||||
It("returns an artist for a successful response", func() {
|
It("returns an artist for a successful response", func() {
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
|
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
artist, err := client.artistGetInfo(context.Background(), "U2", "pt")
|
artist, err := client.artistGetInfo(ctx, "U2", "pt")
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(artist.Name).To(Equal("U2"))
|
Expect(artist.Name).To(Equal("U2"))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&lang=pt&method=artist.getInfo"))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&lang=pt&method=artist.getInfo"))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
It("double-encodes plus signs in the artist name", func() {
|
||||||
|
f, _ := os.Open("tests/fixtures/lastfm.artist.getinfo.json")
|
||||||
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
|
_, err := client.artistGetInfo(ctx, "Florence + the Machine", "en")
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("Florence %2B the Machine"))
|
||||||
|
})
|
||||||
|
|
||||||
It("fails if Last.fm returns an http status != 200", func() {
|
It("fails if Last.fm returns an http status != 200", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`Internal Server Error`)),
|
Body: io.NopCloser(bytes.NewBufferString(`Internal Server Error`)),
|
||||||
StatusCode: 500,
|
StatusCode: http.StatusInternalServerError,
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err := client.artistGetInfo(context.Background(), "U2", "pt")
|
_, err := client.artistGetInfo(ctx, "U2", "pt")
|
||||||
Expect(err).To(MatchError("last.fm http status: (500)"))
|
Expect(err).To(MatchError("last.fm http status: (500)"))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("fails if Last.fm returns an http status != 200", func() {
|
It("fails if Last.fm returns an http status != 200", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"error":3,"message":"Invalid Method - No method with that name in this package"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"error":3,"message":"Invalid Method - No method with that name in this package"}`)),
|
||||||
StatusCode: 400,
|
StatusCode: http.StatusBadRequest,
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err := client.artistGetInfo(context.Background(), "U2", "pt")
|
_, err := client.artistGetInfo(ctx, "U2", "pt")
|
||||||
Expect(err).To(MatchError(&lastFMError{Code: 3, Message: "Invalid Method - No method with that name in this package"}))
|
Expect(err).To(MatchError(&lastFMError{Code: 3, Message: "Invalid Method - No method with that name in this package"}))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("fails if Last.fm returns an error", func() {
|
It("fails if Last.fm returns an error", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"error":6,"message":"The artist you supplied could not be found"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"error":6,"message":"The artist you supplied could not be found"}`)),
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err := client.artistGetInfo(context.Background(), "U2", "pt")
|
_, err := client.artistGetInfo(ctx, "U2", "pt")
|
||||||
Expect(err).To(MatchError(&lastFMError{Code: 6, Message: "The artist you supplied could not be found"}))
|
Expect(err).To(MatchError(&lastFMError{Code: 6, Message: "The artist you supplied could not be found"}))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("fails if HttpClient.Do() returns error", func() {
|
It("fails if HttpClient.Do() returns error", func() {
|
||||||
httpClient.Err = errors.New("generic error")
|
httpClient.Err = errors.New("generic error")
|
||||||
|
|
||||||
_, err := client.artistGetInfo(context.Background(), "U2", "pt")
|
_, err := client.artistGetInfo(ctx, "U2", "pt")
|
||||||
Expect(err).To(MatchError("generic error"))
|
Expect(err).To(MatchError("generic error"))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("fails if returned body is not a valid JSON", func() {
|
It("fails if returned body is not a valid JSON", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`<xml>NOT_VALID_JSON</xml>`)),
|
Body: io.NopCloser(bytes.NewBufferString(`<xml>NOT_VALID_JSON</xml>`)),
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err := client.artistGetInfo(context.Background(), "U2", "pt")
|
_, err := client.artistGetInfo(ctx, "U2", "pt")
|
||||||
Expect(err).To(MatchError("invalid character '<' looking for beginning of value"))
|
Expect(err).To(MatchError("invalid character '<' looking for beginning of value"))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -100,47 +120,76 @@ var _ = Describe("client", func() {
|
||||||
Describe("artistGetSimilar", func() {
|
Describe("artistGetSimilar", func() {
|
||||||
It("returns an artist for a successful response", func() {
|
It("returns an artist for a successful response", func() {
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
|
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
similar, err := client.artistGetSimilar(context.Background(), "U2", 2)
|
similar, err := client.artistGetSimilar(ctx, "U2", 2)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(len(similar.Artists)).To(Equal(2))
|
Expect(similar.Artists).To(HaveLen(2))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&limit=2&method=artist.getSimilar"))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&limit=2&method=artist.getSimilar"))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
It("double-encodes plus signs in the artist name", func() {
|
||||||
|
f, _ := os.Open("tests/fixtures/lastfm.artist.getsimilar.json")
|
||||||
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
|
_, err := client.artistGetSimilar(ctx, "+44", 2)
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("%2B44"))
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
Describe("artistGetTopTracks", func() {
|
Describe("artistGetTopTracks", func() {
|
||||||
It("returns top tracks for a successful response", func() {
|
It("returns top tracks for a successful response", func() {
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
|
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
top, err := client.artistGetTopTracks(context.Background(), "U2", 2)
|
top, err := client.artistGetTopTracks(ctx, "U2", 2)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(len(top.Track)).To(Equal(2))
|
Expect(top.Track).To(HaveLen(2))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&limit=2&method=artist.getTopTracks"))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=U2&format=json&limit=2&method=artist.getTopTracks"))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
It("double-encodes plus signs in the artist name", func() {
|
||||||
|
f, _ := os.Open("tests/fixtures/lastfm.artist.gettoptracks.json")
|
||||||
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
|
_, err := client.artistGetTopTracks(ctx, "C+C Music Factory", 2)
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("C%2BC Music Factory"))
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
Describe("trackGetSimilar", func() {
|
Describe("trackGetSimilar", func() {
|
||||||
It("returns similar tracks for a successful response", func() {
|
It("returns similar tracks for a successful response", func() {
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
|
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
similar, err := client.trackGetSimilar(context.Background(), "Just Can't Get Enough", "Depeche Mode", 5)
|
similar, err := client.trackGetSimilar(ctx, "Just Can't Get Enough", "Depeche Mode", 5)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(len(similar.Track)).To(Equal(5))
|
Expect(similar.Track).To(HaveLen(5))
|
||||||
Expect(similar.Track[0].Name).To(Equal("Dreaming of Me"))
|
Expect(similar.Track[0].Name).To(Equal("Dreaming of Me"))
|
||||||
Expect(similar.Track[0].Artist.Name).To(Equal("Depeche Mode"))
|
Expect(similar.Track[0].Artist.Name).To(Equal("Depeche Mode"))
|
||||||
Expect(similar.Track[0].Match).To(Equal(1.0))
|
Expect(similar.Track[0].Match).To(Equal(1.0))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=Depeche+Mode&format=json&limit=5&method=track.getSimilar&track=Just+Can%27t+Get+Enough"))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(apiBaseUrl + "?api_key=API_KEY&artist=Depeche+Mode&format=json&limit=5&method=track.getSimilar&track=Just+Can%27t+Get+Enough"))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
It("double-encodes plus signs in the track and artist names", func() {
|
||||||
|
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.json")
|
||||||
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
|
_, err := client.trackGetSimilar(ctx, "1+1", "Queen + Paul Rodgers", 5)
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
query := httpClient.SavedRequest.URL.Query()
|
||||||
|
Expect(query.Get("track")).To(Equal("1%2B1"))
|
||||||
|
Expect(query.Get("artist")).To(Equal("Queen %2B Paul Rodgers"))
|
||||||
|
})
|
||||||
|
|
||||||
It("returns empty list when no similar tracks found", func() {
|
It("returns empty list when no similar tracks found", func() {
|
||||||
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json")
|
f, _ := os.Open("tests/fixtures/lastfm.track.getsimilar.unknown.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
similar, err := client.trackGetSimilar(context.Background(), "UnknownTrack", "UnknownArtist", 3)
|
similar, err := client.trackGetSimilar(ctx, "UnknownTrack", "UnknownArtist", 3)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(similar.Track).To(BeEmpty())
|
Expect(similar.Track).To(BeEmpty())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
@ -149,10 +198,10 @@ var _ = Describe("client", func() {
|
||||||
It("returns a token when the request is successful", func() {
|
It("returns a token when the request is successful", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"token":"TOKEN"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"token":"TOKEN"}`)),
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
}
|
}
|
||||||
|
|
||||||
Expect(client.GetToken(context.Background())).To(Equal("TOKEN"))
|
Expect(client.GetToken(ctx)).To(Equal("TOKEN"))
|
||||||
queryParams := httpClient.SavedRequest.URL.Query()
|
queryParams := httpClient.SavedRequest.URL.Query()
|
||||||
Expect(queryParams.Get("method")).To(Equal("auth.getToken"))
|
Expect(queryParams.Get("method")).To(Equal("auth.getToken"))
|
||||||
Expect(queryParams.Get("format")).To(Equal("json"))
|
Expect(queryParams.Get("format")).To(Equal("json"))
|
||||||
|
|
@ -165,10 +214,10 @@ var _ = Describe("client", func() {
|
||||||
It("returns a session key when the request is successful", func() {
|
It("returns a session key when the request is successful", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"session":{"name":"Navidrome","key":"SESSION_KEY","subscriber":0}}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"session":{"name":"Navidrome","key":"SESSION_KEY","subscriber":0}}`)),
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
}
|
}
|
||||||
|
|
||||||
Expect(client.getSession(context.Background(), "TOKEN")).To(Equal("SESSION_KEY"))
|
Expect(client.getSession(ctx, "TOKEN")).To(Equal("SESSION_KEY"))
|
||||||
queryParams := httpClient.SavedRequest.URL.Query()
|
queryParams := httpClient.SavedRequest.URL.Query()
|
||||||
Expect(queryParams.Get("method")).To(Equal("auth.getSession"))
|
Expect(queryParams.Get("method")).To(Equal("auth.getSession"))
|
||||||
Expect(queryParams.Get("format")).To(Equal("json"))
|
Expect(queryParams.Get("format")).To(Equal("json"))
|
||||||
|
|
@ -182,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{
|
||||||
|
|
@ -193,8 +242,8 @@ var _ = Describe("client", func() {
|
||||||
duration: 276,
|
duration: 276,
|
||||||
albumArtist: "U2",
|
albumArtist: "U2",
|
||||||
}
|
}
|
||||||
err := client.scrobble(context.Background(), "SESSION_KEY", info)
|
err := client.scrobble(ctx, "SESSION_KEY", info)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
||||||
req := httpClient.SavedRequest
|
req := httpClient.SavedRequest
|
||||||
Expect(req.Method).To(Equal(http.MethodPost))
|
Expect(req.Method).To(Equal(http.MethodPost))
|
||||||
|
|
@ -216,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{
|
||||||
|
|
@ -227,8 +276,8 @@ var _ = Describe("client", func() {
|
||||||
duration: 276,
|
duration: 276,
|
||||||
albumArtist: "U2",
|
albumArtist: "U2",
|
||||||
}
|
}
|
||||||
err := client.updateNowPlaying(context.Background(), "SESSION_KEY", info)
|
err := client.updateNowPlaying(ctx, "SESSION_KEY", info)
|
||||||
Expect(err).To(BeNil())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
||||||
req := httpClient.SavedRequest
|
req := httpClient.SavedRequest
|
||||||
Expect(req.Method).To(Equal(http.MethodPost))
|
Expect(req.Method).To(Equal(http.MethodPost))
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ package lastfm
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/conf/configtest"
|
||||||
"github.com/navidrome/navidrome/log"
|
"github.com/navidrome/navidrome/log"
|
||||||
"github.com/navidrome/navidrome/tests"
|
"github.com/navidrome/navidrome/tests"
|
||||||
. "github.com/onsi/ginkgo/v2"
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
|
@ -15,3 +16,5 @@ func TestLastFM(t *testing.T) {
|
||||||
RegisterFailHandler(Fail)
|
RegisterFailHandler(Fail)
|
||||||
RunSpecs(t, "LastFM Test Suite")
|
RunSpecs(t, "LastFM Test Suite")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ = configtest.RestoreAfterEachSpec()
|
||||||
|
|
|
||||||
|
|
@ -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"))
|
||||||
|
|
|
||||||
|
|
@ -31,7 +31,7 @@ func listenBrainzConstructor(ds model.DataStore) *listenBrainzAgent {
|
||||||
l := &listenBrainzAgent{
|
l := &listenBrainzAgent{
|
||||||
ds: ds,
|
ds: ds,
|
||||||
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
|
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
|
||||||
baseURL: conf.Server.ListenBrainz.BaseURL,
|
baseURL: conf.Server().ListenBrainz.BaseURL,
|
||||||
}
|
}
|
||||||
hc := httpclient.New(consts.DefaultHttpClientTimeOut)
|
hc := httpclient.New(consts.DefaultHttpClientTimeOut)
|
||||||
chc := cache.NewHTTPClient(hc, consts.DefaultHttpClientTimeOut)
|
chc := cache.NewHTTPClient(hc, consts.DefaultHttpClientTimeOut)
|
||||||
|
|
@ -228,29 +228,30 @@ func (l *listenBrainzAgent) PlaybackReport(context.Context, scrobbler.PlaybackSe
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
conf.AddHook(func() {
|
conf.AddHook(register)
|
||||||
if conf.Server.ListenBrainz.Enabled {
|
}
|
||||||
scrobbler.Register(listenBrainzAgentName, func(ds model.DataStore) scrobbler.Scrobbler {
|
|
||||||
// This is a workaround for the fact that a (Interface)(nil) is not the same as a (*listenBrainzAgent)(nil)
|
|
||||||
// See https://go.dev/doc/faq#nil_error
|
|
||||||
a := listenBrainzConstructor(ds)
|
|
||||||
if a != nil {
|
|
||||||
return a
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
|
|
||||||
agents.Register(listenBrainzAgentName, func(ds model.DataStore) agents.Interface {
|
func register() {
|
||||||
// This is a workaround for the fact that a (Interface)(nil) is not the same as a (*listenBrainzAgent)(nil)
|
scrobbler.Register(listenBrainzAgentName, newScrobbler)
|
||||||
// See https://go.dev/doc/faq#nil_error
|
agents.Register(listenBrainzAgentName, newAgent)
|
||||||
a := listenBrainzConstructor(ds)
|
}
|
||||||
if a != nil {
|
|
||||||
return a
|
func listenBrainzEnabled() bool {
|
||||||
}
|
return conf.Server().ListenBrainz.Enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
func newScrobbler(ds model.DataStore) scrobbler.Scrobbler {
|
||||||
|
if !listenBrainzEnabled() {
|
||||||
return nil
|
return nil
|
||||||
})
|
|
||||||
}
|
}
|
||||||
})
|
return listenBrainzConstructor(ds)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newAgent(ds model.DataStore) agents.Interface {
|
||||||
|
if !listenBrainzEnabled() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return listenBrainzConstructor(ds)
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|
|
||||||
|
|
@ -8,8 +8,10 @@ import (
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"reflect"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/conf"
|
||||||
"github.com/navidrome/navidrome/consts"
|
"github.com/navidrome/navidrome/consts"
|
||||||
"github.com/navidrome/navidrome/core/agents"
|
"github.com/navidrome/navidrome/core/agents"
|
||||||
"github.com/navidrome/navidrome/core/scrobbler"
|
"github.com/navidrome/navidrome/core/scrobbler"
|
||||||
|
|
@ -28,9 +30,9 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
var track *model.MediaFile
|
var track *model.MediaFile
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
ds = &tests.MockDataStore{}
|
ds = &tests.MockDataStore{}
|
||||||
ctx = context.Background()
|
_ = ds.UserProps().Put(ctx, "user-1", sessionKeyProperty, "SK-1")
|
||||||
_ = ds.UserProps(ctx).Put("user-1", sessionKeyProperty, "SK-1")
|
|
||||||
httpClient = &tests.FakeHttpClient{}
|
httpClient = &tests.FakeHttpClient{}
|
||||||
agent = listenBrainzConstructor(ds)
|
agent = listenBrainzConstructor(ds)
|
||||||
agent.client = newClient("http://localhost:8080", httpClient)
|
agent.client = newClient("http://localhost:8080", httpClient)
|
||||||
|
|
@ -46,8 +48,8 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
Duration: 142.2,
|
Duration: 142.2,
|
||||||
Participants: map[model.Role]model.ParticipantList{
|
Participants: map[model.Role]model.ParticipantList{
|
||||||
model.RoleArtist: []model.Participant{
|
model.RoleArtist: []model.Participant{
|
||||||
{Artist: model.Artist{ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"}},
|
{ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"},
|
||||||
{Artist: model.Artist{ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"}},
|
{ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
@ -80,7 +82,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
|
|
||||||
Describe("NowPlaying", func() {
|
Describe("NowPlaying", func() {
|
||||||
It("updates NowPlaying successfully", func() {
|
It("updates NowPlaying successfully", func() {
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: http.StatusOK}
|
||||||
|
|
||||||
err := agent.NowPlaying(ctx, "user-1", track, 0)
|
err := agent.NowPlaying(ctx, "user-1", track, 0)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
@ -100,14 +102,14 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("sends a Scrobble successfully", func() {
|
It("sends a Scrobble successfully", func() {
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: http.StatusOK}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", sc)
|
err := agent.Scrobble(ctx, "user-1", sc)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("sets the Timestamp properly", func() {
|
It("sets the Timestamp properly", func() {
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: http.StatusOK}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", sc)
|
err := agent.Scrobble(ctx, "user-1", sc)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
@ -128,7 +130,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
It("returns ErrRetryLater on error 503", func() {
|
It("returns ErrRetryLater on error 503", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"code": 503, "error": "Cannot submit listens to queue, please try again later."}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"code": 503, "error": "Cannot submit listens to queue, please try again later."}`)),
|
||||||
StatusCode: 503,
|
StatusCode: http.StatusServiceUnavailable,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", sc)
|
err := agent.Scrobble(ctx, "user-1", sc)
|
||||||
|
|
@ -138,7 +140,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
It("returns ErrRetryLater on error 500", func() {
|
It("returns ErrRetryLater on error 500", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"code": 500, "error": "Something went wrong. Please try again."}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"code": 500, "error": "Something went wrong. Please try again."}`)),
|
||||||
StatusCode: 500,
|
StatusCode: http.StatusInternalServerError,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", sc)
|
err := agent.Scrobble(ctx, "user-1", sc)
|
||||||
|
|
@ -148,7 +150,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
It("returns ErrRetryLater on http errors", func() {
|
It("returns ErrRetryLater on http errors", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`Bad Gateway`)),
|
Body: io.NopCloser(bytes.NewBufferString(`Bad Gateway`)),
|
||||||
StatusCode: 500,
|
StatusCode: http.StatusInternalServerError,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", sc)
|
err := agent.Scrobble(ctx, "user-1", sc)
|
||||||
|
|
@ -158,7 +160,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
It("returns ErrUnrecoverable on other errors", func() {
|
It("returns ErrUnrecoverable on other errors", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400, "error": "BadRequest: Invalid JSON document submitted."}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400, "error": "BadRequest: Invalid JSON document submitted."}`)),
|
||||||
StatusCode: 400,
|
StatusCode: http.StatusBadRequest,
|
||||||
}
|
}
|
||||||
|
|
||||||
err := agent.Scrobble(ctx, "user-1", sc)
|
err := agent.Scrobble(ctx, "user-1", sc)
|
||||||
|
|
@ -167,7 +169,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
|
|
||||||
It("keeps a 429 scrobble for retry and carries the delay", func() {
|
It("keeps a 429 scrobble for retry and carries the delay", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
StatusCode: 429,
|
StatusCode: http.StatusTooManyRequests,
|
||||||
Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}},
|
Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}},
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"code":429,"error":"rate limited"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"code":429,"error":"rate limited"}`)),
|
||||||
}
|
}
|
||||||
|
|
@ -191,7 +193,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
|
|
||||||
It("returns artist url when MBID present", func() {
|
It("returns artist url when MBID present", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
Expect(agent.GetArtistURL(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")).To(Equal("http://projectmili.com/"))
|
Expect(agent.GetArtistURL(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")).To(Equal("http://projectmili.com/"))
|
||||||
Expect(httpClient.RequestCount).To(Equal(1))
|
Expect(httpClient.RequestCount).To(Equal(1))
|
||||||
Expect(httpClient.SavedRequest.URL.Query().Get("artist_mbids")).To(Equal("d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56"))
|
Expect(httpClient.SavedRequest.URL.Query().Get("artist_mbids")).To(Equal("d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56"))
|
||||||
|
|
@ -199,7 +201,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
|
|
||||||
It("returns error when url not present", func() {
|
It("returns error when url not present", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
_, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973")
|
_, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973")
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
Expect(httpClient.RequestCount).To(Equal(1))
|
Expect(httpClient.RequestCount).To(Equal(1))
|
||||||
|
|
@ -217,7 +219,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
It("returns error when ListenBrainz returns an error", func() {
|
It("returns error when ListenBrainz returns an error", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)),
|
||||||
StatusCode: 400,
|
StatusCode: http.StatusBadRequest,
|
||||||
}
|
}
|
||||||
_, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973")
|
_, err := agent.GetArtistURL(ctx, "", "", "7c2cc610-f998-43ef-a08f-dae3344b8973")
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
|
|
@ -247,7 +249,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
It("returns an error on listenbrainz error", func() {
|
It("returns an error on listenbrainz error", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)),
|
||||||
StatusCode: 400,
|
StatusCode: http.StatusBadRequest,
|
||||||
}
|
}
|
||||||
_, err := agent.GetArtistTopSongs(ctx, "", "", "1", 1)
|
_, err := agent.GetArtistTopSongs(ctx, "", "", "1", 1)
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
|
|
@ -257,7 +259,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
|
|
||||||
It("returns all tracks when asked", func() {
|
It("returns all tracks when asked", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 2)
|
data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 2)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(data).To(Equal([]agents.Song{
|
Expect(data).To(Equal([]agents.Song{
|
||||||
|
|
@ -284,7 +286,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
|
|
||||||
It("returns only one track when prompted", func() {
|
It("returns only one track when prompted", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
|
data, err := agent.GetArtistTopSongs(ctx, "", "", "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(data).To(Equal([]agents.Song{
|
Expect(data).To(Equal([]agents.Song{
|
||||||
|
|
@ -310,7 +312,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
"release_mbid": "rel-1",
|
"release_mbid": "rel-1",
|
||||||
"length": 200000
|
"length": 200000
|
||||||
}]`
|
}]`
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: http.StatusOK}
|
||||||
data, err := agent.GetArtistTopSongs(ctx, "", "", "mbid-drake", 1)
|
data, err := agent.GetArtistTopSongs(ctx, "", "", "mbid-drake", 1)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(data).To(HaveLen(1))
|
Expect(data).To(HaveLen(1))
|
||||||
|
|
@ -322,7 +324,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
|
|
||||||
It("leaves Artists nil when the top song carries no name or MBIDs", func() {
|
It("leaves Artists nil when the top song carries no name or MBIDs", func() {
|
||||||
body := `[{"recording_name": "Anon", "recording_mbid": "rec-1", "artist_name": "", "artist_mbids": []}]`
|
body := `[{"recording_name": "Anon", "recording_mbid": "rec-1", "artist_name": "", "artist_mbids": []}]`
|
||||||
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: 200}
|
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: http.StatusOK}
|
||||||
data, err := agent.GetArtistTopSongs(ctx, "", "", "x", 1)
|
data, err := agent.GetArtistTopSongs(ctx, "", "", "x", 1)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(data).To(HaveLen(1))
|
Expect(data).To(HaveLen(1))
|
||||||
|
|
@ -354,7 +356,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
It("returns an error on listenbrainz error", func() {
|
It("returns an error on listenbrainz error", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
|
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
|
||||||
StatusCode: 400,
|
StatusCode: http.StatusBadRequest,
|
||||||
}
|
}
|
||||||
_, err := agent.GetSimilarArtists(ctx, "", "", "1", 1)
|
_, err := agent.GetSimilarArtists(ctx, "", "", "1", 1)
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
|
|
@ -364,7 +366,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
|
|
||||||
It("returns all data on call", func() {
|
It("returns all data on call", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 2)
|
resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 2)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
@ -378,7 +380,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
|
|
||||||
It("returns subset of data on call", func() {
|
It("returns subset of data on call", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 1)
|
resp, err := agent.GetSimilarArtists(ctx, "", "", "db92a151-1ac2-438b-bc43-b82e149ddd50", 1)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
@ -414,7 +416,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
It("returns an error on listenbrainz error", func() {
|
It("returns an error on listenbrainz error", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
|
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
|
||||||
StatusCode: 400,
|
StatusCode: http.StatusBadRequest,
|
||||||
}
|
}
|
||||||
_, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", "1", 1)
|
_, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", "1", 1)
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
|
|
@ -424,7 +426,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
|
|
||||||
It("returns all data on call", func() {
|
It("returns all data on call", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 2)
|
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 2)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
@ -456,7 +458,7 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
|
|
||||||
It("returns subset of data on call", func() {
|
It("returns subset of data on call", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
|
|
||||||
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 1)
|
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 1)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
@ -477,3 +479,43 @@ var _ = Describe("listenBrainzAgent", func() {
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
var _ = Describe("register", func() {
|
||||||
|
var ds model.DataStore
|
||||||
|
|
||||||
|
BeforeEach(func() {
|
||||||
|
ds = &tests.MockDataStore{}
|
||||||
|
delete(agents.Map, listenBrainzAgentName)
|
||||||
|
scrobbler.Unregister(listenBrainzAgentName)
|
||||||
|
})
|
||||||
|
|
||||||
|
When("ListenBrainz is disabled", func() {
|
||||||
|
BeforeEach(func() {
|
||||||
|
conf.Update(func(c *conf.Options) { c.ListenBrainz.Enabled = false })
|
||||||
|
register()
|
||||||
|
})
|
||||||
|
|
||||||
|
It("still registers the builtin name", func() {
|
||||||
|
Expect(scrobbler.IsBuiltinScrobbler(listenBrainzAgentName)).To(BeTrue())
|
||||||
|
Expect(agents.Map).To(HaveKey(listenBrainzAgentName))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("builds no scrobbler and no agent", func() {
|
||||||
|
// TypeOf is nil only for an untyped nil; a typed nil would pass callers' != nil checks
|
||||||
|
Expect(reflect.TypeOf(newScrobbler(ds))).To(BeNil())
|
||||||
|
Expect(reflect.TypeOf(agents.Map[listenBrainzAgentName](ds))).To(BeNil())
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
When("ListenBrainz is enabled", func() {
|
||||||
|
BeforeEach(func() {
|
||||||
|
conf.Update(func(c *conf.Options) { c.ListenBrainz.Enabled = true })
|
||||||
|
register()
|
||||||
|
})
|
||||||
|
|
||||||
|
It("builds the scrobbler and the agent", func() {
|
||||||
|
Expect(newScrobbler(ds)).To(BeAssignableToTypeOf(&listenBrainzAgent{}))
|
||||||
|
Expect(agents.Map[listenBrainzAgentName](ds)).To(BeAssignableToTypeOf(&listenBrainzAgent{}))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
|
||||||
|
|
@ -39,7 +39,7 @@ func NewRouter(ds model.DataStore) *Router {
|
||||||
}
|
}
|
||||||
r.Handler = r.routes()
|
r.Handler = r.routes()
|
||||||
hc := httpclient.New(consts.DefaultHttpClientTimeOut)
|
hc := httpclient.New(consts.DefaultHttpClientTimeOut)
|
||||||
r.client = newClient(conf.Server.ListenBrainz.BaseURL, hc)
|
r.client = newClient(conf.Server().ListenBrainz.BaseURL, hc)
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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(""))
|
||||||
|
|
|
||||||
|
|
@ -64,7 +64,7 @@ type listenBrainzResponse struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
type listenBrainzRequest struct {
|
type listenBrainzRequest struct {
|
||||||
ApiKey string //nolint:gosec
|
ApiKey string
|
||||||
Body listenBrainzRequestBody
|
Body listenBrainzRequestBody
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -162,7 +162,10 @@ func (c *client) path(endpoint string) (string, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) makeAuthenticatedRequest(ctx context.Context, method string, endpoint string, r *listenBrainzRequest) (*listenBrainzResponse, error) {
|
func (c *client) makeAuthenticatedRequest(ctx context.Context, method string, endpoint string, r *listenBrainzRequest) (*listenBrainzResponse, error) {
|
||||||
b, _ := json.Marshal(r.Body)
|
b, err := json.Marshal(r.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("encoding request body: %w", err)
|
||||||
|
}
|
||||||
uri, err := c.path(endpoint)
|
uri, err := c.path(endpoint)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|
@ -171,7 +174,7 @@ func (c *client) makeAuthenticatedRequest(ctx context.Context, method string, en
|
||||||
req.Header.Add("Content-Type", "application/json; charset=UTF-8")
|
req.Header.Add("Content-Type", "application/json; charset=UTF-8")
|
||||||
|
|
||||||
if r.ApiKey != "" {
|
if r.ApiKey != "" {
|
||||||
req.Header.Add("Authorization", fmt.Sprintf("Token %s", r.ApiKey))
|
req.Header.Add("Authorization", "Token "+r.ApiKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz %s request", req.Method), "url", req.URL)
|
log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz %s request", req.Method), "url", req.URL)
|
||||||
|
|
@ -188,7 +191,7 @@ func (c *client) makeAuthenticatedRequest(ctx context.Context, method string, en
|
||||||
|
|
||||||
var response listenBrainzResponse
|
var response listenBrainzResponse
|
||||||
jsonErr := decoder.Decode(&response)
|
jsonErr := decoder.Decode(&response)
|
||||||
if resp.StatusCode != 200 && jsonErr != nil {
|
if resp.StatusCode != http.StatusOK && jsonErr != nil {
|
||||||
return nil, fmt.Errorf("ListenBrainz: HTTP Error, Status: (%d)", resp.StatusCode)
|
return nil, fmt.Errorf("ListenBrainz: HTTP Error, Status: (%d)", resp.StatusCode)
|
||||||
}
|
}
|
||||||
if jsonErr != nil {
|
if jsonErr != nil {
|
||||||
|
|
@ -223,7 +226,7 @@ func (c *client) makeGenericRequest(ctx context.Context, method string, endpoint
|
||||||
}
|
}
|
||||||
|
|
||||||
// On a 200 code, there is no code. Decode using using error message if it exists
|
// On a 200 code, there is no code. Decode using using error message if it exists
|
||||||
if resp.StatusCode != 200 {
|
if resp.StatusCode != http.StatusOK {
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
if resp.StatusCode == http.StatusTooManyRequests {
|
if resp.StatusCode == http.StatusTooManyRequests {
|
||||||
return nil, retryLaterErr(resp.Header)
|
return nil, retryLaterErr(resp.Header)
|
||||||
|
|
@ -315,7 +318,7 @@ func (c *client) getSimilarArtists(ctx context.Context, mbid string, limit int)
|
||||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-artists/json", nil)
|
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-artists/json", nil)
|
||||||
req.Header.Add("Content-Type", "application/json; charset=UTF-8")
|
req.Header.Add("Content-Type", "application/json; charset=UTF-8")
|
||||||
req.URL.RawQuery = url.Values{
|
req.URL.RawQuery = url.Values{
|
||||||
"artist_mbids": []string{mbid}, "algorithm": []string{conf.Server.ListenBrainz.ArtistAlgorithm},
|
"artist_mbids": []string{mbid}, "algorithm": []string{conf.Server().ListenBrainz.ArtistAlgorithm},
|
||||||
}.Encode()
|
}.Encode()
|
||||||
|
|
||||||
log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL)
|
log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL)
|
||||||
|
|
@ -354,7 +357,7 @@ func (c *client) getSimilarRecordings(ctx context.Context, mbid string, limit in
|
||||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-recordings/json", nil)
|
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-recordings/json", nil)
|
||||||
req.Header.Add("Content-Type", "application/json; charset=UTF-8")
|
req.Header.Add("Content-Type", "application/json; charset=UTF-8")
|
||||||
req.URL.RawQuery = url.Values{
|
req.URL.RawQuery = url.Values{
|
||||||
"recording_mbids": []string{mbid}, "algorithm": []string{conf.Server.ListenBrainz.TrackAlgorithm},
|
"recording_mbids": []string{mbid}, "algorithm": []string{conf.Server().ListenBrainz.TrackAlgorithm},
|
||||||
}.Encode()
|
}.Encode()
|
||||||
|
|
||||||
log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL)
|
log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL)
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,6 @@ import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/conf"
|
"github.com/navidrome/navidrome/conf"
|
||||||
"github.com/navidrome/navidrome/conf/configtest"
|
|
||||||
"github.com/navidrome/navidrome/core/agents"
|
"github.com/navidrome/navidrome/core/agents"
|
||||||
"github.com/navidrome/navidrome/tests"
|
"github.com/navidrome/navidrome/tests"
|
||||||
. "github.com/onsi/ginkgo/v2"
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
|
@ -23,7 +22,9 @@ import (
|
||||||
var _ = Describe("client", func() {
|
var _ = Describe("client", func() {
|
||||||
var httpClient *tests.FakeHttpClient
|
var httpClient *tests.FakeHttpClient
|
||||||
var client *client
|
var client *client
|
||||||
|
var ctx context.Context
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
httpClient = &tests.FakeHttpClient{}
|
httpClient = &tests.FakeHttpClient{}
|
||||||
client = newClient("BASE_URL/", httpClient)
|
client = newClient("BASE_URL/", httpClient)
|
||||||
})
|
})
|
||||||
|
|
@ -47,12 +48,12 @@ var _ = Describe("client", func() {
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token valid.", "user_name": "ListenBrainzUser", "valid": true}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"code": 200, "message": "Token valid.", "user_name": "ListenBrainzUser", "valid": true}`)),
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
It("formats the request properly", func() {
|
It("formats the request properly", func() {
|
||||||
_, err := client.validateToken(context.Background(), "LB-TOKEN")
|
_, err := client.validateToken(ctx, "LB-TOKEN")
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/validate-token"))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/validate-token"))
|
||||||
|
|
@ -61,9 +62,9 @@ var _ = Describe("client", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("parses and returns the response", func() {
|
It("parses and returns the response", func() {
|
||||||
res, err := client.validateToken(context.Background(), "LB-TOKEN")
|
res, err := client.validateToken(ctx, "LB-TOKEN")
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(res.Valid).To(Equal(true))
|
Expect(res.Valid).To(BeTrue())
|
||||||
Expect(res.UserName).To(Equal("ListenBrainzUser"))
|
Expect(res.UserName).To(Equal("ListenBrainzUser"))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
@ -73,7 +74,7 @@ var _ = Describe("client", func() {
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)),
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
}
|
}
|
||||||
li = listenInfo{
|
li = listenInfo{
|
||||||
TrackMetadata: trackMetadata{
|
TrackMetadata: trackMetadata{
|
||||||
|
|
@ -94,7 +95,7 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
Describe("updateNowPlaying", func() {
|
Describe("updateNowPlaying", func() {
|
||||||
It("formats the request properly", func() {
|
It("formats the request properly", func() {
|
||||||
Expect(client.updateNowPlaying(context.Background(), "LB-TOKEN", li)).To(Succeed())
|
Expect(client.updateNowPlaying(ctx, "LB-TOKEN", li)).To(Succeed())
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodPost))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodPost))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens"))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens"))
|
||||||
Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
|
Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
|
||||||
|
|
@ -112,7 +113,7 @@ var _ = Describe("client", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("formats the request properly", func() {
|
It("formats the request properly", func() {
|
||||||
Expect(client.scrobble(context.Background(), "LB-TOKEN", li)).To(Succeed())
|
Expect(client.scrobble(ctx, "LB-TOKEN", li)).To(Succeed())
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodPost))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodPost))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens"))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal("BASE_URL/submit-listens"))
|
||||||
Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
|
Expect(httpClient.SavedRequest.Header.Get("Authorization")).To(Equal("Token LB-TOKEN"))
|
||||||
|
|
@ -130,9 +131,9 @@ var _ = Describe("client", func() {
|
||||||
It("handles a malformed request with status code", func() {
|
It("handles a malformed request with status code", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"code": 400,"error": "artist mbid 1 is not valid."}`)),
|
||||||
StatusCode: 400,
|
StatusCode: http.StatusBadRequest,
|
||||||
}
|
}
|
||||||
_, err := client.getArtistUrl(context.Background(), "1")
|
_, err := client.getArtistUrl(ctx, "1")
|
||||||
Expect(err.Error()).To(Equal("ListenBrainz error(400): artist mbid 1 is not valid."))
|
Expect(err.Error()).To(Equal("ListenBrainz error(400): artist mbid 1 is not valid."))
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=1"))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=1"))
|
||||||
|
|
@ -142,9 +143,9 @@ var _ = Describe("client", func() {
|
||||||
It("handles a malformed request without meaningful body", func() {
|
It("handles a malformed request without meaningful body", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(``)),
|
Body: io.NopCloser(bytes.NewBufferString(``)),
|
||||||
StatusCode: 501,
|
StatusCode: http.StatusNotImplemented,
|
||||||
}
|
}
|
||||||
_, err := client.getArtistUrl(context.Background(), "1")
|
_, err := client.getArtistUrl(ctx, "1")
|
||||||
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (501)"))
|
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (501)"))
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=1"))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=1"))
|
||||||
|
|
@ -153,8 +154,8 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("It returns not found when the artist has no official homepage", func() {
|
It("It returns not found when the artist has no official homepage", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.no_homepage.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
_, err := client.getArtistUrl(context.Background(), "7c2cc610-f998-43ef-a08f-dae3344b8973")
|
_, err := client.getArtistUrl(ctx, "7c2cc610-f998-43ef-a08f-dae3344b8973")
|
||||||
Expect(err.Error()).To(Equal("listenbrainz: not found"))
|
Expect(err.Error()).To(Equal("listenbrainz: not found"))
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=7c2cc610-f998-43ef-a08f-dae3344b8973"))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "artist_mbids=7c2cc610-f998-43ef-a08f-dae3344b8973"))
|
||||||
|
|
@ -163,8 +164,8 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("It returns data when the artist has a homepage", func() {
|
It("It returns data when the artist has a homepage", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.artist.metadata.homepage.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
url, err := client.getArtistUrl(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")
|
url, err := client.getArtistUrl(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56")
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(url).To(Equal("http://projectmili.com/"))
|
Expect(url).To(Equal("http://projectmili.com/"))
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
|
|
@ -179,9 +180,9 @@ var _ = Describe("client", func() {
|
||||||
It("handles a malformed request with status code", func() {
|
It("handles a malformed request with status code", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)),
|
Body: io.NopCloser(bytes.NewBufferString(`{"code":400,"error":"artist_mbid: '1' is not a valid uuid"}`)),
|
||||||
StatusCode: 400,
|
StatusCode: http.StatusBadRequest,
|
||||||
}
|
}
|
||||||
_, err := client.getArtistTopSongs(context.Background(), "1", 50)
|
_, err := client.getArtistTopSongs(ctx, "1", 50)
|
||||||
Expect(err.Error()).To(Equal("ListenBrainz error(400): artist_mbid: '1' is not a valid uuid"))
|
Expect(err.Error()).To(Equal("ListenBrainz error(400): artist_mbid: '1' is not a valid uuid"))
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1"))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1"))
|
||||||
|
|
@ -191,9 +192,9 @@ var _ = Describe("client", func() {
|
||||||
It("handles a malformed request without standard body", func() {
|
It("handles a malformed request without standard body", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(``)),
|
Body: io.NopCloser(bytes.NewBufferString(``)),
|
||||||
StatusCode: 500,
|
StatusCode: http.StatusInternalServerError,
|
||||||
}
|
}
|
||||||
_, err := client.getArtistTopSongs(context.Background(), "1", 1)
|
_, err := client.getArtistTopSongs(ctx, "1", 1)
|
||||||
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (500)"))
|
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (500)"))
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1"))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(baseUrl + "1"))
|
||||||
|
|
@ -202,8 +203,8 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("It returns all tracks when given the opportunity", func() {
|
It("It returns all tracks when given the opportunity", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
data, err := client.getArtistTopSongs(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 5)
|
data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 5)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(data).To(Equal([]trackInfo{
|
Expect(data).To(Equal([]trackInfo{
|
||||||
{
|
{
|
||||||
|
|
@ -232,8 +233,8 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("It returns a subset of tracks when allowed", func() {
|
It("It returns a subset of tracks when allowed", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.popularity.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
data, err := client.getArtistTopSongs(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
|
data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(data).To(Equal([]trackInfo{
|
Expect(data).To(Equal([]trackInfo{
|
||||||
{
|
{
|
||||||
|
|
@ -257,7 +258,6 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
algorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30"
|
algorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30"
|
||||||
DeferCleanup(configtest.SetupConfig())
|
|
||||||
})
|
})
|
||||||
|
|
||||||
getUrl := func(mbid string) string {
|
getUrl := func(mbid string) string {
|
||||||
|
|
@ -269,9 +269,9 @@ var _ = Describe("client", func() {
|
||||||
It("handles a malformed request with status code", func() {
|
It("handles a malformed request with status code", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
|
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
|
||||||
StatusCode: 400,
|
StatusCode: http.StatusBadRequest,
|
||||||
}
|
}
|
||||||
_, err := client.getSimilarArtists(context.Background(), "1", 2)
|
_, err := client.getSimilarArtists(ctx, "1", 2)
|
||||||
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)"))
|
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)"))
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl("1")))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl("1")))
|
||||||
|
|
@ -280,8 +280,8 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("handles real data properly", func() {
|
It("handles real data properly", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
resp, err := client.getSimilarArtists(context.Background(), mbid, 2)
|
resp, err := client.getSimilarArtists(ctx, mbid, 2)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||||
|
|
@ -294,8 +294,8 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("truncates data when requested", func() {
|
It("truncates data when requested", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
resp, err := client.getSimilarArtists(context.Background(), "db92a151-1ac2-438b-bc43-b82e149ddd50", 1)
|
resp, err := client.getSimilarArtists(ctx, "db92a151-1ac2-438b-bc43-b82e149ddd50", 1)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||||
|
|
@ -307,11 +307,11 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("fetches a different endpoint when algorithm changes", func() {
|
It("fetches a different endpoint when algorithm changes", func() {
|
||||||
algorithm = "session_based_days_1825_session_300_contribution_3_threshold_10_limit_100_filter_True_skip_30"
|
algorithm = "session_based_days_1825_session_300_contribution_3_threshold_10_limit_100_filter_True_skip_30"
|
||||||
conf.Server.ListenBrainz.ArtistAlgorithm = algorithm
|
conf.Update(func(c *conf.Options) { c.ListenBrainz.ArtistAlgorithm = algorithm })
|
||||||
|
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-artists.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
resp, err := client.getSimilarArtists(context.Background(), mbid, 2)
|
resp, err := client.getSimilarArtists(ctx, mbid, 2)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||||
|
|
@ -328,7 +328,6 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
algorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30"
|
algorithm = "session_based_days_9000_session_300_contribution_5_threshold_15_limit_50_skip_30"
|
||||||
DeferCleanup(configtest.SetupConfig())
|
|
||||||
})
|
})
|
||||||
|
|
||||||
getUrl := func(mbid string) string {
|
getUrl := func(mbid string) string {
|
||||||
|
|
@ -340,9 +339,9 @@ var _ = Describe("client", func() {
|
||||||
It("handles a malformed request with status code", func() {
|
It("handles a malformed request with status code", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
|
Body: io.NopCloser(bytes.NewBufferString(`Bad request`)),
|
||||||
StatusCode: 400,
|
StatusCode: http.StatusBadRequest,
|
||||||
}
|
}
|
||||||
_, err := client.getSimilarRecordings(context.Background(), "1", 2)
|
_, err := client.getSimilarRecordings(ctx, "1", 2)
|
||||||
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)"))
|
Expect(err.Error()).To(Equal("ListenBrainz: HTTP Error, Status: (400)"))
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl("1")))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl("1")))
|
||||||
|
|
@ -351,8 +350,8 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("handles real data properly", func() {
|
It("handles real data properly", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
resp, err := client.getSimilarRecordings(context.Background(), mbid, 2)
|
resp, err := client.getSimilarRecordings(ctx, mbid, 2)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||||
|
|
@ -379,8 +378,8 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("truncates data when requested", func() {
|
It("truncates data when requested", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
resp, err := client.getSimilarRecordings(context.Background(), mbid, 1)
|
resp, err := client.getSimilarRecordings(ctx, mbid, 1)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||||
|
|
@ -399,9 +398,9 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("properly sorts by score and truncates duplicates", func() {
|
It("properly sorts by score and truncates duplicates", func() {
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings-real-out-of-order.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings-real-out-of-order.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
// There are actually 5 items. The dedup should happen FIRST
|
// There are actually 5 items. The dedup should happen FIRST
|
||||||
resp, err := client.getSimilarRecordings(context.Background(), mbid, 4)
|
resp, err := client.getSimilarRecordings(ctx, mbid, 4)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||||
|
|
@ -444,11 +443,11 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("uses a different algorithm when configured", func() {
|
It("uses a different algorithm when configured", func() {
|
||||||
algorithm = "session_based_days_180_session_300_contribution_5_threshold_15_limit_50_skip_30"
|
algorithm = "session_based_days_180_session_300_contribution_5_threshold_15_limit_50_skip_30"
|
||||||
conf.Server.ListenBrainz.TrackAlgorithm = algorithm
|
conf.Update(func(c *conf.Options) { c.ListenBrainz.TrackAlgorithm = algorithm })
|
||||||
|
|
||||||
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
f, _ := os.Open("tests/fixtures/listenbrainz.labs.similar-recordings.json")
|
||||||
httpClient.Res = http.Response{Body: f, StatusCode: 200}
|
httpClient.Res = http.Response{Body: f, StatusCode: http.StatusOK}
|
||||||
resp, err := client.getSimilarRecordings(context.Background(), mbid, 1)
|
resp, err := client.getSimilarRecordings(ctx, mbid, 1)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
Expect(httpClient.SavedRequest.Method).To(Equal(http.MethodGet))
|
||||||
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
Expect(httpClient.SavedRequest.URL.String()).To(Equal(getUrl(mbid)))
|
||||||
|
|
@ -469,11 +468,11 @@ var _ = Describe("client", func() {
|
||||||
Describe("rate limiting", func() {
|
Describe("rate limiting", func() {
|
||||||
It("returns RetryLaterError with the header delay on 429", func() {
|
It("returns RetryLaterError with the header delay on 429", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
StatusCode: 429,
|
StatusCode: http.StatusTooManyRequests,
|
||||||
Header: http.Header{"X-Ratelimit-Reset-In": []string{"3"}},
|
Header: http.Header{"X-Ratelimit-Reset-In": []string{"3"}},
|
||||||
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)),
|
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)),
|
||||||
}
|
}
|
||||||
_, err := client.validateToken(context.Background(), "token")
|
_, err := client.validateToken(ctx, "token")
|
||||||
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
||||||
retry, ok := errors.AsType[*agents.RetryLaterError](err)
|
retry, ok := errors.AsType[*agents.RetryLaterError](err)
|
||||||
Expect(ok).To(BeTrue())
|
Expect(ok).To(BeTrue())
|
||||||
|
|
@ -482,10 +481,10 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("returns RetryLaterError with zero delay when no header is present", func() {
|
It("returns RetryLaterError with zero delay when no header is present", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
StatusCode: 429,
|
StatusCode: http.StatusTooManyRequests,
|
||||||
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
|
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
|
||||||
}
|
}
|
||||||
_, err := client.validateToken(context.Background(), "token")
|
_, err := client.validateToken(ctx, "token")
|
||||||
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
||||||
retry, _ := errors.AsType[*agents.RetryLaterError](err)
|
retry, _ := errors.AsType[*agents.RetryLaterError](err)
|
||||||
Expect(retry.RetryIn).To(BeZero())
|
Expect(retry.RetryIn).To(BeZero())
|
||||||
|
|
@ -494,11 +493,11 @@ var _ = Describe("client", func() {
|
||||||
DescribeTable("caps absurd header values at one hour",
|
DescribeTable("caps absurd header values at one hour",
|
||||||
func(header string) {
|
func(header string) {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
StatusCode: 429,
|
StatusCode: http.StatusTooManyRequests,
|
||||||
Header: http.Header{"X-Ratelimit-Reset-In": []string{header}},
|
Header: http.Header{"X-Ratelimit-Reset-In": []string{header}},
|
||||||
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
|
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
|
||||||
}
|
}
|
||||||
_, err := client.validateToken(context.Background(), "token")
|
_, err := client.validateToken(ctx, "token")
|
||||||
retry, _ := errors.AsType[*agents.RetryLaterError](err)
|
retry, _ := errors.AsType[*agents.RetryLaterError](err)
|
||||||
Expect(retry.RetryIn).To(Equal(time.Hour))
|
Expect(retry.RetryIn).To(Equal(time.Hour))
|
||||||
},
|
},
|
||||||
|
|
@ -510,11 +509,11 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("maps a body-level 429 sent with a non-429 status", func() {
|
It("maps a body-level 429 sent with a non-429 status", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
StatusCode: 200,
|
StatusCode: http.StatusOK,
|
||||||
Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}},
|
Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}},
|
||||||
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)),
|
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)),
|
||||||
}
|
}
|
||||||
_, err := client.validateToken(context.Background(), "token")
|
_, err := client.validateToken(ctx, "token")
|
||||||
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
||||||
retry, ok := errors.AsType[*agents.RetryLaterError](err)
|
retry, ok := errors.AsType[*agents.RetryLaterError](err)
|
||||||
Expect(ok).To(BeTrue())
|
Expect(ok).To(BeTrue())
|
||||||
|
|
@ -523,11 +522,11 @@ var _ = Describe("client", func() {
|
||||||
|
|
||||||
It("returns RetryLaterError on a 429 from makeGenericRequest", func() {
|
It("returns RetryLaterError on a 429 from makeGenericRequest", func() {
|
||||||
httpClient.Res = http.Response{
|
httpClient.Res = http.Response{
|
||||||
StatusCode: 429,
|
StatusCode: http.StatusTooManyRequests,
|
||||||
Header: http.Header{"X-Ratelimit-Reset-In": []string{"5"}},
|
Header: http.Header{"X-Ratelimit-Reset-In": []string{"5"}},
|
||||||
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
|
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
|
||||||
}
|
}
|
||||||
_, err := client.getArtistUrl(context.Background(), "1")
|
_, err := client.getArtistUrl(ctx, "1")
|
||||||
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
|
||||||
retry, ok := errors.AsType[*agents.RetryLaterError](err)
|
retry, ok := errors.AsType[*agents.RetryLaterError](err)
|
||||||
Expect(ok).To(BeTrue())
|
Expect(ok).To(BeTrue())
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ package listenbrainz
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/conf/configtest"
|
||||||
"github.com/navidrome/navidrome/log"
|
"github.com/navidrome/navidrome/log"
|
||||||
"github.com/navidrome/navidrome/tests"
|
"github.com/navidrome/navidrome/tests"
|
||||||
. "github.com/onsi/ginkgo/v2"
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
|
@ -15,3 +16,5 @@ func TestListenBrainz(t *testing.T) {
|
||||||
RegisterFailHandler(Fail)
|
RegisterFailHandler(Fail)
|
||||||
RunSpecs(t, "ListenBrainz Test Suite")
|
RunSpecs(t, "ListenBrainz Test Suite")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ = configtest.RestoreAfterEachSpec()
|
||||||
|
|
|
||||||
1
api/.oasdiff-levels.txt
Normal file
1
api/.oasdiff-levels.txt
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
response-property-enum-value-added INFO
|
||||||
155
api/.vacuum.yaml
Normal file
155
api/.vacuum.yaml
Normal file
|
|
@ -0,0 +1,155 @@
|
||||||
|
extends: [[spectral:oas, recommended]]
|
||||||
|
rules:
|
||||||
|
# vacuum's `enumeration` function mis-resolves hyphenated `then.field` names,
|
||||||
|
# so the value check below targets `x-module` via `given` instead.
|
||||||
|
nd-operation-x-module-required:
|
||||||
|
description: Every operation belongs to exactly one capability module.
|
||||||
|
severity: error
|
||||||
|
given: $.paths[*][get,put,post,delete,patch]
|
||||||
|
then:
|
||||||
|
field: x-module
|
||||||
|
function: truthy
|
||||||
|
nd-operation-x-module:
|
||||||
|
description: Every operation's capability module is one of the known values.
|
||||||
|
severity: error
|
||||||
|
given: $.paths[*][get,put,post,delete,patch]['x-module']
|
||||||
|
then:
|
||||||
|
function: enumeration
|
||||||
|
functionOptions:
|
||||||
|
values:
|
||||||
|
- core
|
||||||
|
- streaming
|
||||||
|
- download
|
||||||
|
- artwork
|
||||||
|
- lyrics
|
||||||
|
- transcoding
|
||||||
|
- annotations
|
||||||
|
- playback
|
||||||
|
- queue
|
||||||
|
- custom-tags
|
||||||
|
- grouping
|
||||||
|
- playlists
|
||||||
|
- smart-playlists
|
||||||
|
- sync
|
||||||
|
- events
|
||||||
|
- jukebox
|
||||||
|
- sharing
|
||||||
|
- radio
|
||||||
|
- admin
|
||||||
|
nd-operation-stability-level-required:
|
||||||
|
description: Every operation declares its stability level, which the breaking-change gate relies on.
|
||||||
|
severity: error
|
||||||
|
given: $.paths[*][get,put,post,delete,patch]
|
||||||
|
then:
|
||||||
|
field: x-stability-level
|
||||||
|
function: truthy
|
||||||
|
nd-operation-stability-level:
|
||||||
|
description: Every operation's stability level is alpha, beta, or stable.
|
||||||
|
severity: error
|
||||||
|
given: $.paths[*][get,put,post,delete,patch]['x-stability-level']
|
||||||
|
then:
|
||||||
|
function: enumeration
|
||||||
|
functionOptions:
|
||||||
|
values:
|
||||||
|
- alpha
|
||||||
|
- beta
|
||||||
|
- stable
|
||||||
|
nd-operation-required-fields:
|
||||||
|
description: Operations need a stable operationId, summary, description and tags.
|
||||||
|
severity: error
|
||||||
|
given: $.paths[*][get,put,post,delete,patch]
|
||||||
|
then:
|
||||||
|
- field: operationId
|
||||||
|
function: truthy
|
||||||
|
- field: summary
|
||||||
|
function: truthy
|
||||||
|
- field: description
|
||||||
|
function: truthy
|
||||||
|
- field: tags
|
||||||
|
function: truthy
|
||||||
|
# Our schemas live in path/response files, not root components, so this
|
||||||
|
# walks every resolved `properties` map in the document via `$..` instead.
|
||||||
|
nd-schema-property-descriptions:
|
||||||
|
description: Every schema property is documented.
|
||||||
|
severity: error
|
||||||
|
given: $..properties[*]
|
||||||
|
then:
|
||||||
|
field: description
|
||||||
|
function: truthy
|
||||||
|
# patternProperties covers the full 4xx/5xx range; needs an explicit
|
||||||
|
# `properties` entry too, or `additionalProperties: false` rejects it.
|
||||||
|
nd-error-responses-are-problems:
|
||||||
|
description: 4xx and 5xx responses use application/problem+json.
|
||||||
|
severity: error
|
||||||
|
given: $.paths[*][*].responses
|
||||||
|
then:
|
||||||
|
function: schema
|
||||||
|
functionOptions:
|
||||||
|
forceValidationOnCurrentNode: true
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
patternProperties:
|
||||||
|
"^[45][0-9][0-9]$":
|
||||||
|
type: object
|
||||||
|
required: [content]
|
||||||
|
properties:
|
||||||
|
content:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
application/problem+json: {}
|
||||||
|
required: [application/problem+json]
|
||||||
|
additionalProperties: false
|
||||||
|
# Same filter limitation applies here: "is this a list endpoint" is expressed
|
||||||
|
# as a JSON Schema if/then on the operation object instead of a `given` filter.
|
||||||
|
nd-list-endpoints-paginate:
|
||||||
|
description: List endpoints declare the shared offset and limit parameters.
|
||||||
|
severity: error
|
||||||
|
given: $.paths[*].get
|
||||||
|
then:
|
||||||
|
function: schema
|
||||||
|
functionOptions:
|
||||||
|
forceValidationOnCurrentNode: true
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
if:
|
||||||
|
required: [responses]
|
||||||
|
properties:
|
||||||
|
responses:
|
||||||
|
type: object
|
||||||
|
required: ['200']
|
||||||
|
properties:
|
||||||
|
'200':
|
||||||
|
type: object
|
||||||
|
required: [content]
|
||||||
|
properties:
|
||||||
|
content:
|
||||||
|
type: object
|
||||||
|
required: [application/json]
|
||||||
|
properties:
|
||||||
|
application/json:
|
||||||
|
type: object
|
||||||
|
required: [schema]
|
||||||
|
properties:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
required: [properties]
|
||||||
|
properties:
|
||||||
|
properties:
|
||||||
|
type: object
|
||||||
|
required: [items]
|
||||||
|
then:
|
||||||
|
required: [parameters]
|
||||||
|
properties:
|
||||||
|
parameters:
|
||||||
|
type: array
|
||||||
|
allOf:
|
||||||
|
- contains:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
name:
|
||||||
|
const: offset
|
||||||
|
- contains:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
name:
|
||||||
|
const: limit
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
package ffmpeg
|
package api_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
@ -9,9 +9,9 @@ import (
|
||||||
. "github.com/onsi/gomega"
|
. "github.com/onsi/gomega"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestFFMpeg(t *testing.T) {
|
func TestAPI(t *testing.T) {
|
||||||
tests.Init(t, true)
|
tests.Init(t, false)
|
||||||
log.SetLevel(log.LevelFatal)
|
log.SetLevel(log.LevelFatal)
|
||||||
RegisterFailHandler(Fail)
|
RegisterFailHandler(Fail)
|
||||||
RunSpecs(t, "FFMpeg Suite")
|
RunSpecs(t, "API Spec Suite")
|
||||||
}
|
}
|
||||||
262
api/bundled/openapi.json
Normal file
262
api/bundled/openapi.json
Normal file
|
|
@ -0,0 +1,262 @@
|
||||||
|
{
|
||||||
|
"openapi": "3.0.3",
|
||||||
|
"info": {
|
||||||
|
"title": "Navidrome API",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "Navidrome API v1. Spec-first, additive within v1. Clients discover implemented\ncapability modules through `GET /server` and never sniff versions.\n\nEnums are open: new values may be added to any enum within v1. Clients must\naccept values they do not recognise instead of failing.\n\nEvery operation declares `x-stability-level`: `alpha` operations may change or\ndisappear without notice, `beta` and `stable` operations only change additively.\nA level is only ever raised, never lowered.\n\n`HEAD` is accepted wherever `GET` is. A `405` response lists the allowed methods\nin its `Allow` header.\n",
|
||||||
|
"license": {
|
||||||
|
"name": "GPL-3.0",
|
||||||
|
"url": "https://www.gnu.org/licenses/gpl-3.0.html"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"servers": [
|
||||||
|
{
|
||||||
|
"url": "/api/v1"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"tags": [
|
||||||
|
{
|
||||||
|
"name": "server",
|
||||||
|
"description": "Server discovery and the published OpenAPI document."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"paths": {
|
||||||
|
"/server": {
|
||||||
|
"get": {
|
||||||
|
"operationId": "getServerInfo",
|
||||||
|
"x-module": "core",
|
||||||
|
"x-stability-level": "alpha",
|
||||||
|
"tags": [
|
||||||
|
"server"
|
||||||
|
],
|
||||||
|
"summary": "Describe the server",
|
||||||
|
"description": "Returns the public server description. No authentication required.\nAuthenticated requests will additionally receive the implemented capability modules\nonce authentication is available.\n",
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "Server description.",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/ServerInfo"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"500": {
|
||||||
|
"$ref": "#/components/responses/InternalError"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/openapi.json": {
|
||||||
|
"get": {
|
||||||
|
"operationId": "getOpenAPISpecJSON",
|
||||||
|
"x-module": "core",
|
||||||
|
"x-stability-level": "alpha",
|
||||||
|
"tags": [
|
||||||
|
"server"
|
||||||
|
],
|
||||||
|
"summary": "Get the OpenAPI document (JSON)",
|
||||||
|
"description": "The bundled OpenAPI document of the running server version. Supports ETag revalidation.",
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "The OpenAPI document.",
|
||||||
|
"headers": {
|
||||||
|
"ETag": {
|
||||||
|
"$ref": "#/components/headers/ETag"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "OpenAPI 3.0 document."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"304": {
|
||||||
|
"$ref": "#/components/responses/NotModified"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"/openapi.yaml": {
|
||||||
|
"get": {
|
||||||
|
"operationId": "getOpenAPISpecYAML",
|
||||||
|
"x-module": "core",
|
||||||
|
"x-stability-level": "alpha",
|
||||||
|
"tags": [
|
||||||
|
"server"
|
||||||
|
],
|
||||||
|
"summary": "Get the OpenAPI document (YAML)",
|
||||||
|
"description": "The bundled OpenAPI document of the running server version. Supports ETag revalidation.",
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "The OpenAPI document.",
|
||||||
|
"headers": {
|
||||||
|
"ETag": {
|
||||||
|
"$ref": "#/components/headers/ETag"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"content": {
|
||||||
|
"application/yaml": {
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "OpenAPI 3.0 document."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"304": {
|
||||||
|
"$ref": "#/components/responses/NotModified"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"components": {
|
||||||
|
"securitySchemes": {
|
||||||
|
"bearerAuth": {
|
||||||
|
"type": "http",
|
||||||
|
"scheme": "bearer",
|
||||||
|
"bearerFormat": "JWT",
|
||||||
|
"description": "Short-lived access token minted from a device grant. Not yet applied to any operation."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"schemas": {
|
||||||
|
"ServerInfo": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "Public server description. Everything an add-server screen needs before login.",
|
||||||
|
"required": [
|
||||||
|
"name",
|
||||||
|
"serverVersion",
|
||||||
|
"specVersion",
|
||||||
|
"setupRequired",
|
||||||
|
"loginMethods"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Human-readable server product name."
|
||||||
|
},
|
||||||
|
"serverVersion": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Version of the running server build."
|
||||||
|
},
|
||||||
|
"specVersion": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Version of the OpenAPI document this server implements."
|
||||||
|
},
|
||||||
|
"setupRequired": {
|
||||||
|
"type": "boolean",
|
||||||
|
"description": "True until the first admin user has been created."
|
||||||
|
},
|
||||||
|
"loginMethods": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Login methods this server accepts. New methods may be added; clients ignore values they do not recognise.",
|
||||||
|
"items": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"password"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Problem": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "RFC 9457 problem details, returned for every 4xx and 5xx response.",
|
||||||
|
"required": [
|
||||||
|
"title",
|
||||||
|
"status",
|
||||||
|
"code"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"type": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "URI reference identifying the problem type. Omitted while the problem carries no semantics\nbeyond its HTTP status code, which RFC 9457 defines as `about:blank`. Problems with their\nown semantics get their own URI; switch on `code` instead.\n"
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Short human-readable summary, the same for all occurrences of this problem type."
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": "HTTP status code of this response."
|
||||||
|
},
|
||||||
|
"detail": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Human-readable explanation specific to this occurrence. Omitted for internal errors."
|
||||||
|
},
|
||||||
|
"code": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Machine-readable error code, and the value clients switch on. New codes may be added.",
|
||||||
|
"enum": [
|
||||||
|
"validation",
|
||||||
|
"unauthorized",
|
||||||
|
"forbidden",
|
||||||
|
"not_found",
|
||||||
|
"method_not_allowed",
|
||||||
|
"unavailable",
|
||||||
|
"internal"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Per-field failures. Present only when `code` is `validation`.",
|
||||||
|
"items": {
|
||||||
|
"$ref": "#/components/schemas/ValidationError"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ValidationError": {
|
||||||
|
"type": "object",
|
||||||
|
"description": "One field-level validation failure.",
|
||||||
|
"required": [
|
||||||
|
"field",
|
||||||
|
"message"
|
||||||
|
],
|
||||||
|
"properties": {
|
||||||
|
"field": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Name of the offending query parameter, path parameter, or body field (dotted for nested)."
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Why the value was rejected."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"responses": {
|
||||||
|
"InternalError": {
|
||||||
|
"description": "Unexpected server failure. Details are in the server log.",
|
||||||
|
"content": {
|
||||||
|
"application/problem+json": {
|
||||||
|
"schema": {
|
||||||
|
"$ref": "#/components/schemas/Problem"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"NotModified": {
|
||||||
|
"description": "Not modified.",
|
||||||
|
"headers": {
|
||||||
|
"ETag": {
|
||||||
|
"$ref": "#/components/headers/ETag"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"headers": {
|
||||||
|
"ETag": {
|
||||||
|
"description": "Entity tag for `If-None-Match` revalidation.",
|
||||||
|
"schema": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
194
api/bundled/openapi.yaml
Normal file
194
api/bundled/openapi.yaml
Normal file
|
|
@ -0,0 +1,194 @@
|
||||||
|
openapi: 3.0.3
|
||||||
|
info:
|
||||||
|
title: Navidrome API
|
||||||
|
version: 1.0.0
|
||||||
|
description: |
|
||||||
|
Navidrome API v1. Spec-first, additive within v1. Clients discover implemented
|
||||||
|
capability modules through `GET /server` and never sniff versions.
|
||||||
|
|
||||||
|
Enums are open: new values may be added to any enum within v1. Clients must
|
||||||
|
accept values they do not recognise instead of failing.
|
||||||
|
|
||||||
|
Every operation declares `x-stability-level`: `alpha` operations may change or
|
||||||
|
disappear without notice, `beta` and `stable` operations only change additively.
|
||||||
|
A level is only ever raised, never lowered.
|
||||||
|
|
||||||
|
`HEAD` is accepted wherever `GET` is. A `405` response lists the allowed methods
|
||||||
|
in its `Allow` header.
|
||||||
|
license:
|
||||||
|
name: GPL-3.0
|
||||||
|
url: https://www.gnu.org/licenses/gpl-3.0.html
|
||||||
|
servers:
|
||||||
|
- url: /api/v1
|
||||||
|
tags:
|
||||||
|
- name: server
|
||||||
|
description: Server discovery and the published OpenAPI document.
|
||||||
|
paths:
|
||||||
|
/server:
|
||||||
|
get:
|
||||||
|
operationId: getServerInfo
|
||||||
|
x-module: core
|
||||||
|
x-stability-level: alpha
|
||||||
|
tags: [server]
|
||||||
|
summary: Describe the server
|
||||||
|
description: |
|
||||||
|
Returns the public server description. No authentication required.
|
||||||
|
Authenticated requests will additionally receive the implemented capability modules
|
||||||
|
once authentication is available.
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Server description.
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/ServerInfo'
|
||||||
|
'500':
|
||||||
|
$ref: '#/components/responses/InternalError'
|
||||||
|
/openapi.json:
|
||||||
|
get:
|
||||||
|
operationId: getOpenAPISpecJSON
|
||||||
|
x-module: core
|
||||||
|
x-stability-level: alpha
|
||||||
|
tags: [server]
|
||||||
|
summary: Get the OpenAPI document (JSON)
|
||||||
|
description: The bundled OpenAPI document of the running server version. Supports ETag revalidation.
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: The OpenAPI document.
|
||||||
|
headers:
|
||||||
|
ETag:
|
||||||
|
$ref: '#/components/headers/ETag'
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
description: OpenAPI 3.0 document.
|
||||||
|
'304':
|
||||||
|
$ref: '#/components/responses/NotModified'
|
||||||
|
/openapi.yaml:
|
||||||
|
get:
|
||||||
|
operationId: getOpenAPISpecYAML
|
||||||
|
x-module: core
|
||||||
|
x-stability-level: alpha
|
||||||
|
tags: [server]
|
||||||
|
summary: Get the OpenAPI document (YAML)
|
||||||
|
description: The bundled OpenAPI document of the running server version. Supports ETag revalidation.
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: The OpenAPI document.
|
||||||
|
headers:
|
||||||
|
ETag:
|
||||||
|
$ref: '#/components/headers/ETag'
|
||||||
|
content:
|
||||||
|
application/yaml:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
description: OpenAPI 3.0 document.
|
||||||
|
'304':
|
||||||
|
$ref: '#/components/responses/NotModified'
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
bearerAuth:
|
||||||
|
type: http
|
||||||
|
scheme: bearer
|
||||||
|
bearerFormat: JWT
|
||||||
|
description: Short-lived access token minted from a device grant. Not yet applied to any operation.
|
||||||
|
schemas:
|
||||||
|
ServerInfo:
|
||||||
|
type: object
|
||||||
|
description: Public server description. Everything an add-server screen needs before login.
|
||||||
|
required:
|
||||||
|
- name
|
||||||
|
- serverVersion
|
||||||
|
- specVersion
|
||||||
|
- setupRequired
|
||||||
|
- loginMethods
|
||||||
|
properties:
|
||||||
|
name:
|
||||||
|
type: string
|
||||||
|
description: Human-readable server product name.
|
||||||
|
serverVersion:
|
||||||
|
type: string
|
||||||
|
description: Version of the running server build.
|
||||||
|
specVersion:
|
||||||
|
type: string
|
||||||
|
description: Version of the OpenAPI document this server implements.
|
||||||
|
setupRequired:
|
||||||
|
type: boolean
|
||||||
|
description: True until the first admin user has been created.
|
||||||
|
loginMethods:
|
||||||
|
type: array
|
||||||
|
description: Login methods this server accepts. New methods may be added; clients ignore values they do not recognise.
|
||||||
|
items:
|
||||||
|
type: string
|
||||||
|
enum:
|
||||||
|
- password
|
||||||
|
Problem:
|
||||||
|
type: object
|
||||||
|
description: RFC 9457 problem details, returned for every 4xx and 5xx response.
|
||||||
|
required:
|
||||||
|
- title
|
||||||
|
- status
|
||||||
|
- code
|
||||||
|
properties:
|
||||||
|
type:
|
||||||
|
type: string
|
||||||
|
description: |
|
||||||
|
URI reference identifying the problem type. Omitted while the problem carries no semantics
|
||||||
|
beyond its HTTP status code, which RFC 9457 defines as `about:blank`. Problems with their
|
||||||
|
own semantics get their own URI; switch on `code` instead.
|
||||||
|
title:
|
||||||
|
type: string
|
||||||
|
description: Short human-readable summary, the same for all occurrences of this problem type.
|
||||||
|
status:
|
||||||
|
type: integer
|
||||||
|
description: HTTP status code of this response.
|
||||||
|
detail:
|
||||||
|
type: string
|
||||||
|
description: Human-readable explanation specific to this occurrence. Omitted for internal errors.
|
||||||
|
code:
|
||||||
|
type: string
|
||||||
|
description: Machine-readable error code, and the value clients switch on. New codes may be added.
|
||||||
|
enum:
|
||||||
|
- validation
|
||||||
|
- unauthorized
|
||||||
|
- forbidden
|
||||||
|
- not_found
|
||||||
|
- method_not_allowed
|
||||||
|
- unavailable
|
||||||
|
- internal
|
||||||
|
errors:
|
||||||
|
type: array
|
||||||
|
description: Per-field failures. Present only when `code` is `validation`.
|
||||||
|
items:
|
||||||
|
$ref: '#/components/schemas/ValidationError'
|
||||||
|
ValidationError:
|
||||||
|
type: object
|
||||||
|
description: One field-level validation failure.
|
||||||
|
required:
|
||||||
|
- field
|
||||||
|
- message
|
||||||
|
properties:
|
||||||
|
field:
|
||||||
|
type: string
|
||||||
|
description: Name of the offending query parameter, path parameter, or body field (dotted for nested).
|
||||||
|
message:
|
||||||
|
type: string
|
||||||
|
description: Why the value was rejected.
|
||||||
|
responses:
|
||||||
|
InternalError:
|
||||||
|
description: Unexpected server failure. Details are in the server log.
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/Problem'
|
||||||
|
NotModified:
|
||||||
|
description: Not modified.
|
||||||
|
headers:
|
||||||
|
ETag:
|
||||||
|
$ref: '#/components/headers/ETag'
|
||||||
|
headers:
|
||||||
|
ETag:
|
||||||
|
description: Entity tag for `If-None-Match` revalidation.
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
35
api/embed.go
Normal file
35
api/embed.go
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
_ "embed"
|
||||||
|
"encoding/json"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed bundled/openapi.json
|
||||||
|
var specJSON []byte
|
||||||
|
|
||||||
|
//go:embed bundled/openapi.yaml
|
||||||
|
var specYAML []byte
|
||||||
|
|
||||||
|
func SpecJSON() []byte {
|
||||||
|
return specJSON
|
||||||
|
}
|
||||||
|
|
||||||
|
func SpecYAML() []byte {
|
||||||
|
return specYAML
|
||||||
|
}
|
||||||
|
|
||||||
|
var specVersion = sync.OnceValue(func() string {
|
||||||
|
var doc struct {
|
||||||
|
Info struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
} `json:"info"`
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(SpecJSON(), &doc)
|
||||||
|
return doc.Info.Version
|
||||||
|
})
|
||||||
|
|
||||||
|
func SpecVersion() string {
|
||||||
|
return specVersion()
|
||||||
|
}
|
||||||
37
api/embed_test.go
Normal file
37
api/embed_test.go
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
package api_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/getkin/kin-openapi/openapi3"
|
||||||
|
"github.com/navidrome/navidrome/api"
|
||||||
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
. "github.com/onsi/gomega"
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ = Describe("Bundled spec", func() {
|
||||||
|
It("embeds a valid OpenAPI 3 document", func() {
|
||||||
|
doc, err := openapi3.NewLoader().LoadFromData(api.SpecJSON())
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
Expect(doc.Validate(GinkgoT().Context())).To(Succeed())
|
||||||
|
Expect(doc.Paths.Find("/server")).ToNot(BeNil())
|
||||||
|
})
|
||||||
|
|
||||||
|
It("embeds the YAML variant", func() {
|
||||||
|
var doc map[string]any
|
||||||
|
Expect(yaml.Unmarshal(api.SpecYAML(), &doc)).To(Succeed())
|
||||||
|
Expect(doc).To(HaveKey("paths"))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("reports the version from the bundle, matching the source root document", func() {
|
||||||
|
src, err := os.ReadFile("api/openapi/openapi.yaml")
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
var root struct {
|
||||||
|
Info struct{ Version string } `yaml:"info"`
|
||||||
|
}
|
||||||
|
Expect(yaml.Unmarshal(src, &root)).To(Succeed())
|
||||||
|
Expect(api.SpecVersion()).To(Equal(root.Info.Version))
|
||||||
|
Expect(api.SpecVersion()).ToNot(BeEmpty())
|
||||||
|
})
|
||||||
|
})
|
||||||
3
api/openapi/components/headers/ETag.yaml
Normal file
3
api/openapi/components/headers/ETag.yaml
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
description: Entity tag for `If-None-Match` revalidation.
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
9
api/openapi/components/parameters/limit.yaml
Normal file
9
api/openapi/components/parameters/limit.yaml
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
name: limit
|
||||||
|
in: query
|
||||||
|
description: Maximum number of items to return.
|
||||||
|
required: false
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
minimum: 1
|
||||||
|
maximum: 2000
|
||||||
|
default: 100
|
||||||
8
api/openapi/components/parameters/offset.yaml
Normal file
8
api/openapi/components/parameters/offset.yaml
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
name: offset
|
||||||
|
in: query
|
||||||
|
description: Zero-based index of the first item to return.
|
||||||
|
required: false
|
||||||
|
schema:
|
||||||
|
type: integer
|
||||||
|
minimum: 0
|
||||||
|
default: 0
|
||||||
5
api/openapi/components/responses/BadRequest.yaml
Normal file
5
api/openapi/components/responses/BadRequest.yaml
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
description: The request is malformed or fails validation.
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: ../schemas/Problem.yaml
|
||||||
5
api/openapi/components/responses/Forbidden.yaml
Normal file
5
api/openapi/components/responses/Forbidden.yaml
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
description: The caller is authenticated but not allowed to do this.
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: ../schemas/Problem.yaml
|
||||||
5
api/openapi/components/responses/InternalError.yaml
Normal file
5
api/openapi/components/responses/InternalError.yaml
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
description: Unexpected server failure. Details are in the server log.
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: ../schemas/Problem.yaml
|
||||||
5
api/openapi/components/responses/NotFound.yaml
Normal file
5
api/openapi/components/responses/NotFound.yaml
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
description: No such resource or endpoint.
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: ../schemas/Problem.yaml
|
||||||
4
api/openapi/components/responses/NotModified.yaml
Normal file
4
api/openapi/components/responses/NotModified.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
description: Not modified.
|
||||||
|
headers:
|
||||||
|
ETag:
|
||||||
|
$ref: ../headers/ETag.yaml
|
||||||
5
api/openapi/components/responses/Unauthorized.yaml
Normal file
5
api/openapi/components/responses/Unauthorized.yaml
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
description: Missing, invalid, or expired credentials.
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: ../schemas/Problem.yaml
|
||||||
13
api/openapi/components/schemas/ListMeta.yaml
Normal file
13
api/openapi/components/schemas/ListMeta.yaml
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
type: object
|
||||||
|
description: Pagination metadata carried by every list response.
|
||||||
|
required: [total, offset, limit]
|
||||||
|
properties:
|
||||||
|
total:
|
||||||
|
type: integer
|
||||||
|
description: Total number of items matching the request, ignoring pagination.
|
||||||
|
offset:
|
||||||
|
type: integer
|
||||||
|
description: Zero-based index of the first returned item.
|
||||||
|
limit:
|
||||||
|
type: integer
|
||||||
|
description: Maximum number of items in this page.
|
||||||
35
api/openapi/components/schemas/Problem.yaml
Normal file
35
api/openapi/components/schemas/Problem.yaml
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
type: object
|
||||||
|
description: RFC 9457 problem details, returned for every 4xx and 5xx response.
|
||||||
|
required: [title, status, code]
|
||||||
|
properties:
|
||||||
|
type:
|
||||||
|
type: string
|
||||||
|
description: |
|
||||||
|
URI reference identifying the problem type. Omitted while the problem carries no semantics
|
||||||
|
beyond its HTTP status code, which RFC 9457 defines as `about:blank`. Problems with their
|
||||||
|
own semantics get their own URI; switch on `code` instead.
|
||||||
|
title:
|
||||||
|
type: string
|
||||||
|
description: Short human-readable summary, the same for all occurrences of this problem type.
|
||||||
|
status:
|
||||||
|
type: integer
|
||||||
|
description: HTTP status code of this response.
|
||||||
|
detail:
|
||||||
|
type: string
|
||||||
|
description: Human-readable explanation specific to this occurrence. Omitted for internal errors.
|
||||||
|
code:
|
||||||
|
type: string
|
||||||
|
description: Machine-readable error code, and the value clients switch on. New codes may be added.
|
||||||
|
enum:
|
||||||
|
- validation
|
||||||
|
- unauthorized
|
||||||
|
- forbidden
|
||||||
|
- not_found
|
||||||
|
- method_not_allowed
|
||||||
|
- unavailable
|
||||||
|
- internal
|
||||||
|
errors:
|
||||||
|
type: array
|
||||||
|
description: Per-field failures. Present only when `code` is `validation`.
|
||||||
|
items:
|
||||||
|
$ref: ./ValidationError.yaml
|
||||||
22
api/openapi/components/schemas/ServerInfo.yaml
Normal file
22
api/openapi/components/schemas/ServerInfo.yaml
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
type: object
|
||||||
|
description: Public server description. Everything an add-server screen needs before login.
|
||||||
|
required: [name, serverVersion, specVersion, setupRequired, loginMethods]
|
||||||
|
properties:
|
||||||
|
name:
|
||||||
|
type: string
|
||||||
|
description: Human-readable server product name.
|
||||||
|
serverVersion:
|
||||||
|
type: string
|
||||||
|
description: Version of the running server build.
|
||||||
|
specVersion:
|
||||||
|
type: string
|
||||||
|
description: Version of the OpenAPI document this server implements.
|
||||||
|
setupRequired:
|
||||||
|
type: boolean
|
||||||
|
description: True until the first admin user has been created.
|
||||||
|
loginMethods:
|
||||||
|
type: array
|
||||||
|
description: Login methods this server accepts. New methods may be added; clients ignore values they do not recognise.
|
||||||
|
items:
|
||||||
|
type: string
|
||||||
|
enum: [password]
|
||||||
10
api/openapi/components/schemas/ValidationError.yaml
Normal file
10
api/openapi/components/schemas/ValidationError.yaml
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
type: object
|
||||||
|
description: One field-level validation failure.
|
||||||
|
required: [field, message]
|
||||||
|
properties:
|
||||||
|
field:
|
||||||
|
type: string
|
||||||
|
description: Name of the offending query parameter, path parameter, or body field (dotted for nested).
|
||||||
|
message:
|
||||||
|
type: string
|
||||||
|
description: Why the value was rejected.
|
||||||
39
api/openapi/openapi.yaml
Normal file
39
api/openapi/openapi.yaml
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
openapi: 3.0.3
|
||||||
|
info:
|
||||||
|
title: Navidrome API
|
||||||
|
version: 1.0.0
|
||||||
|
description: |
|
||||||
|
Navidrome API v1. Spec-first, additive within v1. Clients discover implemented
|
||||||
|
capability modules through `GET /server` and never sniff versions.
|
||||||
|
|
||||||
|
Enums are open: new values may be added to any enum within v1. Clients must
|
||||||
|
accept values they do not recognise instead of failing.
|
||||||
|
|
||||||
|
Every operation declares `x-stability-level`: `alpha` operations may change or
|
||||||
|
disappear without notice, `beta` and `stable` operations only change additively.
|
||||||
|
A level is only ever raised, never lowered.
|
||||||
|
|
||||||
|
`HEAD` is accepted wherever `GET` is. A `405` response lists the allowed methods
|
||||||
|
in its `Allow` header.
|
||||||
|
license:
|
||||||
|
name: GPL-3.0
|
||||||
|
url: https://www.gnu.org/licenses/gpl-3.0.html
|
||||||
|
servers:
|
||||||
|
- url: /api/v1
|
||||||
|
tags:
|
||||||
|
- name: server
|
||||||
|
description: Server discovery and the published OpenAPI document.
|
||||||
|
paths:
|
||||||
|
/server:
|
||||||
|
$ref: ./paths/server.yaml
|
||||||
|
/openapi.json:
|
||||||
|
$ref: ./paths/openapi.yaml#/json
|
||||||
|
/openapi.yaml:
|
||||||
|
$ref: ./paths/openapi.yaml#/yaml
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
bearerAuth:
|
||||||
|
type: http
|
||||||
|
scheme: bearer
|
||||||
|
bearerFormat: JWT
|
||||||
|
description: Short-lived access token minted from a device grant. Not yet applied to any operation.
|
||||||
42
api/openapi/paths/openapi.yaml
Normal file
42
api/openapi/paths/openapi.yaml
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
json:
|
||||||
|
get:
|
||||||
|
operationId: getOpenAPISpecJSON
|
||||||
|
x-module: core
|
||||||
|
x-stability-level: alpha
|
||||||
|
tags: [server]
|
||||||
|
summary: Get the OpenAPI document (JSON)
|
||||||
|
description: The bundled OpenAPI document of the running server version. Supports ETag revalidation.
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: The OpenAPI document.
|
||||||
|
headers:
|
||||||
|
ETag:
|
||||||
|
$ref: ../components/headers/ETag.yaml
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
description: OpenAPI 3.0 document.
|
||||||
|
'304':
|
||||||
|
$ref: ../components/responses/NotModified.yaml
|
||||||
|
yaml:
|
||||||
|
get:
|
||||||
|
operationId: getOpenAPISpecYAML
|
||||||
|
x-module: core
|
||||||
|
x-stability-level: alpha
|
||||||
|
tags: [server]
|
||||||
|
summary: Get the OpenAPI document (YAML)
|
||||||
|
description: The bundled OpenAPI document of the running server version. Supports ETag revalidation.
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: The OpenAPI document.
|
||||||
|
headers:
|
||||||
|
ETag:
|
||||||
|
$ref: ../components/headers/ETag.yaml
|
||||||
|
content:
|
||||||
|
application/yaml:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
description: OpenAPI 3.0 document.
|
||||||
|
'304':
|
||||||
|
$ref: ../components/responses/NotModified.yaml
|
||||||
19
api/openapi/paths/server.yaml
Normal file
19
api/openapi/paths/server.yaml
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
get:
|
||||||
|
operationId: getServerInfo
|
||||||
|
x-module: core
|
||||||
|
x-stability-level: alpha
|
||||||
|
tags: [server]
|
||||||
|
summary: Describe the server
|
||||||
|
description: |
|
||||||
|
Returns the public server description. No authentication required.
|
||||||
|
Authenticated requests will additionally receive the implemented capability modules
|
||||||
|
once authentication is available.
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Server description.
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: ../components/schemas/ServerInfo.yaml
|
||||||
|
'500':
|
||||||
|
$ref: ../components/responses/InternalError.yaml
|
||||||
|
|
@ -174,28 +174,28 @@ func queueTotal(stats []model.ArtworkQueueStat) int64 {
|
||||||
}
|
}
|
||||||
|
|
||||||
func collectStatus(ctx context.Context, ds model.DataStore) (statusReport, error) {
|
func collectStatus(ctx context.Context, ds model.DataStore) (statusReport, error) {
|
||||||
q := ds.ArtworkQueue(ctx)
|
q := ds.ArtworkQueue()
|
||||||
var rep statusReport
|
var rep statusReport
|
||||||
var err error
|
var err error
|
||||||
if rep.queue, err = q.CountQueued(nil, nil); err != nil {
|
if rep.queue, err = q.CountQueued(ctx, nil, nil); err != nil {
|
||||||
return rep, fmt.Errorf("breaking the artwork queue down by kind: %w", err)
|
return rep, fmt.Errorf("breaking the artwork queue down by kind: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, k := range artwork.ReprocessKinds {
|
for _, k := range artwork.ReprocessKinds {
|
||||||
sources, err := q.SourcesInUse(k)
|
sources, err := q.SourcesInUse(ctx, k)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return rep, fmt.Errorf("listing the sources in use by %s artwork: %w", k, err)
|
return rep, fmt.Errorf("listing the sources in use by %s artwork: %w", k, err)
|
||||||
}
|
}
|
||||||
slices.Sort(sources)
|
slices.Sort(sources)
|
||||||
for _, s := range sources {
|
for _, s := range sources {
|
||||||
n, err := q.CountBySource(k, []string{s})
|
n, err := q.CountBySource(ctx, k, []string{s})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return rep, fmt.Errorf("counting %s artwork resolved from %s: %w", k, displaySource(s), err)
|
return rep, fmt.Errorf("counting %s artwork resolved from %s: %w", k, displaySource(s), err)
|
||||||
}
|
}
|
||||||
rep.sources = append(rep.sources, sourceCount{kind: k, source: s, count: n})
|
rep.sources = append(rep.sources, sourceCount{kind: k, source: s, count: n})
|
||||||
// An absent state is exactly a row with no source, so it needs no second query.
|
// An absent state is exactly a row with no source, so it needs no second query.
|
||||||
if s == "" {
|
if s == "" {
|
||||||
failed, err := q.CountBySource(k, []string{model.ArtworkSourceFailed})
|
failed, err := q.CountBySource(ctx, k, []string{model.ArtworkSourceFailed})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return rep, fmt.Errorf("counting failed %s artwork: %w", k, err)
|
return rep, fmt.Errorf("counting failed %s artwork: %w", k, err)
|
||||||
}
|
}
|
||||||
|
|
@ -205,7 +205,7 @@ func collectStatus(ctx context.Context, ds model.DataStore) (statusReport, error
|
||||||
}
|
}
|
||||||
|
|
||||||
rep.current, rep.inputs = artwork.ConfigFingerprint(), artwork.FingerprintInputs()
|
rep.current, rep.inputs = artwork.ConfigFingerprint(), artwork.FingerprintInputs()
|
||||||
if rep.stored, err = ds.Property(ctx).DefaultGet(consts.ArtConfFingerprintPropertyKey, ""); err != nil {
|
if rep.stored, err = ds.Property().DefaultGet(ctx, consts.ArtConfFingerprintPropertyKey, ""); err != nil {
|
||||||
return rep, fmt.Errorf("reading the stored artwork fingerprint: %w", err)
|
return rep, fmt.Errorf("reading the stored artwork fingerprint: %w", err)
|
||||||
}
|
}
|
||||||
return rep, nil
|
return rep, nil
|
||||||
|
|
@ -342,7 +342,7 @@ func selectedKinds(kinds, sources []string, all bool) ([]model.Kind, error) {
|
||||||
return artwork.ReprocessKinds, nil
|
return artwork.ReprocessKinds, nil
|
||||||
}
|
}
|
||||||
if len(kinds) == 0 {
|
if len(kinds) == 0 {
|
||||||
return nil, fmt.Errorf("no selector given: pass --kind, --source or --all")
|
return nil, errors.New("no selector given: pass --kind, --source or --all")
|
||||||
}
|
}
|
||||||
return parseAll(kinds, func(s string) (model.Kind, error) {
|
return parseAll(kinds, func(s string) (model.Kind, error) {
|
||||||
return parseArtworkKind(s, artwork.ReprocessKinds)
|
return parseArtworkKind(s, artwork.ReprocessKinds)
|
||||||
|
|
@ -416,7 +416,7 @@ func needsImageAgents(kinds []model.Kind) bool {
|
||||||
// configuredAgents names the agents in priority order; one absent from it can never supply an image.
|
// configuredAgents names the agents in priority order; one absent from it can never supply an image.
|
||||||
func configuredAgents() []string {
|
func configuredAgents() []string {
|
||||||
var names []string
|
var names []string
|
||||||
for name := range strings.SplitSeq(conf.Server.Agents, ",") {
|
for name := range strings.SplitSeq(conf.Server().Agents, ",") {
|
||||||
if name = strings.TrimSpace(name); name != "" {
|
if name = strings.TrimSpace(name); name != "" {
|
||||||
names = append(names, name)
|
names = append(names, name)
|
||||||
}
|
}
|
||||||
|
|
@ -428,7 +428,7 @@ func promptConfirm(in io.Reader, verb string) confirmFunc {
|
||||||
return func(out io.Writer, total, external int64) bool {
|
return func(out io.Writer, total, external int64) bool {
|
||||||
var cost string
|
var cost string
|
||||||
if external > 0 {
|
if external > 0 {
|
||||||
cost = fmt.Sprintf(" %s", externalLookupLine(external))
|
cost = " " + externalLookupLine(external)
|
||||||
}
|
}
|
||||||
fmt.Fprintf(out, "\nThis will %s %d items.%s Continue? [y/N] ", verb, total, cost)
|
fmt.Fprintf(out, "\nThis will %s %d items.%s Continue? [y/N] ", verb, total, cost)
|
||||||
var answer string
|
var answer string
|
||||||
|
|
@ -442,13 +442,13 @@ func promptConfirm(in io.Reader, verb string) confirmFunc {
|
||||||
|
|
||||||
// validateSources rejects a typo'd source: matching nothing silently reads as "nothing to do" when
|
// validateSources rejects a typo'd source: matching nothing silently reads as "nothing to do" when
|
||||||
// it means the filter was wrong. Checked table-wide, so a filter is never a typo for one --kind only.
|
// it means the filter was wrong. Checked table-wide, so a filter is never a typo for one --kind only.
|
||||||
func validateSources(q model.ArtworkQueueRepository, sources []string) error {
|
func validateSources(ctx context.Context, q model.ArtworkQueueRepository, sources []string) error {
|
||||||
if len(sources) == 0 {
|
if len(sources) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
var inUse []string
|
var inUse []string
|
||||||
for _, k := range artwork.ReprocessKinds {
|
for _, k := range artwork.ReprocessKinds {
|
||||||
found, err := q.SourcesInUse(k)
|
found, err := q.SourcesInUse(ctx, k)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("listing the sources in use by %s artwork: %w", k, err)
|
return fmt.Errorf("listing the sources in use by %s artwork: %w", k, err)
|
||||||
}
|
}
|
||||||
|
|
@ -475,8 +475,8 @@ func validateSources(q model.ArtworkQueueRepository, sources []string) error {
|
||||||
// actually inserted; the two differ because an already-queued row is left untouched.
|
// actually inserted; the two differ because an already-queued row is left untouched.
|
||||||
func reprocessArtwork(ctx context.Context, ds model.DataStore, kinds []model.Kind, sources []string,
|
func reprocessArtwork(ctx context.Context, ds model.DataStore, kinds []model.Kind, sources []string,
|
||||||
imageAgents artwork.ImageAgentCount, dryRun bool, confirm confirmFunc, out io.Writer) error {
|
imageAgents artwork.ImageAgentCount, dryRun bool, confirm confirmFunc, out io.Writer) error {
|
||||||
q := ds.ArtworkQueue(ctx)
|
q := ds.ArtworkQueue()
|
||||||
if err := validateSources(q, sources); err != nil {
|
if err := validateSources(ctx, q, sources); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -495,7 +495,7 @@ func reprocessArtwork(ctx context.Context, ds model.DataStore, kinds []model.Kin
|
||||||
matched := make([]int64, len(kinds))
|
matched := make([]int64, len(kinds))
|
||||||
var total, external int64
|
var total, external int64
|
||||||
for i, k := range kinds {
|
for i, k := range kinds {
|
||||||
n, err := q.CountBySource(k, sources)
|
n, err := q.CountBySource(ctx, k, sources)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("counting %s artwork: %w", k, err)
|
return fmt.Errorf("counting %s artwork: %w", k, err)
|
||||||
}
|
}
|
||||||
|
|
@ -523,7 +523,7 @@ func reprocessArtwork(ctx context.Context, ds model.DataStore, kinds []model.Kin
|
||||||
if matched[i] == 0 {
|
if matched[i] == 0 {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
n, err := q.EnqueueBySource(k, sources, model.ArtworkPriorityRecheck)
|
n, err := q.EnqueueBySource(ctx, k, sources, model.ArtworkPriorityRecheck)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("queueing %s artwork: %w", k, err)
|
return fmt.Errorf("queueing %s artwork: %w", k, err)
|
||||||
}
|
}
|
||||||
|
|
@ -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) {
|
||||||
|
|
@ -590,8 +590,8 @@ func parseAll[T comparable](values []string, parse func(string) (T, error)) ([]T
|
||||||
|
|
||||||
func cancelArtwork(ctx context.Context, ds model.DataStore, kinds []model.Kind, priorities []int,
|
func cancelArtwork(ctx context.Context, ds model.DataStore, kinds []model.Kind, priorities []int,
|
||||||
dryRun bool, confirm confirmFunc, out io.Writer) error {
|
dryRun bool, confirm confirmFunc, out io.Writer) error {
|
||||||
q := ds.ArtworkQueue(ctx)
|
q := ds.ArtworkQueue()
|
||||||
matched, err := q.CountQueued(kinds, priorities)
|
matched, err := q.CountQueued(ctx, kinds, priorities)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("counting queued artwork: %w", err)
|
return fmt.Errorf("counting queued artwork: %w", err)
|
||||||
}
|
}
|
||||||
|
|
@ -612,7 +612,7 @@ func cancelArtwork(ctx context.Context, ds model.DataStore, kinds []model.Kind,
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
cancelled, err := q.PurgeQueued(kinds, priorities)
|
cancelled, err := q.PurgeQueued(ctx, kinds, priorities)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("cancelling queued artwork: %w", err)
|
return fmt.Errorf("cancelling queued artwork: %w", err)
|
||||||
}
|
}
|
||||||
|
|
@ -811,13 +811,13 @@ func explainResult(source string, steps []artwork.TraceStep) string {
|
||||||
func explainConfig(kind model.Kind) (name, value string) {
|
func explainConfig(kind model.Kind) (name, value string) {
|
||||||
switch kind {
|
switch kind {
|
||||||
case model.KindArtistArtwork:
|
case model.KindArtistArtwork:
|
||||||
return "ArtistArtPriority", conf.Server.ArtistArtPriority
|
return "ArtistArtPriority", conf.Server().ArtistArtPriority
|
||||||
case model.KindAlbumArtwork:
|
case model.KindAlbumArtwork:
|
||||||
return "CoverArtPriority", conf.Server.CoverArtPriority
|
return "CoverArtPriority", conf.Server().CoverArtPriority
|
||||||
case model.KindDiscArtwork:
|
case model.KindDiscArtwork:
|
||||||
return "DiscArtPriority", conf.Server.DiscArtPriority
|
return "DiscArtPriority", conf.Server().DiscArtPriority
|
||||||
case model.KindMediaFileArtwork:
|
case model.KindMediaFileArtwork:
|
||||||
return "EnableMediaFileCoverArt", strconv.FormatBool(conf.Server.EnableMediaFileCoverArt)
|
return "EnableMediaFileCoverArt", strconv.FormatBool(conf.Server().EnableMediaFileCoverArt)
|
||||||
}
|
}
|
||||||
return "", ""
|
return "", ""
|
||||||
}
|
}
|
||||||
|
|
@ -984,11 +984,11 @@ func runExplain(ctx context.Context, args []string) {
|
||||||
}
|
}
|
||||||
rep := explainReport{kind: kind, id: id, name: name}
|
rep := explainReport{kind: kind, id: id, name: name}
|
||||||
if artwork.KeepsState(kind) {
|
if artwork.KeepsState(kind) {
|
||||||
rep.stored, err = ds.Artwork(ctx).GetItemArtwork(kind, id, model.ImageTypePrimary)
|
rep.stored, err = ds.Artwork().GetItemArtwork(ctx, kind, id, model.ImageTypePrimary)
|
||||||
if err != nil && !errors.Is(err, model.ErrNotFound) {
|
if err != nil && !errors.Is(err, model.ErrNotFound) {
|
||||||
log.Fatal(ctx, "Failed to read artwork state", "kind", kind, "id", id, err)
|
log.Fatal(ctx, "Failed to read artwork state", "kind", kind, "id", id, err)
|
||||||
}
|
}
|
||||||
rep.queued, err = ds.ArtworkQueue(ctx).Get(kind, id, model.ImageTypePrimary)
|
rep.queued, err = ds.ArtworkQueue().Get(ctx, kind, id, model.ImageTypePrimary)
|
||||||
if err != nil && !errors.Is(err, model.ErrNotFound) {
|
if err != nil && !errors.Is(err, model.ErrNotFound) {
|
||||||
log.Fatal(ctx, "Failed to read the artwork queue", "kind", kind, "id", id, err)
|
log.Fatal(ctx, "Failed to read the artwork queue", "kind", kind, "id", id, err)
|
||||||
}
|
}
|
||||||
|
|
@ -1002,7 +1002,7 @@ func runExplain(ctx context.Context, args []string) {
|
||||||
if kind == model.KindArtistArtwork || kind == model.KindAlbumArtwork {
|
if kind == model.KindArtistArtwork || kind == model.KindAlbumArtwork {
|
||||||
mgr := loadPluginAgents(ctx, explainLive)
|
mgr := loadPluginAgents(ctx, explainLive)
|
||||||
defer func() { _ = mgr.Stop() }()
|
defer func() { _ = mgr.Stop() }()
|
||||||
rep.agents = explainAgents(conf.Server.Agents, availableImageAgents(ds, mgr, kind))
|
rep.agents = explainAgents(conf.Server().Agents, availableImageAgents(ds, mgr, kind))
|
||||||
}
|
}
|
||||||
switch {
|
switch {
|
||||||
case rep.walked:
|
case rep.walked:
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,6 @@ import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/conf"
|
"github.com/navidrome/navidrome/conf"
|
||||||
"github.com/navidrome/navidrome/conf/configtest"
|
|
||||||
"github.com/navidrome/navidrome/consts"
|
"github.com/navidrome/navidrome/consts"
|
||||||
"github.com/navidrome/navidrome/core/artwork"
|
"github.com/navidrome/navidrome/core/artwork"
|
||||||
"github.com/navidrome/navidrome/model"
|
"github.com/navidrome/navidrome/model"
|
||||||
|
|
@ -56,9 +55,10 @@ var _ = Describe("parseArtworkKind", func() {
|
||||||
|
|
||||||
var _ = Describe("resolveArtworkTargets", func() {
|
var _ = Describe("resolveArtworkTargets", func() {
|
||||||
var ds *tests.MockDataStore
|
var ds *tests.MockDataStore
|
||||||
ctx := context.Background()
|
var ctx context.Context
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
artists := tests.CreateMockArtistRepo()
|
artists := tests.CreateMockArtistRepo()
|
||||||
artists.SetData(model.Artists{{ID: "artist1"}})
|
artists.SetData(model.Artists{{ID: "artist1"}})
|
||||||
ds = &tests.MockDataStore{MockedArtist: artists}
|
ds = &tests.MockDataStore{MockedArtist: artists}
|
||||||
|
|
@ -226,8 +226,7 @@ var _ = Describe("formatExplain", func() {
|
||||||
var rep explainReport
|
var rep explainReport
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
DeferCleanup(configtest.SetupConfig())
|
conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external, artist.*" })
|
||||||
conf.Server.ArtistArtPriority = "external, artist.*"
|
|
||||||
rep = explainReport{
|
rep = explainReport{
|
||||||
kind: model.KindArtistArtwork,
|
kind: model.KindArtistArtwork,
|
||||||
id: "ar-1",
|
id: "ar-1",
|
||||||
|
|
@ -289,7 +288,7 @@ var _ = Describe("formatExplain", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("says a kind that does not walk a chain has no chain, without an empty table", func() {
|
It("says a kind that does not walk a chain has no chain, without an empty table", func() {
|
||||||
conf.Server.CoverArtPriority = "cover.*, embedded"
|
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*, embedded" })
|
||||||
rep.kind = model.KindPlaylistArtwork
|
rep.kind = model.KindPlaylistArtwork
|
||||||
rep.steps = nil
|
rep.steps = nil
|
||||||
rep.agents = ""
|
rep.agents = ""
|
||||||
|
|
@ -305,7 +304,7 @@ var _ = Describe("formatExplain", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("says disc artwork keeps no state instead of reporting it as unresolved state", func() {
|
It("says disc artwork keeps no state instead of reporting it as unresolved state", func() {
|
||||||
conf.Server.DiscArtPriority = "cover.jpg, embedded"
|
conf.Update(func(c *conf.Options) { c.DiscArtPriority = "cover.jpg, embedded" })
|
||||||
rep = explainReport{
|
rep = explainReport{
|
||||||
kind: model.KindDiscArtwork, id: "al-1:2", name: "OK Computer (disc 2)",
|
kind: model.KindDiscArtwork, id: "al-1:2", name: "OK Computer (disc 2)",
|
||||||
steps: []artwork.TraceStep{{Candidate: "cover.jpg", Outcome: "hit", Detail: "/music/cover.jpg"}},
|
steps: []artwork.TraceStep{{Candidate: "cover.jpg", Outcome: "hit", Detail: "/music/cover.jpg"}},
|
||||||
|
|
@ -387,7 +386,7 @@ var _ = Describe("formatExplain", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("reports the setting that governs media file artwork", func() {
|
It("reports the setting that governs media file artwork", func() {
|
||||||
conf.Server.EnableMediaFileCoverArt = false
|
conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false })
|
||||||
rep = explainReport{
|
rep = explainReport{
|
||||||
kind: model.KindMediaFileArtwork, id: "mf-1", name: "Airbag",
|
kind: model.KindMediaFileArtwork, id: "mf-1", name: "Airbag",
|
||||||
walked: true,
|
walked: true,
|
||||||
|
|
@ -406,9 +405,10 @@ var _ = Describe("formatExplain", func() {
|
||||||
|
|
||||||
var _ = Describe("explainConfig", func() {
|
var _ = Describe("explainConfig", func() {
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
DeferCleanup(configtest.SetupConfig())
|
conf.Update(func(c *conf.Options) {
|
||||||
conf.Server.DiscArtPriority = "cover.jpg"
|
c.DiscArtPriority = "cover.jpg"
|
||||||
conf.Server.EnableMediaFileCoverArt = true
|
c.EnableMediaFileCoverArt = true
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
DescribeTable("names the setting that decides where a kind's artwork comes from",
|
DescribeTable("names the setting that decides where a kind's artwork comes from",
|
||||||
|
|
@ -425,9 +425,9 @@ var _ = Describe("explainConfig", func() {
|
||||||
|
|
||||||
var _ = Describe("artwork refresh command", func() {
|
var _ = Describe("artwork refresh command", func() {
|
||||||
It("requires at least one argument", func() {
|
It("requires at least one argument", func() {
|
||||||
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{})).To(HaveOccurred())
|
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{})).ToNot(Succeed())
|
||||||
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"id1"})).ToNot(HaveOccurred())
|
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"id1"})).To(Succeed())
|
||||||
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"ar", "id1"})).ToNot(HaveOccurred())
|
Expect(artworkRefreshCmd.Args(artworkRefreshCmd, []string{"ar", "id1"})).To(Succeed())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -475,7 +475,10 @@ var _ = Describe("artwork reprocess selection", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
var _ = Describe("explain/reprocess source round trip", func() {
|
var _ = Describe("explain/reprocess source round trip", func() {
|
||||||
ctx := context.Background()
|
var ctx context.Context
|
||||||
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
|
})
|
||||||
|
|
||||||
// storedSource reads back the Source line explain printed, as an operator would copy it.
|
// storedSource reads back the Source line explain printed, as an operator would copy it.
|
||||||
storedSource := func(out string) string {
|
storedSource := func(out string) string {
|
||||||
|
|
@ -491,17 +494,17 @@ 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 := &tests.MockDataStore{}
|
||||||
art := ds.Artwork(ctx).(*tests.MockArtworkRepo)
|
art := ds.Artwork().(*tests.MockArtworkRepo)
|
||||||
Expect(art.PutItemArtwork(&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())
|
||||||
|
|
||||||
shown := storedSource(formatExplain(explainReport{kind: model.KindArtistArtwork, id: "ar-1",
|
shown := storedSource(formatExplain(explainReport{kind: model.KindArtistArtwork, id: "ar-1",
|
||||||
stored: &model.ItemArtwork{AttemptedAt: time.Now()}}))
|
stored: &model.ItemArtwork{AttemptedAt: time.Now()}}))
|
||||||
|
|
||||||
q := ds.ArtworkQueue(ctx)
|
q := ds.ArtworkQueue()
|
||||||
Expect(validateSources(q, repositorySources([]string{shown}))).To(Succeed(),
|
Expect(validateSources(ctx, q, repositorySources([]string{shown}))).To(Succeed(),
|
||||||
"explain's spelling of a source must be pasteable into --source")
|
"explain's spelling of a source must be pasteable into --source")
|
||||||
Expect(validateSources(q, repositorySources([]string{"(" + shown + ")"}))).ToNot(Succeed(),
|
Expect(validateSources(ctx, q, repositorySources([]string{"(" + shown + ")"}))).ToNot(Succeed(),
|
||||||
"a parenthesised name would be rejected, so explain must not print one")
|
"a parenthesised name would be rejected, so explain must not print one")
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
@ -567,25 +570,27 @@ var _ = Describe("reprocessArtwork", func() {
|
||||||
var queue *tests.MockArtworkQueueRepo
|
var queue *tests.MockArtworkQueueRepo
|
||||||
var out strings.Builder
|
var out strings.Builder
|
||||||
var imageAgents artwork.ImageAgentCount
|
var imageAgents artwork.ImageAgentCount
|
||||||
ctx := context.Background()
|
var ctx context.Context
|
||||||
kinds := []model.Kind{model.KindArtistArtwork, model.KindAlbumArtwork}
|
kinds := []model.Kind{model.KindArtistArtwork, model.KindAlbumArtwork}
|
||||||
accept := func(io.Writer, int64, int64) bool { return true }
|
accept := func(io.Writer, int64, int64) bool { return true }
|
||||||
decline := func(io.Writer, int64, int64) bool { return false }
|
decline := func(io.Writer, int64, int64) bool { return false }
|
||||||
|
|
||||||
put := func(kind model.Kind, id, source string) {
|
put := func(kind model.Kind, id, source string) {
|
||||||
Expect(art.PutItemArtwork(&model.ItemArtwork{ItemKind: kind.Prefix(), ItemID: id,
|
Expect(art.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: kind.Prefix(), ItemID: id,
|
||||||
ImageType: model.ImageTypePrimary, Hash: "h" + id, Source: source})).To(Succeed())
|
ImageType: model.ImageTypePrimary, Hash: "h" + id, Source: source})).To(Succeed())
|
||||||
}
|
}
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
DeferCleanup(configtest.SetupConfig())
|
ctx = GinkgoT().Context()
|
||||||
conf.Server.CoverArtPriority = "cover.*, external"
|
conf.Update(func(c *conf.Options) {
|
||||||
conf.Server.ArtistArtPriority = "artist.*, external"
|
c.CoverArtPriority = "cover.*, external"
|
||||||
conf.Server.EnableM3UExternalAlbumArt = false
|
c.ArtistArtPriority = "artist.*, external"
|
||||||
|
c.EnableM3UExternalAlbumArt = false
|
||||||
|
})
|
||||||
imageAgents = artwork.ImageAgentCount{Artist: 1, Album: 1}
|
imageAgents = artwork.ImageAgentCount{Artist: 1, Album: 1}
|
||||||
ds = &tests.MockDataStore{}
|
ds = &tests.MockDataStore{}
|
||||||
art = ds.Artwork(ctx).(*tests.MockArtworkRepo)
|
art = ds.Artwork().(*tests.MockArtworkRepo)
|
||||||
queue = ds.ArtworkQueue(ctx).(*tests.MockArtworkQueueRepo)
|
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo)
|
||||||
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", "")
|
||||||
|
|
@ -601,19 +606,19 @@ var _ = Describe("reprocessArtwork", func() {
|
||||||
Expect(out.String()).To(ContainSubstring("album"))
|
Expect(out.String()).To(ContainSubstring("album"))
|
||||||
Expect(out.String()).To(ContainSubstring("TOTAL"))
|
Expect(out.String()).To(ContainSubstring("TOTAL"))
|
||||||
Expect(out.String()).To(ContainSubstring("Dry run"))
|
Expect(out.String()).To(ContainSubstring("Dry run"))
|
||||||
Expect(queue.Count()).To(BeZero())
|
Expect(queue.Count(ctx)).To(BeZero())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("queues nothing when the operator declines", func() {
|
It("queues nothing when the operator declines", func() {
|
||||||
Expect(reprocessArtwork(ctx, ds, kinds, nil, imageAgents, false, decline, &out)).To(Succeed())
|
Expect(reprocessArtwork(ctx, ds, kinds, nil, imageAgents, false, decline, &out)).To(Succeed())
|
||||||
|
|
||||||
Expect(out.String()).To(ContainSubstring("Aborted"))
|
Expect(out.String()).To(ContainSubstring("Aborted"))
|
||||||
Expect(queue.Count()).To(BeZero())
|
Expect(queue.Count(ctx)).To(BeZero())
|
||||||
})
|
})
|
||||||
|
|
||||||
DescribeTable("records the applied config only for a run that leaves nothing on the old one",
|
DescribeTable("records the applied config only for a run that leaves nothing on the old one",
|
||||||
func(selected []model.Kind, sources []string, dryRun, applied bool) {
|
func(selected []model.Kind, sources []string, dryRun, applied bool) {
|
||||||
Expect(ds.Property(ctx).Put(consts.ArtConfFingerprintPropertyKey, "stale-fingerprint")).To(Succeed())
|
Expect(ds.Property().Put(ctx, consts.ArtConfFingerprintPropertyKey, "stale-fingerprint")).To(Succeed())
|
||||||
|
|
||||||
Expect(reprocessArtwork(ctx, ds, selected, sources, imageAgents, dryRun, accept, &out)).To(Succeed())
|
Expect(reprocessArtwork(ctx, ds, selected, sources, imageAgents, dryRun, accept, &out)).To(Succeed())
|
||||||
|
|
||||||
|
|
@ -621,7 +626,7 @@ var _ = Describe("reprocessArtwork", func() {
|
||||||
if applied {
|
if applied {
|
||||||
want = artwork.ConfigFingerprint()
|
want = artwork.ConfigFingerprint()
|
||||||
}
|
}
|
||||||
Expect(ds.Property(ctx).Get(consts.ArtConfFingerprintPropertyKey)).To(Equal(want))
|
Expect(ds.Property().Get(ctx, consts.ArtConfFingerprintPropertyKey)).To(Equal(want))
|
||||||
},
|
},
|
||||||
Entry("every kind, unfiltered", artwork.ReprocessKinds, nil, false, true),
|
Entry("every kind, unfiltered", artwork.ReprocessKinds, nil, false, true),
|
||||||
Entry("every kind, but nothing matched", artwork.ReprocessKinds, []string{}, false, true),
|
Entry("every kind, but nothing matched", artwork.ReprocessKinds, []string{}, false, true),
|
||||||
|
|
@ -633,14 +638,14 @@ var _ = Describe("reprocessArtwork", func() {
|
||||||
It("queues the matching items at recheck priority, leaving their artwork state alone", func() {
|
It("queues the matching items at recheck priority, leaving their artwork state alone", func() {
|
||||||
Expect(reprocessArtwork(ctx, ds, kinds, []string{"external:deezer"}, imageAgents, false, accept, &out)).To(Succeed())
|
Expect(reprocessArtwork(ctx, ds, kinds, []string{"external:deezer"}, imageAgents, false, accept, &out)).To(Succeed())
|
||||||
|
|
||||||
Expect(queue.Count()).To(Equal(int64(2)))
|
Expect(queue.Count(ctx)).To(Equal(int64(2)))
|
||||||
queued, err := queue.Get(model.KindAlbumArtwork, "al-1", model.ImageTypePrimary)
|
queued, err := queue.Get(ctx, model.KindAlbumArtwork, "al-1", model.ImageTypePrimary)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(queued.Priority).To(Equal(model.ArtworkPriorityRecheck))
|
Expect(queued.Priority).To(Equal(model.ArtworkPriorityRecheck))
|
||||||
_, err = queue.Get(model.KindAlbumArtwork, "al-2", model.ImageTypePrimary)
|
_, err = queue.Get(ctx, model.KindAlbumArtwork, "al-2", model.ImageTypePrimary)
|
||||||
Expect(err).To(MatchError(model.ErrNotFound), "a non-matching source must not be queued")
|
Expect(err).To(MatchError(model.ErrNotFound), "a non-matching source must not be queued")
|
||||||
|
|
||||||
stored, err := art.GetItemArtwork(model.KindAlbumArtwork, "al-1", model.ImageTypePrimary)
|
stored, err := art.GetItemArtwork(ctx, model.KindAlbumArtwork, "al-1", model.ImageTypePrimary)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(stored.Hash).To(Equal("hal-1"), "bulk reprocessing must not blank the current artwork")
|
Expect(stored.Hash).To(Equal("hal-1"), "bulk reprocessing must not blank the current artwork")
|
||||||
})
|
})
|
||||||
|
|
@ -648,20 +653,20 @@ var _ = Describe("reprocessArtwork", func() {
|
||||||
It("targets the absent state", func() {
|
It("targets the absent state", func() {
|
||||||
Expect(reprocessArtwork(ctx, ds, kinds, []string{""}, imageAgents, false, accept, &out)).To(Succeed())
|
Expect(reprocessArtwork(ctx, ds, kinds, []string{""}, imageAgents, false, accept, &out)).To(Succeed())
|
||||||
|
|
||||||
Expect(queue.Count()).To(Equal(int64(1)))
|
Expect(queue.Count(ctx)).To(Equal(int64(1)))
|
||||||
_, err := queue.Get(model.KindArtistArtwork, "ar-2", model.ImageTypePrimary)
|
_, err := queue.Get(ctx, model.KindArtistArtwork, "ar-2", model.ImageTypePrimary)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("reports matched and queued separately when part of the set is already queued", func() {
|
It("reports matched and queued separately when part of the set is already queued", func() {
|
||||||
Expect(queue.Enqueue(model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar-1",
|
Expect(queue.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar-1",
|
||||||
ImageType: model.ImageTypePrimary, Priority: model.ArtworkPriorityBump})).To(Succeed())
|
ImageType: model.ImageTypePrimary, Priority: model.ArtworkPriorityBump})).To(Succeed())
|
||||||
|
|
||||||
Expect(reprocessArtwork(ctx, ds, kinds, []string{"external:deezer"}, imageAgents, false, accept, &out)).To(Succeed())
|
Expect(reprocessArtwork(ctx, ds, kinds, []string{"external:deezer"}, imageAgents, false, accept, &out)).To(Succeed())
|
||||||
|
|
||||||
Expect(out.String()).To(ContainSubstring("Queued 1 of 2 matched items"))
|
Expect(out.String()).To(ContainSubstring("Queued 1 of 2 matched items"))
|
||||||
Expect(out.String()).To(ContainSubstring("Already queued, left unchanged: 1"))
|
Expect(out.String()).To(ContainSubstring("Already queued, left unchanged: 1"))
|
||||||
queued, err := queue.Get(model.KindArtistArtwork, "ar-1", model.ImageTypePrimary)
|
queued, err := queue.Get(ctx, model.KindArtistArtwork, "ar-1", model.ImageTypePrimary)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(queued.Priority).To(Equal(model.ArtworkPriorityBump),
|
Expect(queued.Priority).To(Equal(model.ArtworkPriorityBump),
|
||||||
"an already-queued row keeps its priority and backoff")
|
"an already-queued row keeps its priority and backoff")
|
||||||
|
|
@ -675,7 +680,7 @@ var _ = Describe("reprocessArtwork", func() {
|
||||||
}, &out)).To(Succeed())
|
}, &out)).To(Succeed())
|
||||||
|
|
||||||
Expect(out.String()).To(ContainSubstring("Nothing"))
|
Expect(out.String()).To(ContainSubstring("Nothing"))
|
||||||
Expect(queue.Count()).To(BeZero())
|
Expect(queue.Count(ctx)).To(BeZero())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("reports an empty selection as a dry run when one was asked for", func() {
|
It("reports an empty selection as a dry run when one was asked for", func() {
|
||||||
|
|
@ -714,7 +719,7 @@ var _ = Describe("reprocessArtwork", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("says so when the selection needs no external lookup", func() {
|
It("says so when the selection needs no external lookup", func() {
|
||||||
conf.Server.CoverArtPriority = "cover.*"
|
conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*" })
|
||||||
put(model.KindPlaylistArtwork, "pl-1", "playlist")
|
put(model.KindPlaylistArtwork, "pl-1", "playlist")
|
||||||
|
|
||||||
Expect(reprocessArtwork(ctx, ds, []model.Kind{model.KindPlaylistArtwork}, nil, imageAgents, true, accept, &out)).To(Succeed())
|
Expect(reprocessArtwork(ctx, ds, []model.Kind{model.KindPlaylistArtwork}, nil, imageAgents, true, accept, &out)).To(Succeed())
|
||||||
|
|
@ -723,8 +728,10 @@ var _ = Describe("reprocessArtwork", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("counts playlists as external cost when the m3u image fetch is enabled", func() {
|
It("counts playlists as external cost when the m3u image fetch is enabled", func() {
|
||||||
conf.Server.CoverArtPriority = "cover.*"
|
conf.Update(func(c *conf.Options) {
|
||||||
conf.Server.EnableM3UExternalAlbumArt = true
|
c.CoverArtPriority = "cover.*"
|
||||||
|
c.EnableM3UExternalAlbumArt = true
|
||||||
|
})
|
||||||
put(model.KindPlaylistArtwork, "pl-1", "playlist")
|
put(model.KindPlaylistArtwork, "pl-1", "playlist")
|
||||||
var external int64
|
var external int64
|
||||||
capture := func(_ io.Writer, _, e int64) bool { external = e; return false }
|
capture := func(_ io.Writer, _, e int64) bool { external = e; return false }
|
||||||
|
|
@ -767,7 +774,7 @@ var _ = Describe("reprocessArtwork", func() {
|
||||||
Expect(err.Error()).To(ContainSubstring("external:deezer"))
|
Expect(err.Error()).To(ContainSubstring("external:deezer"))
|
||||||
Expect(err.Error()).To(ContainSubstring("folder"))
|
Expect(err.Error()).To(ContainSubstring("folder"))
|
||||||
Expect(err.Error()).To(ContainSubstring("absent"), "the empty source prints under its user-facing name")
|
Expect(err.Error()).To(ContainSubstring("absent"), "the empty source prints under its user-facing name")
|
||||||
Expect(queue.Count()).To(BeZero())
|
Expect(queue.Count(ctx)).To(BeZero())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("accepts the absent filter with nothing absent, still rejecting a typo", func() {
|
It("accepts the absent filter with nothing absent, still rejecting a typo", func() {
|
||||||
|
|
@ -777,7 +784,7 @@ var _ = Describe("reprocessArtwork", func() {
|
||||||
imageAgents, false, accept, &out)).To(Succeed(),
|
imageAgents, false, accept, &out)).To(Succeed(),
|
||||||
"a reserved source must stay valid once the library has none of it")
|
"a reserved source must stay valid once the library has none of it")
|
||||||
Expect(out.String()).To(ContainSubstring("Nothing matches"))
|
Expect(out.String()).To(ContainSubstring("Nothing matches"))
|
||||||
Expect(queue.Count()).To(BeZero())
|
Expect(queue.Count(ctx)).To(BeZero())
|
||||||
|
|
||||||
Expect(reprocessArtwork(ctx, ds, kinds, repositorySources([]string{"absnt"}),
|
Expect(reprocessArtwork(ctx, ds, kinds, repositorySources([]string{"absnt"}),
|
||||||
imageAgents, true, accept, &out)).ToNot(Succeed(), "a typo must still be rejected")
|
imageAgents, true, accept, &out)).ToNot(Succeed(), "a typo must still be rejected")
|
||||||
|
|
@ -797,14 +804,14 @@ var _ = Describe("reprocessArtwork", func() {
|
||||||
|
|
||||||
Expect(out.String()).To(ContainSubstring("Nothing matches"),
|
Expect(out.String()).To(ContainSubstring("Nothing matches"),
|
||||||
"a well-formed filter must not be reported as a typo because of the kinds selected")
|
"a well-formed filter must not be reported as a typo because of the kinds selected")
|
||||||
Expect(queue.Count()).To(BeZero())
|
Expect(queue.Count(ctx)).To(BeZero())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
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())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -812,23 +819,24 @@ var _ = Describe("collectStatus", func() {
|
||||||
var ds *tests.MockDataStore
|
var ds *tests.MockDataStore
|
||||||
var art *tests.MockArtworkRepo
|
var art *tests.MockArtworkRepo
|
||||||
var queue *tests.MockArtworkQueueRepo
|
var queue *tests.MockArtworkQueueRepo
|
||||||
ctx := context.Background()
|
var ctx context.Context
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
ds = &tests.MockDataStore{}
|
ds = &tests.MockDataStore{}
|
||||||
art = ds.Artwork(ctx).(*tests.MockArtworkRepo)
|
art = ds.Artwork().(*tests.MockArtworkRepo)
|
||||||
queue = ds.ArtworkQueue(ctx).(*tests.MockArtworkQueueRepo)
|
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo)
|
||||||
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(&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())
|
||||||
}
|
}
|
||||||
put(model.KindArtistArtwork, "ar-1", "external:deezer", "h1", time.Now())
|
put(model.KindArtistArtwork, "ar-1", "external:deezer", "h1", time.Now())
|
||||||
put(model.KindArtistArtwork, "ar-2", "", "", time.Now().Add(-24*time.Hour))
|
put(model.KindArtistArtwork, "ar-2", "", "", time.Now().Add(-24*time.Hour))
|
||||||
// ar-3 is absent because it gave up, so the two absent artists split across the columns.
|
// ar-3 is absent because it gave up, so the two absent artists split across the columns.
|
||||||
Expect(art.PutItemArtwork(&model.ItemArtwork{ItemKind: "ar", ItemID: "ar-3",
|
Expect(art.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "ar", ItemID: "ar-3",
|
||||||
ImageType: model.ImageTypePrimary, LastFailure: "[]", AttemptedAt: time.Now()})).To(Succeed())
|
ImageType: model.ImageTypePrimary, LastFailure: "[]", AttemptedAt: time.Now()})).To(Succeed())
|
||||||
put(model.KindAlbumArtwork, "al-1", "folder", "h2", time.Now())
|
put(model.KindAlbumArtwork, "al-1", "folder", "h2", time.Now())
|
||||||
Expect(queue.Enqueue(model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar-9",
|
Expect(queue.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar-9",
|
||||||
ImageType: model.ImageTypePrimary, Priority: model.ArtworkPriorityBackfill})).To(Succeed())
|
ImageType: model.ImageTypePrimary, Priority: model.ArtworkPriorityBackfill})).To(Succeed())
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -848,7 +856,7 @@ var _ = Describe("collectStatus", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("compares the stored fingerprint against the current one", func() {
|
It("compares the stored fingerprint against the current one", func() {
|
||||||
Expect(ds.Property(ctx).Put(consts.ArtConfFingerprintPropertyKey, "old-fingerprint")).To(Succeed())
|
Expect(ds.Property().Put(ctx, consts.ArtConfFingerprintPropertyKey, "old-fingerprint")).To(Succeed())
|
||||||
|
|
||||||
rep, err := collectStatus(ctx, ds)
|
rep, err := collectStatus(ctx, ds)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
@ -860,7 +868,7 @@ var _ = Describe("collectStatus", func() {
|
||||||
It("queues nothing", func() {
|
It("queues nothing", func() {
|
||||||
_, err := collectStatus(ctx, ds)
|
_, err := collectStatus(ctx, ds)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(queue.Count()).To(Equal(int64(1)), "status must not enqueue anything")
|
Expect(queue.Count(ctx)).To(Equal(int64(1)), "status must not enqueue anything")
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -967,27 +975,28 @@ var _ = Describe("refreshItems", func() {
|
||||||
var queue *tests.MockArtworkQueueRepo
|
var queue *tests.MockArtworkQueueRepo
|
||||||
var art *tests.MockArtworkRepo
|
var art *tests.MockArtworkRepo
|
||||||
var out strings.Builder
|
var out strings.Builder
|
||||||
ctx := context.Background()
|
var ctx context.Context
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
albums := tests.CreateMockAlbumRepo()
|
albums := tests.CreateMockAlbumRepo()
|
||||||
albums.SetData(model.Albums{{ID: "al-1"}, {ID: "al-3"}})
|
albums.SetData(model.Albums{{ID: "al-1"}, {ID: "al-3"}})
|
||||||
ds = &tests.MockDataStore{MockedAlbum: albums}
|
ds = &tests.MockDataStore{MockedAlbum: albums}
|
||||||
art = ds.Artwork(ctx).(*tests.MockArtworkRepo)
|
art = ds.Artwork().(*tests.MockArtworkRepo)
|
||||||
queue = ds.ArtworkQueue(ctx).(*tests.MockArtworkQueueRepo)
|
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo)
|
||||||
out.Reset()
|
out.Reset()
|
||||||
})
|
})
|
||||||
|
|
||||||
It("clears the stored state and queues each id at Bump priority", func() {
|
It("clears the stored state and queues each id at Bump priority", func() {
|
||||||
Expect(art.PutItemArtwork(&model.ItemArtwork{ItemKind: model.KindAlbumArtwork.Prefix(),
|
Expect(art.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: model.KindAlbumArtwork.Prefix(),
|
||||||
ItemID: "al-1", ImageType: model.ImageTypePrimary, Hash: "abc123"})).To(Succeed())
|
ItemID: "al-1", ImageType: model.ImageTypePrimary, Hash: "abc123"})).To(Succeed())
|
||||||
|
|
||||||
Expect(refreshItems(ctx, ds, []model.ArtworkID{
|
Expect(refreshItems(ctx, ds, []model.ArtworkID{
|
||||||
{Kind: model.KindAlbumArtwork, ID: "al-1"}, {Kind: model.KindAlbumArtwork, ID: "al-3"}}, &out)).To(BeZero())
|
{Kind: model.KindAlbumArtwork, ID: "al-1"}, {Kind: model.KindAlbumArtwork, ID: "al-3"}}, &out)).To(BeZero())
|
||||||
|
|
||||||
_, err := art.GetItemArtwork(model.KindAlbumArtwork, "al-1", model.ImageTypePrimary)
|
_, err := art.GetItemArtwork(ctx, model.KindAlbumArtwork, "al-1", model.ImageTypePrimary)
|
||||||
Expect(err).To(MatchError(model.ErrNotFound))
|
Expect(err).To(MatchError(model.ErrNotFound))
|
||||||
queued, err := queue.Get(model.KindAlbumArtwork, "al-1", model.ImageTypePrimary)
|
queued, err := queue.Get(ctx, model.KindAlbumArtwork, "al-1", model.ImageTypePrimary)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(queued.Priority).To(Equal(model.ArtworkPriorityBump))
|
Expect(queued.Priority).To(Equal(model.ArtworkPriorityBump))
|
||||||
Expect(out.String()).To(Equal("al/al-1: queued\nal/al-3: queued\n"))
|
Expect(out.String()).To(Equal("al/al-1: queued\nal/al-3: queued\n"))
|
||||||
|
|
@ -996,7 +1005,7 @@ var _ = Describe("refreshItems", func() {
|
||||||
It("skips an id that does not exist instead of queuing it", func() {
|
It("skips an id that does not exist instead of queuing it", func() {
|
||||||
Expect(refreshItems(ctx, ds, []model.ArtworkID{{Kind: model.KindAlbumArtwork, ID: "al-2"}}, &out)).To(Equal(1))
|
Expect(refreshItems(ctx, ds, []model.ArtworkID{{Kind: model.KindAlbumArtwork, ID: "al-2"}}, &out)).To(Equal(1))
|
||||||
|
|
||||||
_, err := queue.Get(model.KindAlbumArtwork, "al-2", model.ImageTypePrimary)
|
_, err := queue.Get(ctx, model.KindAlbumArtwork, "al-2", model.ImageTypePrimary)
|
||||||
Expect(err).To(MatchError(model.ErrNotFound), "a typo must not leave an orphan queue row")
|
Expect(err).To(MatchError(model.ErrNotFound), "a typo must not leave an orphan queue row")
|
||||||
Expect(out.String()).To(BeEmpty())
|
Expect(out.String()).To(BeEmpty())
|
||||||
})
|
})
|
||||||
|
|
@ -1012,10 +1021,11 @@ var _ = Describe("refreshItems", func() {
|
||||||
|
|
||||||
var _ = Describe("needsImageAgents", func() {
|
var _ = Describe("needsImageAgents", func() {
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
DeferCleanup(configtest.SetupConfig())
|
conf.Update(func(c *conf.Options) {
|
||||||
conf.Server.CoverArtPriority = "cover.*, external"
|
c.CoverArtPriority = "cover.*, external"
|
||||||
conf.Server.ArtistArtPriority = "artist.*, external"
|
c.ArtistArtPriority = "artist.*, external"
|
||||||
conf.Server.EnableM3UExternalAlbumArt = false
|
c.EnableM3UExternalAlbumArt = false
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
It("is false for a selection no agent can serve", func() {
|
It("is false for a selection no agent can serve", func() {
|
||||||
|
|
@ -1033,24 +1043,25 @@ var _ = Describe("needsImageAgents", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("is false once the chains no longer reach an agent", func() {
|
It("is false once the chains no longer reach an agent", func() {
|
||||||
conf.Server.CoverArtPriority = "cover.*"
|
conf.Update(func(c *conf.Options) {
|
||||||
conf.Server.ArtistArtPriority = "artist.*"
|
c.CoverArtPriority = "cover.*"
|
||||||
|
c.ArtistArtPriority = "artist.*"
|
||||||
|
})
|
||||||
Expect(needsImageAgents(artwork.ReprocessKinds)).To(BeFalse())
|
Expect(needsImageAgents(artwork.ReprocessKinds)).To(BeFalse())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
var _ = Describe("configuredAgents", func() {
|
var _ = Describe("configuredAgents", func() {
|
||||||
BeforeEach(func() { DeferCleanup(configtest.SetupConfig()) })
|
|
||||||
|
|
||||||
It("splits and trims the configured list", func() {
|
It("splits and trims the configured list", func() {
|
||||||
conf.Server.Agents = "lastfm, spotify ,deezer"
|
conf.Update(func(c *conf.Options) { c.Agents = "lastfm, spotify ,deezer" })
|
||||||
Expect(configuredAgents()).To(Equal([]string{"lastfm", "spotify", "deezer"}))
|
Expect(configuredAgents()).To(Equal([]string{"lastfm", "spotify", "deezer"}))
|
||||||
})
|
})
|
||||||
|
|
||||||
// An empty name would match no plugin, but it also must not make the list look non-empty:
|
// An empty name would match no plugin, but it also must not make the list look non-empty:
|
||||||
// LoadPlugins treats an empty list as "load nothing".
|
// LoadPlugins treats an empty list as "load nothing".
|
||||||
It("drops empty entries rather than passing a name nothing can match", func() {
|
It("drops empty entries rather than passing a name nothing can match", func() {
|
||||||
conf.Server.Agents = " , ,"
|
conf.Update(func(c *conf.Options) { c.Agents = " , ," })
|
||||||
Expect(configuredAgents()).To(BeEmpty())
|
Expect(configuredAgents()).To(BeEmpty())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
@ -1139,15 +1150,16 @@ var _ = Describe("cancelArtwork", func() {
|
||||||
var ds *tests.MockDataStore
|
var ds *tests.MockDataStore
|
||||||
var queue *tests.MockArtworkQueueRepo
|
var queue *tests.MockArtworkQueueRepo
|
||||||
var out strings.Builder
|
var out strings.Builder
|
||||||
ctx := context.Background()
|
var ctx context.Context
|
||||||
accept := func(io.Writer, int64, int64) bool { return true }
|
accept := func(io.Writer, int64, int64) bool { return true }
|
||||||
decline := func(io.Writer, int64, int64) bool { return false }
|
decline := func(io.Writer, int64, int64) bool { return false }
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
ds = &tests.MockDataStore{}
|
ds = &tests.MockDataStore{}
|
||||||
queue = ds.ArtworkQueue(ctx).(*tests.MockArtworkQueueRepo)
|
queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo)
|
||||||
out.Reset()
|
out.Reset()
|
||||||
Expect(queue.Enqueue(
|
Expect(queue.Enqueue(ctx,
|
||||||
model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar-1", ImageType: model.ImageTypePrimary,
|
model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar-1", ImageType: model.ImageTypePrimary,
|
||||||
Priority: model.ArtworkPriorityBackfill},
|
Priority: model.ArtworkPriorityBackfill},
|
||||||
model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar-2", ImageType: model.ImageTypePrimary,
|
model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar-2", ImageType: model.ImageTypePrimary,
|
||||||
|
|
@ -1164,28 +1176,28 @@ var _ = Describe("cancelArtwork", func() {
|
||||||
Expect(out.String()).To(ContainSubstring("backfill"))
|
Expect(out.String()).To(ContainSubstring("backfill"))
|
||||||
Expect(out.String()).To(ContainSubstring("TOTAL"))
|
Expect(out.String()).To(ContainSubstring("TOTAL"))
|
||||||
Expect(out.String()).To(ContainSubstring("Dry run"))
|
Expect(out.String()).To(ContainSubstring("Dry run"))
|
||||||
Expect(queue.Count()).To(BeNumerically("==", 3))
|
Expect(queue.Count(ctx)).To(BeNumerically("==", 3))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("cancels nothing when the operator declines", func() {
|
It("cancels nothing when the operator declines", func() {
|
||||||
Expect(cancelArtwork(ctx, ds, nil, nil, false, decline, &out)).To(Succeed())
|
Expect(cancelArtwork(ctx, ds, nil, nil, false, decline, &out)).To(Succeed())
|
||||||
|
|
||||||
Expect(out.String()).To(ContainSubstring("Aborted"))
|
Expect(out.String()).To(ContainSubstring("Aborted"))
|
||||||
Expect(queue.Count()).To(BeNumerically("==", 3))
|
Expect(queue.Count(ctx)).To(BeNumerically("==", 3))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("deletes the selected rows and leaves the rest queued", func() {
|
It("deletes the selected rows and leaves the rest queued", func() {
|
||||||
Expect(cancelArtwork(ctx, ds, nil, []int{model.ArtworkPriorityBackfill}, false, accept, &out)).To(Succeed())
|
Expect(cancelArtwork(ctx, ds, nil, []int{model.ArtworkPriorityBackfill}, false, accept, &out)).To(Succeed())
|
||||||
|
|
||||||
Expect(queue.Count()).To(BeNumerically("==", 1))
|
Expect(queue.Count(ctx)).To(BeNumerically("==", 1))
|
||||||
_, err := queue.Get(model.KindArtistArtwork, "ar-2", model.ImageTypePrimary)
|
_, err := queue.Get(ctx, model.KindArtistArtwork, "ar-2", model.ImageTypePrimary)
|
||||||
Expect(err).ToNot(HaveOccurred(), "a non-matching priority must stay queued")
|
Expect(err).ToNot(HaveOccurred(), "a non-matching priority must stay queued")
|
||||||
Expect(out.String()).To(ContainSubstring("Cancelled 2 of 2 matched items."))
|
Expect(out.String()).To(ContainSubstring("Cancelled 2 of 2 matched items."))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("cancels every kind and priority when neither filter is given", func() {
|
It("cancels every kind and priority when neither filter is given", func() {
|
||||||
Expect(cancelArtwork(ctx, ds, nil, nil, false, accept, &out)).To(Succeed())
|
Expect(cancelArtwork(ctx, ds, nil, nil, false, accept, &out)).To(Succeed())
|
||||||
Expect(queue.Count()).To(BeZero())
|
Expect(queue.Count(ctx)).To(BeZero())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("stops at a selection that matches nothing instead of prompting", func() {
|
It("stops at a selection that matches nothing instead of prompting", func() {
|
||||||
|
|
@ -1196,7 +1208,7 @@ var _ = Describe("cancelArtwork", func() {
|
||||||
Expect(cancelArtwork(ctx, ds, []model.Kind{model.KindPlaylistArtwork}, nil, false, refuse, &out)).To(Succeed())
|
Expect(cancelArtwork(ctx, ds, []model.Kind{model.KindPlaylistArtwork}, nil, false, refuse, &out)).To(Succeed())
|
||||||
|
|
||||||
Expect(out.String()).To(ContainSubstring("Nothing matches this selection."))
|
Expect(out.String()).To(ContainSubstring("Nothing matches this selection."))
|
||||||
Expect(queue.Count()).To(BeNumerically("==", 3))
|
Expect(queue.Count(ctx)).To(BeNumerically("==", 3))
|
||||||
})
|
})
|
||||||
|
|
||||||
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() {
|
||||||
|
|
|
||||||
|
|
@ -2,9 +2,7 @@ package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"path/filepath"
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/conf"
|
"github.com/navidrome/navidrome/conf"
|
||||||
|
|
@ -17,6 +15,7 @@ var (
|
||||||
backupCount int
|
backupCount int
|
||||||
backupDir string
|
backupDir string
|
||||||
force bool
|
force bool
|
||||||
|
integrityCheck bool
|
||||||
restorePath string
|
restorePath string
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -31,8 +30,9 @@ func init() {
|
||||||
pruneCmd.Flags().BoolVarP(&force, "force", "f", false, "bypass warning when backup count is zero")
|
pruneCmd.Flags().BoolVarP(&force, "force", "f", false, "bypass warning when backup count is zero")
|
||||||
backupRoot.AddCommand(pruneCmd)
|
backupRoot.AddCommand(pruneCmd)
|
||||||
|
|
||||||
restoreCommand.Flags().StringVarP(&restorePath, "backup-file", "b", "", "path of backup database to restore")
|
restoreCommand.Flags().StringVarP(&restorePath, "backup-file", "b", "", "file name of the backup database to restore (resolved against the backup directory unless it is an absolute path)")
|
||||||
restoreCommand.Flags().BoolVarP(&force, "force", "f", false, "bypass restore warning")
|
restoreCommand.Flags().BoolVarP(&force, "force", "f", false, "bypass restore warning")
|
||||||
|
restoreCommand.Flags().BoolVarP(&integrityCheck, "integrity-check", "i", false, "check the backup file with a full integrity check before restoring. Finds more kinds of damage, but takes longer")
|
||||||
_ = restoreCommand.MarkFlagRequired("backup-file")
|
_ = restoreCommand.MarkFlagRequired("backup-file")
|
||||||
backupRoot.AddCommand(restoreCommand)
|
backupRoot.AddCommand(restoreCommand)
|
||||||
}
|
}
|
||||||
|
|
@ -75,27 +75,15 @@ var (
|
||||||
|
|
||||||
func runBackup(ctx context.Context) {
|
func runBackup(ctx context.Context) {
|
||||||
if backupDir != "" {
|
if backupDir != "" {
|
||||||
conf.Server.Backup.Path = conf.NewDir(backupDir)
|
conf.Update(func(c *conf.Options) { c.Backup.Path = conf.NewDir(backupDir) })
|
||||||
}
|
}
|
||||||
|
|
||||||
idx := strings.LastIndex(conf.Server.DbPath, "?")
|
requireExistingDB()
|
||||||
var path string
|
|
||||||
|
|
||||||
if idx == -1 {
|
|
||||||
path = conf.Server.DbPath
|
|
||||||
} else {
|
|
||||||
path = conf.Server.DbPath[:idx]
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
|
||||||
log.Fatal("No existing database", "path", path)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
path, err := db.Backup(ctx)
|
path, err := db.Backup(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("Error backing up database", "backup path", conf.Server.BasePath, err)
|
log.Fatal("Error backing up database", "backupPath", conf.Server().Backup.Path, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
elapsed := time.Since(start)
|
elapsed := time.Since(start)
|
||||||
|
|
@ -103,44 +91,26 @@ func runBackup(ctx context.Context) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func runPrune(ctx context.Context) {
|
func runPrune(ctx context.Context) {
|
||||||
|
conf.Update(func(c *conf.Options) {
|
||||||
if backupDir != "" {
|
if backupDir != "" {
|
||||||
conf.Server.Backup.Path = conf.NewDir(backupDir)
|
c.Backup.Path = conf.NewDir(backupDir)
|
||||||
}
|
}
|
||||||
|
|
||||||
if backupCount != -1 {
|
if backupCount != -1 {
|
||||||
conf.Server.Backup.Count = backupCount
|
c.Backup.Count = backupCount
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
|
||||||
if conf.Server.Backup.Count == 0 && !force {
|
if conf.Server().Backup.Count == 0 && !force && !confirmYES("Warning: pruning ALL backups") {
|
||||||
fmt.Println("Warning: pruning ALL backups")
|
|
||||||
fmt.Printf("Please enter YES (all caps) to continue: ")
|
|
||||||
var input string
|
|
||||||
_, err := fmt.Scanln(&input)
|
|
||||||
|
|
||||||
if input != "YES" || err != nil {
|
|
||||||
log.Warn("Prune cancelled")
|
log.Warn("Prune cancelled")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
idx := strings.LastIndex(conf.Server.DbPath, "?")
|
requireExistingDB()
|
||||||
var path string
|
|
||||||
|
|
||||||
if idx == -1 {
|
|
||||||
path = conf.Server.DbPath
|
|
||||||
} else {
|
|
||||||
path = conf.Server.DbPath[:idx]
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
|
||||||
log.Fatal("No existing database", "path", path)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
count, err := db.Prune(ctx)
|
count, err := db.Prune(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("Error pruning up database", "backup path", conf.Server.BasePath, err)
|
log.Fatal("Error pruning database", "backupPath", conf.Server().Backup.Path, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
elapsed := time.Since(start)
|
elapsed := time.Since(start)
|
||||||
|
|
@ -149,36 +119,29 @@ func runPrune(ctx context.Context) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func runRestore(ctx context.Context) {
|
func runRestore(ctx context.Context) {
|
||||||
idx := strings.LastIndex(conf.Server.DbPath, "?")
|
requireExistingDB()
|
||||||
var path string
|
|
||||||
|
|
||||||
if idx == -1 {
|
// A relative --backup-file is resolved against Backup.Path, the same folder
|
||||||
path = conf.Server.DbPath
|
// `backup create` writes to. Without this, the value was treated as relative
|
||||||
} else {
|
// to the working directory, where the file does not exist.
|
||||||
path = conf.Server.DbPath[:idx]
|
if !filepath.IsAbs(restorePath) {
|
||||||
}
|
backupPath, err := conf.Server().Backup.Path.Path()
|
||||||
|
if err != nil {
|
||||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
log.Fatal("Backup directory not available", "backupPath", conf.Server().Backup.Path, err)
|
||||||
log.Fatal("No existing database", "path", path)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
restorePath = filepath.Join(backupPath, restorePath)
|
||||||
|
}
|
||||||
|
|
||||||
if !force {
|
if !force && !confirmYES("Warning: restoring the Navidrome database should only be done offline, especially if your backup is very old.") {
|
||||||
fmt.Println("Warning: restoring the Navidrome database should only be done offline, especially if your backup is very old.")
|
|
||||||
fmt.Printf("Please enter YES (all caps) to continue: ")
|
|
||||||
var input string
|
|
||||||
_, err := fmt.Scanln(&input)
|
|
||||||
|
|
||||||
if input != "YES" || err != nil {
|
|
||||||
log.Warn("Restore cancelled")
|
log.Warn("Restore cancelled")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
err := db.Restore(ctx, restorePath)
|
err := db.Restore(ctx, restorePath, integrityCheck)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("Error restoring database", "backup path", conf.Server.BasePath, err)
|
log.Fatal("Error restoring database", "backupFile", restorePath, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
elapsed := time.Since(start)
|
elapsed := time.Since(start)
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ package cmd
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/conf/configtest"
|
||||||
"github.com/navidrome/navidrome/log"
|
"github.com/navidrome/navidrome/log"
|
||||||
"github.com/navidrome/navidrome/tests"
|
"github.com/navidrome/navidrome/tests"
|
||||||
. "github.com/onsi/ginkgo/v2"
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
|
@ -15,3 +16,5 @@ func TestCmd(t *testing.T) {
|
||||||
RegisterFailHandler(Fail)
|
RegisterFailHandler(Fail)
|
||||||
RunSpecs(t, "Cmd Suite")
|
RunSpecs(t, "Cmd Suite")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ = configtest.RestoreAfterEachSpec()
|
||||||
|
|
|
||||||
99
cmd/doctor.go
Normal file
99
cmd/doctor.go
Normal file
|
|
@ -0,0 +1,99 @@
|
||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/db"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
rootCmd.AddCommand(doctorCmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
var doctorCmd = &cobra.Command{
|
||||||
|
Use: "doctor",
|
||||||
|
Short: "Check your Navidrome installation for problems",
|
||||||
|
Long: "Run read-only health checks and report what was found. Checks the database for " +
|
||||||
|
"corruption and foreign key violations, and reports whether 'navidrome search rebuild' " +
|
||||||
|
"can fix what it finds. This command never alters your data",
|
||||||
|
Run: func(cmd *cobra.Command, _ []string) {
|
||||||
|
runDoctor(cmd.Context())
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func runDoctor(ctx context.Context) {
|
||||||
|
requireExistingDB()
|
||||||
|
|
||||||
|
healthy := doctor(ctx, db.Db(), os.Stdout)
|
||||||
|
db.Close(ctx)
|
||||||
|
if !healthy {
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const recoveryAdvice = "Restore a backup (navidrome backup restore), or try SQLite's '.recover' command."
|
||||||
|
|
||||||
|
func printFindings(out io.Writer, check, noun string, items []string) {
|
||||||
|
fmt.Fprintf(out, "%s reported %d %s:\n", check, len(items), noun)
|
||||||
|
for _, item := range items {
|
||||||
|
fmt.Fprintln(out, " "+item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func doctor(ctx context.Context, database *sql.DB, out io.Writer) bool {
|
||||||
|
healthy := true
|
||||||
|
|
||||||
|
fmt.Fprintln(out, "Checking database integrity...")
|
||||||
|
issues, truncated, err := db.IntegrityCheck(ctx, database)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
fmt.Fprintln(out, "The integrity check could not complete: "+err.Error())
|
||||||
|
fmt.Fprintln(out, recoveryAdvice)
|
||||||
|
return false
|
||||||
|
case len(issues) == 0:
|
||||||
|
fmt.Fprintln(out, "Integrity check passed.")
|
||||||
|
default:
|
||||||
|
healthy = false
|
||||||
|
printFindings(out, "Integrity check", "issue(s)", issues)
|
||||||
|
switch {
|
||||||
|
case truncated:
|
||||||
|
fmt.Fprintln(out, "The integrity check stopped at its limit, so the damage may reach further than listed.")
|
||||||
|
fmt.Fprintln(out, recoveryAdvice)
|
||||||
|
case db.IsFTSCorruptionOnly(issues):
|
||||||
|
fmt.Fprintln(out, "Corruption is limited to the search index. Run 'navidrome search rebuild' to fix it.")
|
||||||
|
default:
|
||||||
|
fmt.Fprintln(out, "Corruption is not limited to the search index, and cannot be repaired automatically.")
|
||||||
|
fmt.Fprintln(out, recoveryAdvice)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintln(out, "Checking foreign keys...")
|
||||||
|
violations, err := db.ForeignKeyCheck(ctx, database)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
healthy = false
|
||||||
|
fmt.Fprintln(out, "The foreign key check could not complete: "+err.Error())
|
||||||
|
case len(violations) == 0:
|
||||||
|
fmt.Fprintln(out, "Foreign key check passed.")
|
||||||
|
default:
|
||||||
|
healthy = false
|
||||||
|
lines := make([]string, 0, len(violations))
|
||||||
|
for _, v := range violations {
|
||||||
|
lines = append(lines,
|
||||||
|
fmt.Sprintf("%s: %d row(s) reference missing rows in %s", v.Table, v.Count, v.Parent))
|
||||||
|
}
|
||||||
|
printFindings(out, "Foreign key check", "violation(s)", lines)
|
||||||
|
fmt.Fprintln(out, "These are orphaned rows, not corruption. 'navidrome scan -f' clears some of them "+
|
||||||
|
"in library data; the rest have to be removed by hand.")
|
||||||
|
}
|
||||||
|
|
||||||
|
if healthy {
|
||||||
|
fmt.Fprintln(out, "Database is healthy.")
|
||||||
|
}
|
||||||
|
return healthy
|
||||||
|
}
|
||||||
124
cmd/doctor_test.go
Normal file
124
cmd/doctor_test.go
Normal file
|
|
@ -0,0 +1,124 @@
|
||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/db"
|
||||||
|
|
||||||
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
. "github.com/onsi/gomega"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ = Describe("doctor", func() {
|
||||||
|
var (
|
||||||
|
ctx context.Context
|
||||||
|
dbPath string
|
||||||
|
database *sql.DB
|
||||||
|
out *strings.Builder
|
||||||
|
reopen func()
|
||||||
|
)
|
||||||
|
|
||||||
|
// A file-backed DB so specs can corrupt raw pages; a table named like a real FTS
|
||||||
|
// search table so IsFTSCorruptionOnly matches, plus a parent/child pair for FK checks.
|
||||||
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
|
dbPath = filepath.Join(GinkgoT().TempDir(), "doctor.db")
|
||||||
|
reopen = func() {
|
||||||
|
var err error
|
||||||
|
database, err = sql.Open(db.Dialect, dbPath)
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
database.SetMaxOpenConns(1)
|
||||||
|
}
|
||||||
|
reopen()
|
||||||
|
DeferCleanup(func() { _ = database.Close() })
|
||||||
|
|
||||||
|
for _, stmt := range []string{
|
||||||
|
`create virtual table media_file_fts using fts5(title, content='', content_rowid='rowid')`,
|
||||||
|
`insert into media_file_fts(rowid, title) values (1, 'teenage lobotomy'), (2, 'rockaway beach')`,
|
||||||
|
`create table library(id integer primary key)`,
|
||||||
|
`create table media_file(id integer primary key, library_id integer references library(id))`,
|
||||||
|
} {
|
||||||
|
_, err := database.ExecContext(ctx, stmt)
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
}
|
||||||
|
out = &strings.Builder{}
|
||||||
|
})
|
||||||
|
|
||||||
|
It("reports a healthy database", func() {
|
||||||
|
Expect(doctor(ctx, database, out)).To(BeTrue())
|
||||||
|
Expect(out.String()).To(ContainSubstring("Database is healthy."))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("points to 'search rebuild' when corruption is limited to the search index", func() {
|
||||||
|
_, err := database.ExecContext(ctx,
|
||||||
|
`update media_file_fts_data set block = x'deadbeefdeadbeef' where id > 1`)
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
||||||
|
Expect(doctor(ctx, database, out)).To(BeFalse())
|
||||||
|
Expect(out.String()).To(ContainSubstring("navidrome search rebuild"))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("points to a backup restore when corruption is not limited to the search index", func() {
|
||||||
|
_, err := database.ExecContext(ctx,
|
||||||
|
`insert into library(id)
|
||||||
|
with recursive s(x) as (select 1 union all select x+1 from s where x < 200)
|
||||||
|
select x from s`)
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
var rootPage, pageSize int64
|
||||||
|
Expect(database.QueryRowContext(ctx,
|
||||||
|
`select rootpage from sqlite_master where name = 'library'`).Scan(&rootPage)).To(Succeed())
|
||||||
|
Expect(database.QueryRowContext(ctx, `pragma page_size`).Scan(&pageSize)).To(Succeed())
|
||||||
|
Expect(database.Close()).To(Succeed())
|
||||||
|
f, err := os.OpenFile(dbPath, os.O_WRONLY, 0600)
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
_, err = f.WriteAt([]byte{0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef}, (rootPage-1)*pageSize+40)
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
Expect(f.Close()).To(Succeed())
|
||||||
|
reopen()
|
||||||
|
|
||||||
|
Expect(doctor(ctx, database, out)).To(BeFalse())
|
||||||
|
Expect(out.String()).To(ContainSubstring("backup restore"))
|
||||||
|
Expect(out.String()).ToNot(ContainSubstring("search rebuild"))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("reports foreign key violations", func() {
|
||||||
|
_, err := database.ExecContext(ctx, `pragma foreign_keys = off`)
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
_, err = database.ExecContext(ctx, `insert into media_file(id, library_id) values (1, 999)`)
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
|
||||||
|
Expect(doctor(ctx, database, out)).To(BeFalse())
|
||||||
|
Expect(out.String()).To(ContainSubstring("Foreign key check reported"))
|
||||||
|
Expect(out.String()).To(ContainSubstring("media_file"))
|
||||||
|
Expect(out.String()).To(ContainSubstring("navidrome scan -f"))
|
||||||
|
// GC never touches player, share or playqueue, so don't promise a full cleanup.
|
||||||
|
Expect(out.String()).To(ContainSubstring("removed by hand"))
|
||||||
|
})
|
||||||
|
|
||||||
|
// Every issue names an FTS-like index, so IsFTSCorruptionOnly alone would send the
|
||||||
|
// user to 'search rebuild', but the pragma stopped at its limit without saying so.
|
||||||
|
It("does not blame the search index when the issue list is truncated", func() {
|
||||||
|
for _, stmt := range []string{
|
||||||
|
`create table t(a, b)`,
|
||||||
|
`with recursive s(x) as (select 1 union all select x+1 from s where x < 300)
|
||||||
|
insert into t select x, x + 10000 from s`,
|
||||||
|
`create index media_file_fts_probe on t(a)`,
|
||||||
|
`pragma writable_schema=on`,
|
||||||
|
`update sqlite_master set sql = 'CREATE INDEX media_file_fts_probe ON t(b)'
|
||||||
|
where name = 'media_file_fts_probe'`,
|
||||||
|
} {
|
||||||
|
_, err := database.ExecContext(ctx, stmt)
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
}
|
||||||
|
Expect(database.Close()).To(Succeed())
|
||||||
|
reopen()
|
||||||
|
|
||||||
|
Expect(doctor(ctx, database, out)).To(BeFalse())
|
||||||
|
Expect(out.String()).ToNot(ContainSubstring("search rebuild"))
|
||||||
|
Expect(out.String()).To(ContainSubstring("backup restore"))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -1,13 +1,17 @@
|
||||||
package cmd
|
package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/core"
|
"github.com/navidrome/navidrome/core"
|
||||||
|
"github.com/navidrome/navidrome/db"
|
||||||
"github.com/navidrome/navidrome/log"
|
"github.com/navidrome/navidrome/log"
|
||||||
"github.com/navidrome/navidrome/model"
|
"github.com/navidrome/navidrome/model"
|
||||||
|
"github.com/navidrome/navidrome/persistence"
|
||||||
"github.com/pelletier/go-toml/v2"
|
"github.com/pelletier/go-toml/v2"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
|
|
@ -28,7 +32,7 @@ var inspectCmd = &cobra.Command{
|
||||||
Long: "Show file tags as seen by Navidrome",
|
Long: "Show file tags as seen by Navidrome",
|
||||||
Args: cobra.MinimumNArgs(1),
|
Args: cobra.MinimumNArgs(1),
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
runInspector(args)
|
runInspector(cmd.Context(), args)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -46,27 +50,33 @@ func prettyMarshal(v any) ([]byte, error) {
|
||||||
out := v.([]core.InspectOutput)
|
out := v.([]core.InspectOutput)
|
||||||
var res strings.Builder
|
var res strings.Builder
|
||||||
for i := range out {
|
for i := range out {
|
||||||
res.WriteString(fmt.Sprintf("====================\nFile: %s\n\n", out[i].File))
|
fmt.Fprintf(&res, "====================\nFile: %s\n\n", out[i].File)
|
||||||
t, _ := toml.Marshal(out[i].RawTags)
|
t, _ := toml.Marshal(out[i].RawTags)
|
||||||
res.WriteString(fmt.Sprintf("Raw tags:\n%s\n\n", t))
|
fmt.Fprintf(&res, "Raw tags:\n%s\n\n", t)
|
||||||
t, _ = toml.Marshal(out[i].MappedTags)
|
t, _ = toml.Marshal(out[i].MappedTags)
|
||||||
res.WriteString(fmt.Sprintf("Mapped tags:\n%s\n\n", t))
|
fmt.Fprintf(&res, "Mapped tags:\n%s\n\n", t)
|
||||||
}
|
}
|
||||||
return []byte(res.String()), nil
|
return []byte(res.String()), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func runInspector(args []string) {
|
func runInspector(ctx context.Context, args []string) {
|
||||||
marshal := marshalers[format]
|
marshal := marshalers[format]
|
||||||
if marshal == nil {
|
if marshal == nil {
|
||||||
log.Fatal("Invalid format", "format", format)
|
log.Fatal("Invalid format", "format", format)
|
||||||
}
|
}
|
||||||
|
libs := loadLibraries(ctx)
|
||||||
|
matcher := model.NewLibraryMatcher(libs)
|
||||||
var out []core.InspectOutput
|
var out []core.InspectOutput
|
||||||
for _, filePath := range args {
|
for _, filePath := range args {
|
||||||
if !model.IsAudioFile(filePath) {
|
if !model.IsAudioFile(filePath) {
|
||||||
log.Warn("Not an audio file", "file", filePath)
|
log.Warn("Not an audio file", "file", filePath)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
output, err := core.Inspect(filePath, 1, "")
|
lib, ok := libraryForFile(matcher, filePath)
|
||||||
|
if !ok && len(libs) > 0 {
|
||||||
|
log.Warn("File is not in any library, using the global PID config", "file", filePath)
|
||||||
|
}
|
||||||
|
output, err := core.Inspect(filePath, lib, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warn("Unable to process file", "file", filePath, "error", err)
|
log.Warn("Unable to process file", "file", filePath, "error", err)
|
||||||
continue
|
continue
|
||||||
|
|
@ -77,3 +87,33 @@ func runInspector(args []string) {
|
||||||
data, _ := marshal(out)
|
data, _ := marshal(out)
|
||||||
fmt.Println(string(data))
|
fmt.Println(string(data))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// loadLibraries reads the libraries, so each file gets its library's PID config. It never creates a DB.
|
||||||
|
func loadLibraries(ctx context.Context) model.Libraries {
|
||||||
|
if dbFile, ok := existingDBFile(); !ok {
|
||||||
|
log.Warn(ctx, "No database found, using the global PID config", "path", dbFile)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
defer db.Init(ctx)()
|
||||||
|
libs, err := persistence.New(db.Db()).Library().GetAll(ctx)
|
||||||
|
if err != nil {
|
||||||
|
log.Warn(ctx, "Could not load libraries, using the global PID config", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for i := range libs {
|
||||||
|
if absPath, err := filepath.Abs(libs[i].Path); err == nil {
|
||||||
|
libs[i].Path = absPath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return libs
|
||||||
|
}
|
||||||
|
|
||||||
|
// libraryForFile falls back to the default library with no overrides, which uses the global PID config.
|
||||||
|
func libraryForFile(matcher *model.LibraryMatcher, filePath string) (model.Library, bool) {
|
||||||
|
if absPath, err := filepath.Abs(filePath); err == nil {
|
||||||
|
if lib, ok := matcher.FindLibrary(absPath); ok {
|
||||||
|
return lib, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return model.Library{ID: model.DefaultLibraryID}, false
|
||||||
|
}
|
||||||
|
|
|
||||||
57
cmd/inspect_test.go
Normal file
57
cmd/inspect_test.go
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/conf"
|
||||||
|
"github.com/navidrome/navidrome/model"
|
||||||
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
. "github.com/onsi/gomega"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ = Describe("inspect", func() {
|
||||||
|
Describe("libraryForFile", func() {
|
||||||
|
var matcher *model.LibraryMatcher
|
||||||
|
var root string
|
||||||
|
|
||||||
|
BeforeEach(func() {
|
||||||
|
root = GinkgoT().TempDir()
|
||||||
|
cwd, err := os.Getwd()
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
matcher = model.NewLibraryMatcher(model.Libraries{
|
||||||
|
{ID: 1, Path: filepath.Join(root, "music")},
|
||||||
|
{ID: 2, Path: filepath.Join(cwd, "loose"), PIDAlbum: "folder"},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
It("returns the library that contains an absolute path", func() {
|
||||||
|
lib, ok := libraryForFile(matcher, filepath.Join(root, "music", "album", "track.mp3"))
|
||||||
|
Expect(ok).To(BeTrue())
|
||||||
|
Expect(lib.ID).To(Equal(1))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("resolves a relative path against the working directory", func() {
|
||||||
|
lib, ok := libraryForFile(matcher, filepath.Join("loose", "track.mp3"))
|
||||||
|
Expect(ok).To(BeTrue())
|
||||||
|
Expect(lib.PIDAlbum).To(Equal("folder"))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("falls back to the default library without overrides", func() {
|
||||||
|
lib, ok := libraryForFile(matcher, filepath.Join(root, "elsewhere", "track.mp3"))
|
||||||
|
Expect(ok).To(BeFalse())
|
||||||
|
Expect(lib).To(Equal(model.Library{ID: model.DefaultLibraryID}))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
Describe("loadLibraries", func() {
|
||||||
|
|
||||||
|
It("does not create a database when there is none", func() {
|
||||||
|
dbFile := filepath.Join(GinkgoT().TempDir(), "navidrome.db")
|
||||||
|
conf.Update(func(c *conf.Options) { c.DbPath = dbFile + "?_journal_mode=WAL" })
|
||||||
|
|
||||||
|
Expect(loadLibraries(GinkgoT().Context())).To(BeNil())
|
||||||
|
Expect(dbFile).ToNot(BeAnExistingFile())
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
174
cmd/missing.go
Normal file
174
cmd/missing.go
Normal file
|
|
@ -0,0 +1,174 @@
|
||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"encoding/csv"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Masterminds/squirrel"
|
||||||
|
"github.com/navidrome/navidrome/core"
|
||||||
|
"github.com/navidrome/navidrome/log"
|
||||||
|
"github.com/navidrome/navidrome/model"
|
||||||
|
"github.com/navidrome/navidrome/utils/slice"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
var missingListFormat string
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
missingListCmd.Flags().StringVarP(&missingListFormat, "format", "f", "csv", "output format [supported values: csv, json]")
|
||||||
|
missingCmd.AddCommand(missingListCmd)
|
||||||
|
missingCmd.AddCommand(missingFixCmd)
|
||||||
|
rootCmd.AddCommand(missingCmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
missingCmd = &cobra.Command{
|
||||||
|
Use: "missing",
|
||||||
|
Short: "Manage missing files",
|
||||||
|
Long: "List files marked as missing and remap them onto existing files",
|
||||||
|
}
|
||||||
|
|
||||||
|
missingListCmd = &cobra.Command{
|
||||||
|
Use: "list",
|
||||||
|
Short: "List missing files",
|
||||||
|
Run: func(cmd *cobra.Command, _ []string) {
|
||||||
|
runMissingList(cmd.Context())
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
missingFixCmd = &cobra.Command{
|
||||||
|
Use: "fix <missing path|id> <target path|id>",
|
||||||
|
Short: "Remap a missing file onto an existing file",
|
||||||
|
Long: "Remap a file marked as missing onto an existing (non-missing) file, the same way\n" +
|
||||||
|
"the scanner reconciles moved or renamed files. Each argument may be a media file ID,\n" +
|
||||||
|
"a library-relative path, or a libraryID:path pair.",
|
||||||
|
Args: cobra.ExactArgs(2),
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
runMissingFix(cmd.Context(), args[0], args[1])
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
type displayMissingFile struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
LibraryID int `json:"libraryId"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Album string `json:"album"`
|
||||||
|
Artist string `json:"artist"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func runMissingList(ctx context.Context) {
|
||||||
|
if missingListFormat != "csv" && missingListFormat != "json" {
|
||||||
|
log.Fatal("Invalid output format. Must be one of csv, json", "format", missingListFormat)
|
||||||
|
}
|
||||||
|
|
||||||
|
ds, ctx := getAdminContext(ctx)
|
||||||
|
mfs, err := ds.MediaFile().GetCursor(ctx, model.QueryOptions{
|
||||||
|
Filters: squirrel.Eq{"missing": true},
|
||||||
|
Sort: "path",
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
err = writeMissingList(os.Stdout, missingListFormat, mfs)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(ctx, "Failed to retrieve missing files", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeMissingList streams the cursor so a library with many missing files doesn't get loaded into memory
|
||||||
|
func writeMissingList(w io.Writer, format string, mfs model.MediaFileCursor) error {
|
||||||
|
if format == "json" {
|
||||||
|
bw := bufio.NewWriter(w)
|
||||||
|
_, _ = io.WriteString(bw, "[")
|
||||||
|
sep := ""
|
||||||
|
for mf, err := range mfs {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
j, err := json.Marshal(displayMissingFile{ID: mf.ID, LibraryID: mf.LibraryID, Title: mf.Title, Album: mf.Album, Artist: mf.Artist, Path: mf.Path})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, _ = fmt.Fprintf(bw, "%s%s", sep, j)
|
||||||
|
sep = ","
|
||||||
|
}
|
||||||
|
_, _ = io.WriteString(bw, "]\n")
|
||||||
|
return bw.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
cw := csv.NewWriter(w)
|
||||||
|
_ = cw.Write([]string{"id", "library id", "title", "album", "artist", "path"})
|
||||||
|
for mf, err := range mfs {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_ = cw.Write([]string{mf.ID, strconv.Itoa(mf.LibraryID), mf.Title, mf.Album, mf.Artist, mf.Path})
|
||||||
|
}
|
||||||
|
cw.Flush()
|
||||||
|
return cw.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
func runMissingFix(ctx context.Context, missingRef, targetRef string) {
|
||||||
|
ds, ctx := getAdminContext(ctx)
|
||||||
|
|
||||||
|
missing := resolveMediaFile(ctx, ds, missingRef)
|
||||||
|
target := resolveMediaFile(ctx, ds, targetRef)
|
||||||
|
|
||||||
|
if err := core.NewMaintenance(ds).RemapMissingFile(ctx, missing.ID, target.ID); err != nil {
|
||||||
|
log.Fatal(ctx, "Failed to remap missing file", "missing", missing.Path, "target", target.Path, err)
|
||||||
|
}
|
||||||
|
fmt.Printf("Remapped %q onto %q\n", missing.Path, target.Path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveMediaFile looks up a media file by ID first, then by path (optionally libraryID:path).
|
||||||
|
func resolveMediaFile(ctx context.Context, ds model.DataStore, ref string) *model.MediaFile {
|
||||||
|
mf, err := ds.MediaFile().Get(ctx, ref)
|
||||||
|
if err == nil {
|
||||||
|
return mf
|
||||||
|
}
|
||||||
|
if !errors.Is(err, model.ErrNotFound) {
|
||||||
|
log.Fatal(ctx, "Error looking up media file", "ref", ref, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
mfs, err := ds.MediaFile().FindByPaths(ctx, []string{ref})
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(ctx, "Error looking up media file by path", "ref", ref, err)
|
||||||
|
}
|
||||||
|
if len(mfs) == 0 {
|
||||||
|
log.Fatal(ctx, "No media file found", "ref", ref)
|
||||||
|
}
|
||||||
|
mfs = preferQualified(ref, mfs)
|
||||||
|
if len(mfs) > 1 {
|
||||||
|
log.Fatal(ctx, "Path matches multiple files; disambiguate with an ID or libraryID:path", "ref", ref, "matches", len(mfs))
|
||||||
|
}
|
||||||
|
return &mfs[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
// preferQualified resolves the ambiguity FindByPaths creates by searching a "libraryID:path"
|
||||||
|
// reference both ways: an explicit library wins over a file literally named like one.
|
||||||
|
func preferQualified(ref string, mfs model.MediaFiles) model.MediaFiles {
|
||||||
|
id, path, ok := strings.Cut(ref, ":")
|
||||||
|
if !ok {
|
||||||
|
return mfs
|
||||||
|
}
|
||||||
|
libraryID, err := strconv.Atoi(id)
|
||||||
|
if err != nil {
|
||||||
|
return mfs
|
||||||
|
}
|
||||||
|
qualified := slice.Filter(mfs, func(mf model.MediaFile) bool {
|
||||||
|
return mf.LibraryID == libraryID && strings.EqualFold(mf.Path, path)
|
||||||
|
})
|
||||||
|
if len(qualified) == 0 {
|
||||||
|
return mfs
|
||||||
|
}
|
||||||
|
return qualified
|
||||||
|
}
|
||||||
81
cmd/missing_test.go
Normal file
81
cmd/missing_test.go
Normal file
|
|
@ -0,0 +1,81 @@
|
||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/model"
|
||||||
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
. "github.com/onsi/gomega"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ = Describe("writeMissingList", func() {
|
||||||
|
cursor := func(err error, mfs ...model.MediaFile) model.MediaFileCursor {
|
||||||
|
return func(yield func(model.MediaFile, error) bool) {
|
||||||
|
for _, mf := range mfs {
|
||||||
|
if !yield(mf, nil) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
yield(model.MediaFile{}, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
song := model.MediaFile{ID: "1", LibraryID: 1, Path: "Bach: Goldberg/01.mp3", Title: "Aria", Album: "Goldberg", Artist: "Bach"}
|
||||||
|
|
||||||
|
It("writes csv with a header, quoting as needed", func() {
|
||||||
|
var out strings.Builder
|
||||||
|
Expect(writeMissingList(&out, "csv", cursor(nil, song))).To(Succeed())
|
||||||
|
Expect(out.String()).To(Equal("id,library id,title,album,artist,path\n1,1,Aria,Goldberg,Bach,Bach: Goldberg/01.mp3\n"))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("writes a json array", func() {
|
||||||
|
var out strings.Builder
|
||||||
|
Expect(writeMissingList(&out, "json", cursor(nil, song, song))).To(Succeed())
|
||||||
|
Expect(out.String()).To(MatchJSON(`[
|
||||||
|
{"id":"1","libraryId":1,"path":"Bach: Goldberg/01.mp3","title":"Aria","album":"Goldberg","artist":"Bach"},
|
||||||
|
{"id":"1","libraryId":1,"path":"Bach: Goldberg/01.mp3","title":"Aria","album":"Goldberg","artist":"Bach"}
|
||||||
|
]`))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("writes an empty json array when nothing is missing", func() {
|
||||||
|
var out strings.Builder
|
||||||
|
Expect(writeMissingList(&out, "json", cursor(nil))).To(Succeed())
|
||||||
|
Expect(out.String()).To(MatchJSON(`[]`))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("returns the cursor's error", func() {
|
||||||
|
var out strings.Builder
|
||||||
|
Expect(writeMissingList(&out, "csv", cursor(errors.New("boom"), song))).To(MatchError("boom"))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
var _ = Describe("preferQualified", func() {
|
||||||
|
target := model.MediaFile{ID: "want", LibraryID: 1, Path: "foo.mp3"}
|
||||||
|
decoy := model.MediaFile{ID: "decoy", LibraryID: 1, Path: "1:foo.mp3"}
|
||||||
|
|
||||||
|
It("picks the library-qualified match over a literal path that looks like one", func() {
|
||||||
|
Expect(preferQualified("1:foo.mp3", model.MediaFiles{target, decoy})).To(Equal(model.MediaFiles{target}))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("picks the named library when the same path exists in two", func() {
|
||||||
|
other := model.MediaFile{ID: "other", LibraryID: 2, Path: "foo.mp3"}
|
||||||
|
Expect(preferQualified("1:foo.mp3", model.MediaFiles{target, other})).To(Equal(model.MediaFiles{target}))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("leaves an unqualified reference ambiguous", func() {
|
||||||
|
both := model.MediaFiles{target, {ID: "other", LibraryID: 2, Path: "foo.mp3"}}
|
||||||
|
Expect(preferQualified("foo.mp3", both)).To(Equal(both))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("leaves it alone when the prefix is not a library id", func() {
|
||||||
|
both := model.MediaFiles{decoy, {ID: "other", LibraryID: 2, Path: "1:foo.mp3"}}
|
||||||
|
Expect(preferQualified("x:foo.mp3", both)).To(Equal(both))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("leaves it alone when no candidate matches the qualified form", func() {
|
||||||
|
both := model.MediaFiles{decoy, {ID: "other", LibraryID: 2, Path: "1:foo.mp3"}}
|
||||||
|
Expect(preferQualified("9:nope.mp3", both)).To(Equal(both))
|
||||||
|
})
|
||||||
|
})
|
||||||
15
cmd/pls.go
15
cmd/pls.go
|
|
@ -109,7 +109,7 @@ func fetchPlaylists(ctx context.Context, ds model.DataStore, sort string) model.
|
||||||
}
|
}
|
||||||
options.Filters = squirrel.Eq{"owner_id": user.ID}
|
options.Filters = squirrel.Eq{"owner_id": user.ID}
|
||||||
}
|
}
|
||||||
pls, err := ds.Playlist(ctx).GetAll(options)
|
pls, err := ds.Playlist().GetAll(ctx, options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(ctx, "Failed to retrieve playlists", err)
|
log.Fatal(ctx, "Failed to retrieve playlists", err)
|
||||||
}
|
}
|
||||||
|
|
@ -117,17 +117,17 @@ func fetchPlaylists(ctx context.Context, ds model.DataStore, sort string) model.
|
||||||
}
|
}
|
||||||
|
|
||||||
func findPlaylist(ctx context.Context, ds model.DataStore, nameOrID string) *model.Playlist {
|
func findPlaylist(ctx context.Context, ds model.DataStore, nameOrID string) *model.Playlist {
|
||||||
playlist, err := ds.Playlist(ctx).GetWithTracks(nameOrID, true, false)
|
playlist, err := ds.Playlist().GetWithTracks(ctx, nameOrID, true, false)
|
||||||
if err != nil && !errors.Is(err, model.ErrNotFound) {
|
if err != nil && !errors.Is(err, model.ErrNotFound) {
|
||||||
log.Fatal("Error retrieving playlist", "name", nameOrID, err)
|
log.Fatal("Error retrieving playlist", "name", nameOrID, err)
|
||||||
}
|
}
|
||||||
if errors.Is(err, model.ErrNotFound) {
|
if errors.Is(err, model.ErrNotFound) {
|
||||||
playlists, err := ds.Playlist(ctx).GetAll(model.QueryOptions{Filters: squirrel.Eq{"playlist.name": nameOrID}})
|
playlists, err := ds.Playlist().GetAll(ctx, model.QueryOptions{Filters: squirrel.Eq{"playlist.name": nameOrID}})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("Error retrieving playlist", "name", nameOrID, err)
|
log.Fatal("Error retrieving playlist", "name", nameOrID, err)
|
||||||
}
|
}
|
||||||
if len(playlists) > 0 {
|
if len(playlists) > 0 {
|
||||||
playlist, err = ds.Playlist(ctx).GetWithTracks(playlists[0].ID, true, false)
|
playlist, err = ds.Playlist().GetWithTracks(ctx, playlists[0].ID, true, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("Error retrieving playlist", "name", nameOrID, err)
|
log.Fatal("Error retrieving playlist", "name", nameOrID, err)
|
||||||
}
|
}
|
||||||
|
|
@ -194,7 +194,7 @@ func runExport(ctx context.Context) {
|
||||||
|
|
||||||
exported := 0
|
exported := 0
|
||||||
for _, pls := range allPls {
|
for _, pls := range allPls {
|
||||||
plsWithTracks, err := ds.Playlist(ctx).GetWithTracks(pls.ID, true, false)
|
plsWithTracks, err := ds.Playlist().GetWithTracks(ctx, pls.ID, true, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Error loading playlist tracks", "playlist", pls.Name, err)
|
log.Error("Error loading playlist tracks", "playlist", pls.Name, err)
|
||||||
continue
|
continue
|
||||||
|
|
@ -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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/csv"
|
"encoding/csv"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
|
|
@ -243,7 +244,7 @@ func runPluginInfo(ctx context.Context, arg string) {
|
||||||
}
|
}
|
||||||
requirePluginsEnabled(ctx)
|
requirePluginsEnabled(ctx)
|
||||||
ds, ctx := getAdminContext(ctx)
|
ds, ctx := getAdminContext(ctx)
|
||||||
p, err := ds.Plugin(ctx).Get(arg)
|
p, err := ds.Plugin().Get(ctx, arg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(ctx, "Plugin not found", "id", arg, err)
|
log.Fatal(ctx, "Plugin not found", "id", arg, err)
|
||||||
}
|
}
|
||||||
|
|
@ -264,7 +265,7 @@ func runPluginValidate(ctx context.Context, arg string) {
|
||||||
}
|
}
|
||||||
requirePluginsEnabled(ctx)
|
requirePluginsEnabled(ctx)
|
||||||
ds, ctx := getAdminContext(ctx)
|
ds, ctx := getAdminContext(ctx)
|
||||||
p, err := ds.Plugin(ctx).Get(arg)
|
p, err := ds.Plugin().Get(ctx, arg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(ctx, "Plugin not found", "id", arg, err)
|
log.Fatal(ctx, "Plugin not found", "id", arg, err)
|
||||||
}
|
}
|
||||||
|
|
@ -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()
|
||||||
|
|
@ -329,7 +330,7 @@ func formatPluginList(list model.Plugins, format string) (string, error) {
|
||||||
func runPluginList(ctx context.Context) {
|
func runPluginList(ctx context.Context) {
|
||||||
requirePluginsEnabled(ctx)
|
requirePluginsEnabled(ctx)
|
||||||
ds, ctx := getAdminContext(ctx)
|
ds, ctx := getAdminContext(ctx)
|
||||||
list, err := ds.Plugin(ctx).GetAll()
|
list, err := ds.Plugin().GetAll(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(ctx, "Failed to list plugins", err)
|
log.Fatal(ctx, "Failed to list plugins", err)
|
||||||
}
|
}
|
||||||
|
|
@ -343,7 +344,7 @@ func runPluginList(ctx context.Context) {
|
||||||
// requirePluginsEnabled gates DB/manager-backed commands; off-disk .ndp
|
// requirePluginsEnabled gates DB/manager-backed commands; off-disk .ndp
|
||||||
// inspection deliberately skips this so it works without a configured server.
|
// inspection deliberately skips this so it works without a configured server.
|
||||||
func requirePluginsEnabled(ctx context.Context) {
|
func requirePluginsEnabled(ctx context.Context) {
|
||||||
if !conf.Server.Plugins.Enabled {
|
if !conf.Server().Plugins.Enabled {
|
||||||
log.Fatal(ctx, "Plugin system is disabled (set Plugins.Enabled to use this command)")
|
log.Fatal(ctx, "Plugin system is disabled (set Plugins.Enabled to use this command)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -372,7 +373,7 @@ var pluginEditCmd = &cobra.Command{
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
requirePluginsEnabled(cmd.Context())
|
requirePluginsEnabled(cmd.Context())
|
||||||
ds, ctx := getAdminContext(cmd.Context())
|
ds, ctx := getAdminContext(cmd.Context())
|
||||||
cur, err := ds.Plugin(ctx).Get(args[0])
|
cur, err := ds.Plugin().Get(ctx, args[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(ctx, "Plugin not found", "id", args[0], err)
|
log.Fatal(ctx, "Plugin not found", "id", args[0], err)
|
||||||
}
|
}
|
||||||
|
|
@ -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{
|
||||||
|
|
|
||||||
|
|
@ -65,16 +65,21 @@ var _ = Describe("formatPluginList", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
var _ = Describe("enable/disable plugin", func() {
|
var _ = Describe("enable/disable plugin", func() {
|
||||||
|
var ctx context.Context
|
||||||
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
|
})
|
||||||
|
|
||||||
It("calls EnablePlugin on the manager", func() {
|
It("calls EnablePlugin on the manager", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
err := enablePlugin(context.Background(), mgr, "alpha")
|
err := enablePlugin(ctx, mgr, "alpha")
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(mgr.EnablePluginCalls).To(Equal([]string{"alpha"}))
|
Expect(mgr.EnablePluginCalls).To(Equal([]string{"alpha"}))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("calls DisablePlugin on the manager", func() {
|
It("calls DisablePlugin on the manager", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
err := disablePlugin(context.Background(), mgr, "beta")
|
err := disablePlugin(ctx, mgr, "beta")
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(mgr.DisablePluginCalls).To(Equal([]string{"beta"}))
|
Expect(mgr.DisablePluginCalls).To(Equal([]string{"beta"}))
|
||||||
})
|
})
|
||||||
|
|
@ -82,14 +87,16 @@ var _ = Describe("enable/disable plugin", func() {
|
||||||
|
|
||||||
var _ = Describe("applyPluginEdit", func() {
|
var _ = Describe("applyPluginEdit", func() {
|
||||||
var cur *model.Plugin
|
var cur *model.Plugin
|
||||||
|
var ctx context.Context
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
cur = &model.Plugin{ID: "alpha", Users: `["bob"]`, Libraries: `[1,2]`, AllowWriteAccess: true}
|
cur = &model.Plugin{ID: "alpha", Users: `["bob"]`, Libraries: `[1,2]`, AllowWriteAccess: true}
|
||||||
})
|
})
|
||||||
|
|
||||||
It("validates then updates config when config is provided", func() {
|
It("validates then updates config when config is provided", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
cfg := `{"key":"val"}`
|
cfg := `{"key":"val"}`
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{config: &cfg})
|
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{config: &cfg})
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(mgr.ValidatePluginConfigCalls).To(HaveLen(1))
|
Expect(mgr.ValidatePluginConfigCalls).To(HaveLen(1))
|
||||||
Expect(mgr.ValidatePluginConfigCalls[0].ConfigJSON).To(Equal(cfg))
|
Expect(mgr.ValidatePluginConfigCalls[0].ConfigJSON).To(Equal(cfg))
|
||||||
|
|
@ -100,7 +107,7 @@ var _ = Describe("applyPluginEdit", func() {
|
||||||
It("updates users with allUsers flag", func() {
|
It("updates users with allUsers flag", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
all := true
|
all := true
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur,
|
err := applyPluginEdit(ctx, mgr, cur,
|
||||||
pluginEditOptions{allUsers: &all})
|
pluginEditOptions{allUsers: &all})
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(mgr.UpdatePluginUsersCalls).To(HaveLen(1))
|
Expect(mgr.UpdatePluginUsersCalls).To(HaveLen(1))
|
||||||
|
|
@ -111,7 +118,7 @@ var _ = Describe("applyPluginEdit", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
all := true
|
all := true
|
||||||
wr := true
|
wr := true
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur,
|
err := applyPluginEdit(ctx, mgr, cur,
|
||||||
pluginEditOptions{allLibraries: &all, writeAccess: &wr})
|
pluginEditOptions{allLibraries: &all, writeAccess: &wr})
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(mgr.UpdatePluginLibrariesCalls).To(HaveLen(1))
|
Expect(mgr.UpdatePluginLibrariesCalls).To(HaveLen(1))
|
||||||
|
|
@ -122,7 +129,7 @@ var _ = Describe("applyPluginEdit", func() {
|
||||||
It("preserves existing fields when only the write-access flag changes", func() {
|
It("preserves existing fields when only the write-access flag changes", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
no := false
|
no := false
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{writeAccess: &no})
|
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{writeAccess: &no})
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(mgr.UpdatePluginLibrariesCalls).To(HaveLen(1))
|
Expect(mgr.UpdatePluginLibrariesCalls).To(HaveLen(1))
|
||||||
Expect(mgr.UpdatePluginLibrariesCalls[0].LibrariesJSON).To(Equal(`[1,2]`)) // not wiped
|
Expect(mgr.UpdatePluginLibrariesCalls[0].LibrariesJSON).To(Equal(`[1,2]`)) // not wiped
|
||||||
|
|
@ -132,7 +139,7 @@ var _ = Describe("applyPluginEdit", func() {
|
||||||
It("preserves existing users when only the all-users flag changes", func() {
|
It("preserves existing users when only the all-users flag changes", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
all := true
|
all := true
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{allUsers: &all})
|
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{allUsers: &all})
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["bob"]`)) // not wiped
|
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["bob"]`)) // not wiped
|
||||||
})
|
})
|
||||||
|
|
@ -140,7 +147,7 @@ var _ = Describe("applyPluginEdit", func() {
|
||||||
It("parses a comma-separated users value into a JSON array", func() {
|
It("parses a comma-separated users value into a JSON array", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
users := "alice, bob"
|
users := "alice, bob"
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{users: &users})
|
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{users: &users})
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["alice","bob"]`))
|
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["alice","bob"]`))
|
||||||
})
|
})
|
||||||
|
|
@ -148,7 +155,7 @@ var _ = Describe("applyPluginEdit", func() {
|
||||||
It("passes a JSON-array users value through unchanged", func() {
|
It("passes a JSON-array users value through unchanged", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
users := `["alice","bob"]`
|
users := `["alice","bob"]`
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{users: &users})
|
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{users: &users})
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["alice","bob"]`))
|
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["alice","bob"]`))
|
||||||
})
|
})
|
||||||
|
|
@ -156,7 +163,7 @@ var _ = Describe("applyPluginEdit", func() {
|
||||||
It("rejects a malformed JSON-array users value", func() {
|
It("rejects a malformed JSON-array users value", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
users := `["alice"`
|
users := `["alice"`
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{users: &users})
|
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{users: &users})
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
Expect(mgr.UpdatePluginUsersCalls).To(BeEmpty())
|
Expect(mgr.UpdatePluginUsersCalls).To(BeEmpty())
|
||||||
})
|
})
|
||||||
|
|
@ -164,7 +171,7 @@ var _ = Describe("applyPluginEdit", func() {
|
||||||
It("parses a comma-separated libraries value into a JSON array of ints", func() {
|
It("parses a comma-separated libraries value into a JSON array of ints", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
libs := "1, 2"
|
libs := "1, 2"
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{libraries: &libs})
|
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{libraries: &libs})
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(mgr.UpdatePluginLibrariesCalls[0].LibrariesJSON).To(Equal(`[1,2]`))
|
Expect(mgr.UpdatePluginLibrariesCalls[0].LibrariesJSON).To(Equal(`[1,2]`))
|
||||||
})
|
})
|
||||||
|
|
@ -172,7 +179,7 @@ var _ = Describe("applyPluginEdit", func() {
|
||||||
It("rejects a non-integer library ID", func() {
|
It("rejects a non-integer library ID", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
libs := "1,abc"
|
libs := "1,abc"
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{libraries: &libs})
|
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{libraries: &libs})
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
Expect(mgr.UpdatePluginLibrariesCalls).To(BeEmpty())
|
Expect(mgr.UpdatePluginLibrariesCalls).To(BeEmpty())
|
||||||
})
|
})
|
||||||
|
|
@ -181,7 +188,7 @@ var _ = Describe("applyPluginEdit", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
cur.AllUsers = true
|
cur.AllUsers = true
|
||||||
users := "alice"
|
users := "alice"
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{users: &users})
|
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{users: &users})
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["alice"]`))
|
Expect(mgr.UpdatePluginUsersCalls[0].UsersJSON).To(Equal(`["alice"]`))
|
||||||
Expect(mgr.UpdatePluginUsersCalls[0].AllUsers).To(BeFalse())
|
Expect(mgr.UpdatePluginUsersCalls[0].AllUsers).To(BeFalse())
|
||||||
|
|
@ -191,7 +198,7 @@ var _ = Describe("applyPluginEdit", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
cur.AllLibraries = true
|
cur.AllLibraries = true
|
||||||
libs := "1"
|
libs := "1"
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{libraries: &libs})
|
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{libraries: &libs})
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(mgr.UpdatePluginLibrariesCalls[0].LibrariesJSON).To(Equal(`[1]`))
|
Expect(mgr.UpdatePluginLibrariesCalls[0].LibrariesJSON).To(Equal(`[1]`))
|
||||||
Expect(mgr.UpdatePluginLibrariesCalls[0].AllLibraries).To(BeFalse())
|
Expect(mgr.UpdatePluginLibrariesCalls[0].AllLibraries).To(BeFalse())
|
||||||
|
|
@ -199,14 +206,14 @@ var _ = Describe("applyPluginEdit", func() {
|
||||||
|
|
||||||
It("does nothing and errors when no fields are set", func() {
|
It("does nothing and errors when no fields are set", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{})
|
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{})
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("aborts the config update when validation fails", func() {
|
It("aborts the config update when validation fails", func() {
|
||||||
mgr := &tests.MockPluginManager{ValidateError: errors.New("bad config")}
|
mgr := &tests.MockPluginManager{ValidateError: errors.New("bad config")}
|
||||||
cfg := `{"key":"val"}`
|
cfg := `{"key":"val"}`
|
||||||
err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{config: &cfg})
|
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{config: &cfg})
|
||||||
Expect(err).To(HaveOccurred())
|
Expect(err).To(HaveOccurred())
|
||||||
Expect(mgr.ValidatePluginConfigCalls).To(HaveLen(1))
|
Expect(mgr.ValidatePluginConfigCalls).To(HaveLen(1))
|
||||||
Expect(mgr.UpdatePluginConfigCalls).To(BeEmpty())
|
Expect(mgr.UpdatePluginConfigCalls).To(BeEmpty())
|
||||||
|
|
@ -353,7 +360,7 @@ var _ = Describe("formatManifestInfo enriched text", func() {
|
||||||
var _ = Describe("rescanPlugins", func() {
|
var _ = Describe("rescanPlugins", func() {
|
||||||
It("calls RescanPlugins on the manager", func() {
|
It("calls RescanPlugins on the manager", func() {
|
||||||
mgr := &tests.MockPluginManager{}
|
mgr := &tests.MockPluginManager{}
|
||||||
err := rescanPlugins(context.Background(), mgr)
|
err := rescanPlugins(GinkgoT().Context(), mgr)
|
||||||
Expect(err).ToNot(HaveOccurred())
|
Expect(err).ToNot(HaveOccurred())
|
||||||
Expect(mgr.RescanPluginsCalls).To(Equal(1))
|
Expect(mgr.RescanPluginsCalls).To(Equal(1))
|
||||||
})
|
})
|
||||||
|
|
|
||||||
139
cmd/root.go
139
cmd/root.go
|
|
@ -44,7 +44,9 @@ Complete documentation is available at https://www.navidrome.org/docs`,
|
||||||
preRun()
|
preRun()
|
||||||
},
|
},
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
runNavidrome(cmd.Context())
|
if err := runNavidrome(cmd.Context()); err != nil {
|
||||||
|
log.Fatal("Fatal error in Navidrome. Aborting", err)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
PostRun: func(cmd *cobra.Command, args []string) {
|
PostRun: func(cmd *cobra.Command, args []string) {
|
||||||
postRun()
|
postRun()
|
||||||
|
|
@ -76,16 +78,17 @@ func postRun() {
|
||||||
}
|
}
|
||||||
|
|
||||||
// runNavidrome is the main entry point for the Navidrome server. It starts all the services and blocks.
|
// runNavidrome is the main entry point for the Navidrome server. It starts all the services and blocks.
|
||||||
// If any of the services returns an error, it will log it and exit. If the process receives a signal to exit,
|
// If any of the services returns an error, it stops the others and returns that error, so the caller can
|
||||||
// it will cancel the context and exit gracefully.
|
// exit with a non-zero code. If the context is cancelled (a signal or a service stop), it returns nil.
|
||||||
func runNavidrome(ctx context.Context) {
|
func runNavidrome(parentCtx context.Context) error {
|
||||||
defer db.Init(ctx)()
|
defer db.Init(parentCtx)()
|
||||||
|
|
||||||
g, ctx := errgroup.WithContext(ctx)
|
g, ctx := errgroup.WithContext(parentCtx)
|
||||||
g.Go(startServer(ctx))
|
g.Go(startServer(ctx))
|
||||||
g.Go(startSignaller(ctx))
|
g.Go(startSignaller(ctx))
|
||||||
g.Go(startScheduler(ctx))
|
g.Go(startScheduler(ctx))
|
||||||
g.Go(startPlaybackServer(ctx))
|
g.Go(startPlaybackServer(ctx))
|
||||||
|
g.Go(startJellyfinDiscovery(ctx))
|
||||||
g.Go(schedulePeriodicBackup(ctx))
|
g.Go(schedulePeriodicBackup(ctx))
|
||||||
g.Go(startInsightsCollector(ctx))
|
g.Go(startInsightsCollector(ctx))
|
||||||
g.Go(scheduleDBAnalyzer(ctx))
|
g.Go(scheduleDBAnalyzer(ctx))
|
||||||
|
|
@ -94,16 +97,18 @@ func runNavidrome(ctx context.Context) {
|
||||||
g.Go(startArtworkWorker(ctx, artworkWorker))
|
g.Go(startArtworkWorker(ctx, artworkWorker))
|
||||||
g.Go(scheduleArtworkHousekeeping(ctx, artworkWorker))
|
g.Go(scheduleArtworkHousekeeping(ctx, artworkWorker))
|
||||||
g.Go(runInitialScan(ctx))
|
g.Go(runInitialScan(ctx))
|
||||||
if conf.Server.Scanner.Enabled {
|
if conf.Server().Scanner.Enabled {
|
||||||
g.Go(startScanWatcher(ctx))
|
g.Go(startScanWatcher(ctx))
|
||||||
g.Go(schedulePeriodicScan(ctx))
|
g.Go(schedulePeriodicScan(ctx))
|
||||||
} else {
|
} else {
|
||||||
log.Warn(ctx, "Automatic Scanning is DISABLED")
|
log.Warn(ctx, "Automatic Scanning is DISABLED")
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := g.Wait(); err != nil {
|
// Errors caused by a normal shutdown are not failures
|
||||||
log.Error("Fatal error in Navidrome. Aborting", err)
|
if err := g.Wait(); err != nil && parentCtx.Err() == nil {
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// mainContext returns a context that is cancelled when the process receives a signal to exit.
|
// mainContext returns a context that is cancelled when the process receives a signal to exit.
|
||||||
|
|
@ -123,28 +128,31 @@ func startServer(ctx context.Context) func() error {
|
||||||
a.MountRouter("Native API", consts.URLPathNativeAPI, CreateNativeAPIRouter(ctx))
|
a.MountRouter("Native API", consts.URLPathNativeAPI, CreateNativeAPIRouter(ctx))
|
||||||
a.MountRouter("Subsonic API", consts.URLPathSubsonicAPI, CreateSubsonicAPIRouter(ctx))
|
a.MountRouter("Subsonic API", consts.URLPathSubsonicAPI, CreateSubsonicAPIRouter(ctx))
|
||||||
a.MountRouter("Public Endpoints", consts.URLPathPublic, CreatePublicRouter())
|
a.MountRouter("Public Endpoints", consts.URLPathPublic, CreatePublicRouter())
|
||||||
if conf.Server.LastFM.Enabled {
|
if conf.Server().LastFM.Enabled {
|
||||||
a.MountRouter("LastFM Auth", consts.URLPathNativeAPI+"/lastfm", CreateLastFMRouter())
|
a.MountRouter("LastFM Auth", consts.URLPathNativeAPI+"/lastfm", CreateLastFMRouter())
|
||||||
}
|
}
|
||||||
if conf.Server.ListenBrainz.Enabled {
|
if conf.Server().ListenBrainz.Enabled {
|
||||||
a.MountRouter("ListenBrainz Auth", consts.URLPathNativeAPI+"/listenbrainz", CreateListenBrainzRouter())
|
a.MountRouter("ListenBrainz Auth", consts.URLPathNativeAPI+"/listenbrainz", CreateListenBrainzRouter())
|
||||||
}
|
}
|
||||||
if conf.Server.Jellyfin.Enabled {
|
if conf.Server().Jellyfin.Enabled {
|
||||||
a.MountRouter("Jellyfin API", consts.URLPathJellyfinAPI, CreateJellyfinAPIRouter(ctx))
|
a.MountRouter("Jellyfin API", consts.URLPathJellyfinAPI, CreateJellyfinAPIRouter(ctx))
|
||||||
}
|
}
|
||||||
if conf.Server.Prometheus.Enabled {
|
if conf.Server().DevAPIv1 {
|
||||||
|
a.MountRouter("API v1", consts.URLPathAPIv1, CreateAPIv1Router(ctx))
|
||||||
|
}
|
||||||
|
if conf.Server().Prometheus.Enabled {
|
||||||
p := CreatePrometheus()
|
p := CreatePrometheus()
|
||||||
// blocking call because takes <100ms but useful if fails
|
// blocking call because takes <100ms but useful if fails
|
||||||
p.WriteInitialMetrics(ctx)
|
p.WriteInitialMetrics(ctx)
|
||||||
a.MountRouter("Prometheus metrics", conf.Server.Prometheus.MetricsPath, p.GetHandler())
|
a.MountRouter("Prometheus metrics", conf.Server().Prometheus.MetricsPath, p.GetHandler())
|
||||||
}
|
}
|
||||||
if conf.Server.DevEnableProfiler {
|
if conf.Server().DevEnableProfiler {
|
||||||
a.MountRouter("Profiling", "/debug", profilerHandler())
|
a.MountRouter("Profiling", "/debug", profilerHandler())
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(conf.Server.UILoginBackgroundURL, "/") {
|
if strings.HasPrefix(conf.Server().UILoginBackgroundURL, "/") {
|
||||||
a.MountRouter("Background images", conf.Server.UILoginBackgroundURL, backgrounds.NewHandler())
|
a.MountRouter("Background images", conf.Server().UILoginBackgroundURL, backgrounds.NewHandler())
|
||||||
}
|
}
|
||||||
return a.Run(ctx, conf.Server.Address, conf.Server.Port, conf.Server.TLSCert, conf.Server.TLSKey)
|
return a.Run(ctx, conf.Server().Address, conf.Server().Port, conf.Server().TLSCert, conf.Server().TLSKey)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -152,14 +160,14 @@ func startServer(ctx context.Context) func() error {
|
||||||
// name from the raw request path, so the BasePath has to come off first.
|
// name from the raw request path, so the BasePath has to come off first.
|
||||||
func profilerHandler() http.Handler {
|
func profilerHandler() http.Handler {
|
||||||
// A trailing or root slash would make StripPrefix drop the leading slash chi needs.
|
// A trailing or root slash would make StripPrefix drop the leading slash chi needs.
|
||||||
basePath := strings.TrimRight(conf.Server.BasePath, "/")
|
basePath := strings.TrimRight(conf.Server().BasePath, "/")
|
||||||
return http.StripPrefix(basePath, middleware.Profiler())
|
return http.StripPrefix(basePath, middleware.Profiler())
|
||||||
}
|
}
|
||||||
|
|
||||||
// schedulePeriodicScan schedules a periodic scan of the music library, if configured.
|
// schedulePeriodicScan schedules a periodic scan of the music library, if configured.
|
||||||
func schedulePeriodicScan(ctx context.Context) func() error {
|
func schedulePeriodicScan(ctx context.Context) func() error {
|
||||||
return func() error {
|
return func() error {
|
||||||
schedule := conf.Server.Scanner.Schedule
|
schedule := conf.Server().Scanner.Schedule
|
||||||
if schedule == "" {
|
if schedule == "" {
|
||||||
log.Info(ctx, "Periodic scan is DISABLED")
|
log.Info(ctx, "Periodic scan is DISABLED")
|
||||||
return nil
|
return nil
|
||||||
|
|
@ -182,46 +190,50 @@ func schedulePeriodicScan(ctx context.Context) func() error {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func pidHashChanged(ds model.DataStore) (bool, error) {
|
// librariesWithChangedPID returns the names of the libraries whose effective PID config differs from
|
||||||
pidAlbum, err := ds.Property(context.Background()).DefaultGet(consts.PIDAlbumKey, "")
|
// the one used by their last finished scan
|
||||||
|
func librariesWithChangedPID(ctx context.Context, ds model.DataStore) ([]string, error) {
|
||||||
|
libs, err := ds.Library().GetAll(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return nil, err
|
||||||
}
|
}
|
||||||
pidTrack, err := ds.Property(context.Background()).DefaultGet(consts.PIDTrackKey, "")
|
var names []string
|
||||||
if err != nil {
|
for _, lib := range libs {
|
||||||
return false, err
|
if lib.PIDChanged() {
|
||||||
|
names = append(names, lib.Name)
|
||||||
}
|
}
|
||||||
return !strings.EqualFold(pidAlbum, conf.Server.PID.Album) || !strings.EqualFold(pidTrack, conf.Server.PID.Track), nil
|
}
|
||||||
|
return names, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// runInitialScan runs an initial scan of the music library if needed.
|
// runInitialScan runs an initial scan of the music library if needed.
|
||||||
func runInitialScan(ctx context.Context) func() error {
|
func runInitialScan(ctx context.Context) func() error {
|
||||||
return func() error {
|
return func() error {
|
||||||
ds := CreateDataStore()
|
ds := CreateDataStore()
|
||||||
fullScanRequired, err := ds.Property(ctx).DefaultGet(consts.FullScanAfterMigrationFlagKey, "0")
|
fullScanRequired, err := ds.Property().DefaultGet(ctx, consts.FullScanAfterMigrationFlagKey, "0")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
inProgress, err := ds.Library(ctx).ScanInProgress()
|
inProgress, err := ds.Library().ScanInProgress(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
pidHasChanged, err := pidHashChanged(ds)
|
pidChangedLibs, err := librariesWithChangedPID(ctx, ds)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
scanOnStartup := conf.Server.Scanner.Enabled && conf.Server.Scanner.ScanOnStartup
|
scanOnStartup := conf.Server().Scanner.Enabled && conf.Server().Scanner.ScanOnStartup
|
||||||
scanNeeded := scanOnStartup || inProgress || fullScanRequired == "1" || pidHasChanged
|
scanNeeded := scanOnStartup || inProgress || fullScanRequired == "1" || len(pidChangedLibs) > 0
|
||||||
time.Sleep(2 * time.Second) // Wait 2 seconds before the initial scan
|
time.Sleep(2 * time.Second) // Wait 2 seconds before the initial scan
|
||||||
if scanNeeded {
|
if scanNeeded {
|
||||||
s := CreateScanner(ctx)
|
s := CreateScanner(ctx)
|
||||||
switch {
|
switch {
|
||||||
case fullScanRequired == "1":
|
case fullScanRequired == "1":
|
||||||
log.Warn(ctx, "Full scan required after migration")
|
log.Warn(ctx, "Full scan required after migration")
|
||||||
_ = ds.Property(ctx).Delete(consts.FullScanAfterMigrationFlagKey)
|
_ = ds.Property().Delete(ctx, consts.FullScanAfterMigrationFlagKey)
|
||||||
case pidHasChanged:
|
case len(pidChangedLibs) > 0:
|
||||||
log.Warn(ctx, "PID config changed, performing full scan")
|
// Includes never-scanned libraries. The scanner rescans in full only the ones that need it
|
||||||
fullScanRequired = "1"
|
log.Warn(ctx, "Libraries with a new or changed PID config, scanning", "libraries", pidChangedLibs)
|
||||||
case inProgress:
|
case inProgress:
|
||||||
log.Warn(ctx, "Resuming interrupted scan")
|
log.Warn(ctx, "Resuming interrupted scan")
|
||||||
default:
|
default:
|
||||||
|
|
@ -243,7 +255,7 @@ func runInitialScan(ctx context.Context) func() error {
|
||||||
|
|
||||||
func startScanWatcher(ctx context.Context) func() error {
|
func startScanWatcher(ctx context.Context) func() error {
|
||||||
return func() error {
|
return func() error {
|
||||||
if conf.Server.Scanner.WatcherWait == 0 {
|
if conf.Server().Scanner.WatcherWait == 0 {
|
||||||
log.Debug("Folder watcher is DISABLED")
|
log.Debug("Folder watcher is DISABLED")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -258,7 +270,7 @@ func startScanWatcher(ctx context.Context) func() error {
|
||||||
|
|
||||||
func schedulePeriodicBackup(ctx context.Context) func() error {
|
func schedulePeriodicBackup(ctx context.Context) func() error {
|
||||||
return func() error {
|
return func() error {
|
||||||
schedule := conf.Server.Backup.Schedule
|
schedule := conf.Server().Backup.Schedule
|
||||||
if schedule == "" {
|
if schedule == "" {
|
||||||
log.Info(ctx, "Periodic backup is DISABLED")
|
log.Info(ctx, "Periodic backup is DISABLED")
|
||||||
return nil
|
return nil
|
||||||
|
|
@ -293,7 +305,7 @@ func schedulePeriodicBackup(ctx context.Context) func() error {
|
||||||
|
|
||||||
func scheduleDBAnalyzer(ctx context.Context) func() error {
|
func scheduleDBAnalyzer(ctx context.Context) func() error {
|
||||||
return func() error {
|
return func() error {
|
||||||
if !conf.Server.EnableScheduledDBAnalyze {
|
if !conf.Server().EnableScheduledDBAnalyze {
|
||||||
log.Info(ctx, "Scheduled DB analysis is DISABLED")
|
log.Info(ctx, "Scheduled DB analysis is DISABLED")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -327,13 +339,13 @@ func startScheduler(ctx context.Context) func() error {
|
||||||
// startInsightsCollector starts the Navidrome Insight Collector, if configured.
|
// startInsightsCollector starts the Navidrome Insight Collector, if configured.
|
||||||
func startInsightsCollector(ctx context.Context) func() error {
|
func startInsightsCollector(ctx context.Context) func() error {
|
||||||
return func() error {
|
return func() error {
|
||||||
if !conf.Server.EnableInsightsCollector {
|
if !conf.Server().EnableInsightsCollector {
|
||||||
log.Info(ctx, "Insight Collector is DISABLED")
|
log.Info(ctx, "Insight Collector is DISABLED")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
log.Info(ctx, "Starting Insight Collector")
|
log.Info(ctx, "Starting Insight Collector")
|
||||||
select {
|
select {
|
||||||
case <-time.After(conf.Server.DevInsightsInitialDelay):
|
case <-time.After(conf.Server().DevInsightsInitialDelay):
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -343,11 +355,23 @@ func startInsightsCollector(ctx context.Context) func() error {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// startJellyfinDiscovery never returns an error: a discovery failure must not stop the server.
|
||||||
|
func startJellyfinDiscovery(ctx context.Context) func() error {
|
||||||
|
return func() error {
|
||||||
|
if !conf.Server().Jellyfin.Enabled || !conf.Server().Jellyfin.AutoDiscovery {
|
||||||
|
log.Debug("Jellyfin auto-discovery is DISABLED")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
CreateJellyfinDiscovery().Serve(ctx)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// startPlaybackServer starts the Navidrome playback server, if configured.
|
// startPlaybackServer starts the Navidrome playback server, if configured.
|
||||||
// It is responsible for the Jukebox functionality
|
// It is responsible for the Jukebox functionality
|
||||||
func startPlaybackServer(ctx context.Context) func() error {
|
func startPlaybackServer(ctx context.Context) func() error {
|
||||||
return func() error {
|
return func() error {
|
||||||
if !conf.Server.Jukebox.Enabled {
|
if !conf.Server().Jukebox.Enabled {
|
||||||
log.Debug("Jukebox is DISABLED")
|
log.Debug("Jukebox is DISABLED")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -362,10 +386,26 @@ func startPlaybackServer(ctx context.Context) func() error {
|
||||||
func startArtworkWorker(ctx context.Context, worker *artwork.Worker) func() error {
|
func startArtworkWorker(ctx context.Context, worker *artwork.Worker) func() error {
|
||||||
return func() error {
|
return func() error {
|
||||||
log.Info(ctx, "Starting artwork worker")
|
log.Info(ctx, "Starting artwork worker")
|
||||||
|
// The scanner writes to the DB for its whole run; competing for the write lock makes both fail.
|
||||||
|
worker.PauseWhile(scanner.IsScanning)
|
||||||
return worker.Run(ctx)
|
return worker.Run(ctx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// outsideScan runs a DB maintenance job unless a scan is running, and keeps a scan from starting
|
||||||
|
// until it ends; both write to the DB, and competing for the lock can make either fail.
|
||||||
|
func outsideScan(ctx context.Context, job string, run func(context.Context) error) {
|
||||||
|
release, ok := scanner.LockForMaintenance()
|
||||||
|
if !ok {
|
||||||
|
log.Debug(ctx, "Skipping "+job+" because a scan is in progress")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer release()
|
||||||
|
if err := run(ctx); err != nil {
|
||||||
|
log.Error(ctx, "Error running "+job, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// scheduleArtworkHousekeeping registers the recurring missing-state and prune jobs, and
|
// scheduleArtworkHousekeeping registers the recurring missing-state and prune jobs, and
|
||||||
// reports an artwork config change without acting on it.
|
// reports an artwork config change without acting on it.
|
||||||
func scheduleArtworkHousekeeping(ctx context.Context, worker *artwork.Worker) func() error {
|
func scheduleArtworkHousekeeping(ctx context.Context, worker *artwork.Worker) func() error {
|
||||||
|
|
@ -373,26 +413,20 @@ func scheduleArtworkHousekeeping(ctx context.Context, worker *artwork.Worker) fu
|
||||||
schedulerInstance := scheduler.GetInstance()
|
schedulerInstance := scheduler.GetInstance()
|
||||||
|
|
||||||
if _, err := schedulerInstance.Add(consts.ArtworkEnqueueMissingSchedule, func() {
|
if _, err := schedulerInstance.Add(consts.ArtworkEnqueueMissingSchedule, func() {
|
||||||
if err := worker.EnqueueMissingAll(ctx); err != nil {
|
outsideScan(ctx, "artwork missing-state recheck", worker.EnqueueMissingAll)
|
||||||
log.Error(ctx, "Error enqueueing missing artwork rechecks", err)
|
|
||||||
}
|
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
log.Error(ctx, "Error scheduling artwork missing-state recheck", err)
|
log.Error(ctx, "Error scheduling artwork missing-state recheck", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := schedulerInstance.Add(consts.ArtworkPruneSchedule, func() {
|
if _, err := schedulerInstance.Add(consts.ArtworkPruneSchedule, func() {
|
||||||
if err := worker.RunPrune(ctx); err != nil {
|
outsideScan(ctx, "artwork prune", worker.RunPrune)
|
||||||
log.Error(ctx, "Error running artwork prune", err)
|
|
||||||
}
|
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
log.Error(ctx, "Error scheduling artwork prune", err)
|
log.Error(ctx, "Error scheduling artwork prune", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Also run the missing-row recheck once at startup so a never-scanned entity is picked up
|
// Also run the missing-row recheck once at startup so a never-scanned entity is picked up
|
||||||
// immediately, not only on the next hourly tick (e.g. after enabling the feature).
|
// immediately, not only on the next hourly tick (e.g. after enabling the feature).
|
||||||
if err := worker.EnqueueMissingAll(ctx); err != nil {
|
outsideScan(ctx, "artwork missing-state recheck", worker.EnqueueMissingAll)
|
||||||
log.Error(ctx, "Error enqueueing missing artwork rechecks", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := worker.ReconcileConfig(ctx); err != nil {
|
if err := worker.ReconcileConfig(ctx); err != nil {
|
||||||
log.Error(ctx, "Error checking the artwork config fingerprint", err)
|
log.Error(ctx, "Error checking the artwork config fingerprint", err)
|
||||||
|
|
@ -405,7 +439,7 @@ func scheduleArtworkHousekeeping(ctx context.Context, worker *artwork.Worker) fu
|
||||||
func startPluginManager(ctx context.Context) func() error {
|
func startPluginManager(ctx context.Context) func() error {
|
||||||
return func() error {
|
return func() error {
|
||||||
manager := GetPluginManager(ctx)
|
manager := GetPluginManager(ctx)
|
||||||
if !conf.Server.Plugins.Enabled {
|
if !conf.Server().Plugins.Enabled {
|
||||||
log.Debug("Plugin system is DISABLED")
|
log.Debug("Plugin system is DISABLED")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -415,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)
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
package cmd
|
package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"path"
|
"path"
|
||||||
|
|
@ -8,7 +9,8 @@ import (
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/navidrome/navidrome/conf"
|
"github.com/navidrome/navidrome/conf"
|
||||||
"github.com/navidrome/navidrome/conf/configtest"
|
"github.com/navidrome/navidrome/model"
|
||||||
|
"github.com/navidrome/navidrome/tests"
|
||||||
. "github.com/onsi/ginkgo/v2"
|
. "github.com/onsi/ginkgo/v2"
|
||||||
. "github.com/onsi/gomega"
|
. "github.com/onsi/gomega"
|
||||||
)
|
)
|
||||||
|
|
@ -19,17 +21,13 @@ var _ = Describe("profilerHandler", func() {
|
||||||
// Mirrors how server.MountRouter mounts the handler.
|
// Mirrors how server.MountRouter mounts the handler.
|
||||||
mount := func() http.Handler {
|
mount := func() http.Handler {
|
||||||
router := chi.NewRouter()
|
router := chi.NewRouter()
|
||||||
router.Mount(path.Join(conf.Server.BasePath, "/debug"), profilerHandler())
|
router.Mount(path.Join(conf.Server().BasePath, "/debug"), profilerHandler())
|
||||||
return router
|
return router
|
||||||
}
|
}
|
||||||
|
|
||||||
BeforeEach(func() {
|
|
||||||
DeferCleanup(configtest.SetupConfig())
|
|
||||||
})
|
|
||||||
|
|
||||||
DescribeTable("serves a named profile",
|
DescribeTable("serves a named profile",
|
||||||
func(basePath string) {
|
func(basePath string) {
|
||||||
conf.Server.BasePath = basePath
|
conf.Update(func(c *conf.Options) { c.BasePath = basePath })
|
||||||
|
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
target := path.Join(basePath, "/debug/pprof/nd-profiler-test") + "?debug=1"
|
target := path.Join(basePath, "/debug/pprof/nd-profiler-test") + "?debug=1"
|
||||||
|
|
@ -44,3 +42,29 @@ var _ = Describe("profilerHandler", func() {
|
||||||
Entry("with a trailing-slash BasePath", "/music/"),
|
Entry("with a trailing-slash BasePath", "/music/"),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
var _ = Describe("librariesWithChangedPID", func() {
|
||||||
|
var ds *tests.MockDataStore
|
||||||
|
var libs *tests.MockLibraryRepo
|
||||||
|
|
||||||
|
BeforeEach(func() {
|
||||||
|
libs = &tests.MockLibraryRepo{}
|
||||||
|
ds = &tests.MockDataStore{MockedLibrary: libs}
|
||||||
|
})
|
||||||
|
|
||||||
|
It("returns only the libraries whose PID config changed", func() {
|
||||||
|
pid := model.Library{}.EffectivePID()
|
||||||
|
libs.SetData(model.Libraries{
|
||||||
|
{ID: 1, Name: "Same", ScannedPIDAlbum: pid.Album, ScannedPIDTrack: pid.Track},
|
||||||
|
{ID: 2, Name: "Changed", PIDAlbum: "folder", ScannedPIDAlbum: pid.Album, ScannedPIDTrack: pid.Track},
|
||||||
|
{ID: 3, Name: "Never scanned"},
|
||||||
|
})
|
||||||
|
Expect(librariesWithChangedPID(GinkgoT().Context(), ds)).To(ConsistOf("Changed", "Never scanned"))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("returns the error from the repository", func() {
|
||||||
|
libs.Err = errors.New("db down")
|
||||||
|
_, err := librariesWithChangedPID(GinkgoT().Context(), ds)
|
||||||
|
Expect(err).To(MatchError("db down"))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
package cmd
|
package cmd
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
|
|
@ -18,7 +17,7 @@ var _ = Describe("trackScanInteractively", func() {
|
||||||
progress <- &scanner.ProgressInfo{Error: "scan failed"}
|
progress <- &scanner.ProgressInfo{Error: "scan failed"}
|
||||||
close(progress)
|
close(progress)
|
||||||
|
|
||||||
changesDetected, err := trackScanInteractively(context.Background(), progress)
|
changesDetected, err := trackScanInteractively(GinkgoT().Context(), progress)
|
||||||
Expect(changesDetected).To(BeTrue())
|
Expect(changesDetected).To(BeTrue())
|
||||||
Expect(err).To(MatchError("scan failed"))
|
Expect(err).To(MatchError("scan failed"))
|
||||||
})
|
})
|
||||||
|
|
|
||||||
55
cmd/search.go
Normal file
55
cmd/search.go
Normal file
|
|
@ -0,0 +1,55 @@
|
||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/db"
|
||||||
|
"github.com/navidrome/navidrome/log"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
var searchRebuildForce bool
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
rootCmd.AddCommand(searchRoot)
|
||||||
|
|
||||||
|
searchRebuildCmd.Flags().BoolVarP(&searchRebuildForce, "force", "f", false, "bypass rebuild confirmation")
|
||||||
|
searchRoot.AddCommand(searchRebuildCmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
searchRoot = &cobra.Command{
|
||||||
|
Use: "search",
|
||||||
|
Short: "Search index maintenance",
|
||||||
|
}
|
||||||
|
|
||||||
|
searchRebuildCmd = &cobra.Command{
|
||||||
|
Use: "rebuild",
|
||||||
|
Short: "Rebuild the full-text search index",
|
||||||
|
Long: "Drop and rebuild the full-text search index from the library data. Fixes a corrupted " +
|
||||||
|
"or desynced search index without any data loss. Note that 'navidrome doctor' detects a " +
|
||||||
|
"corrupted index, but cannot tell when the index has merely drifted out of sync with the " +
|
||||||
|
"library. This must be done offline",
|
||||||
|
Run: func(cmd *cobra.Command, _ []string) {
|
||||||
|
runSearchRebuild(cmd.Context())
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func runSearchRebuild(ctx context.Context) {
|
||||||
|
requireExistingDB()
|
||||||
|
|
||||||
|
if !searchRebuildForce && !confirmYES("This will rebuild the search index. Make sure Navidrome is not running.") {
|
||||||
|
log.Warn("Rebuild cancelled")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("Rebuilding the search index...")
|
||||||
|
err := db.RebuildFTS(ctx, db.Db())
|
||||||
|
db.Close(ctx)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("Error rebuilding the search index", err)
|
||||||
|
}
|
||||||
|
fmt.Println("Search index rebuilt successfully.")
|
||||||
|
}
|
||||||
37
cmd/svc.go
37
cmd/svc.go
|
|
@ -44,7 +44,7 @@ var svcCmd = &cobra.Command{
|
||||||
}
|
}
|
||||||
|
|
||||||
type svcControl struct {
|
type svcControl struct {
|
||||||
ctx context.Context
|
ctx context.Context //nolint:containedctx // service lifecycle ctx, cancelled by Stop
|
||||||
cancel context.CancelFunc
|
cancel context.CancelFunc
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
}
|
}
|
||||||
|
|
@ -53,8 +53,13 @@ func (p *svcControl) Start(service.Service) error {
|
||||||
p.done = make(chan struct{})
|
p.done = make(chan struct{})
|
||||||
p.ctx, p.cancel = context.WithCancel(context.Background())
|
p.ctx, p.cancel = context.WithCancel(context.Background())
|
||||||
go func() {
|
go func() {
|
||||||
runNavidrome(p.ctx)
|
err := runNavidrome(p.ctx)
|
||||||
close(p.done)
|
close(p.done)
|
||||||
|
// service.Run() only returns when it gets a stop request, so exit here to let the
|
||||||
|
// service manager see the failure and restart the service
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("Fatal error in Navidrome. Aborting", err)
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -74,15 +79,15 @@ func (p *svcControl) Stop(service.Service) error {
|
||||||
var svcInstance = sync.OnceValue(func() service.Service {
|
var svcInstance = sync.OnceValue(func() service.Service {
|
||||||
options := make(service.KeyValue)
|
options := make(service.KeyValue)
|
||||||
options["Restart"] = "on-failure"
|
options["Restart"] = "on-failure"
|
||||||
options["SuccessExitStatus"] = "1 2 8 SIGKILL"
|
options["SuccessExitStatus"] = "SIGKILL"
|
||||||
options["UserService"] = false
|
options["UserService"] = false
|
||||||
options["LogDirectory"] = conf.Server.DataFolder.String()
|
options["LogDirectory"] = conf.Server().DataFolder.String()
|
||||||
options["SystemdScript"] = systemdScript
|
options["SystemdScript"] = systemdScript
|
||||||
if conf.Server.LogFile != "" {
|
if conf.Server().LogFile != "" {
|
||||||
options["LogOutput"] = false
|
options["LogOutput"] = false
|
||||||
} else {
|
} else {
|
||||||
options["LogOutput"] = true
|
options["LogOutput"] = true
|
||||||
options["LogDirectory"] = conf.Server.DataFolder.String()
|
options["LogDirectory"] = conf.Server().DataFolder.String()
|
||||||
}
|
}
|
||||||
svcConfig := &service.Config{
|
svcConfig := &service.Config{
|
||||||
UserName: installUser,
|
UserName: installUser,
|
||||||
|
|
@ -96,8 +101,8 @@ var svcInstance = sync.OnceValue(func() service.Service {
|
||||||
Option: options,
|
Option: options,
|
||||||
}
|
}
|
||||||
arguments := []string{"service", "execute"}
|
arguments := []string{"service", "execute"}
|
||||||
if conf.Server.ConfigFile != "" {
|
if conf.Server().ConfigFile != "" {
|
||||||
arguments = append(arguments, "-c", conf.Server.ConfigFile)
|
arguments = append(arguments, "-c", conf.Server().ConfigFile)
|
||||||
}
|
}
|
||||||
svcConfig.Arguments = arguments
|
svcConfig.Arguments = arguments
|
||||||
|
|
||||||
|
|
@ -130,19 +135,21 @@ func buildInstallCmd() *cobra.Command {
|
||||||
var err error
|
var err error
|
||||||
println("Installing service with:")
|
println("Installing service with:")
|
||||||
println(" working directory: " + executablePath())
|
println(" working directory: " + executablePath())
|
||||||
println(" music folder: " + conf.Server.MusicFolder)
|
println(" music folder: " + conf.Server().MusicFolder)
|
||||||
println(" data folder: " + conf.Server.DataFolder.String())
|
println(" data folder: " + conf.Server().DataFolder.String())
|
||||||
if conf.Server.LogFile != "" {
|
if conf.Server().LogFile != "" {
|
||||||
println(" log file: " + conf.Server.LogFile)
|
println(" log file: " + conf.Server().LogFile)
|
||||||
} else {
|
} else {
|
||||||
println(" logs folder: " + conf.Server.DataFolder.String())
|
println(" logs folder: " + conf.Server().DataFolder.String())
|
||||||
}
|
}
|
||||||
if cfgFile != "" {
|
if cfgFile != "" {
|
||||||
conf.Server.ConfigFile, err = filepath.Abs(cfgFile)
|
var absPath string
|
||||||
|
absPath, err = filepath.Abs(cfgFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
println(" config file: " + conf.Server.ConfigFile)
|
conf.Update(func(c *conf.Options) { c.ConfigFile = absPath })
|
||||||
|
println(" config file: " + absPath)
|
||||||
}
|
}
|
||||||
err = svcInstance().Install()
|
err = svcInstance().Install()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
||||||
31
cmd/user.go
31
cmd/user.go
|
|
@ -183,7 +183,7 @@ func runCreateUser(ctx context.Context) {
|
||||||
ds, ctx := getAdminContext(ctx)
|
ds, ctx := getAdminContext(ctx)
|
||||||
|
|
||||||
err := ds.WithTx(func(tx model.DataStore) error {
|
err := ds.WithTx(func(tx model.DataStore) error {
|
||||||
existingUser, err := tx.User(ctx).FindByUsername(userID)
|
existingUser, err := tx.User().FindByUsername(ctx, userID)
|
||||||
if existingUser != nil {
|
if existingUser != nil {
|
||||||
return fmt.Errorf("existing user '%s'", userID)
|
return fmt.Errorf("existing user '%s'", userID)
|
||||||
}
|
}
|
||||||
|
|
@ -193,7 +193,7 @@ func runCreateUser(ctx context.Context) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(libraryIds) > 0 && !setAdmin {
|
if len(libraryIds) > 0 && !setAdmin {
|
||||||
user.Libraries, err = tx.Library(ctx).GetAll(model.QueryOptions{Filters: squirrel.Eq{"id": libraryIds}})
|
user.Libraries, err = tx.Library().GetAll(ctx, model.QueryOptions{Filters: squirrel.Eq{"id": libraryIds}})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -202,13 +202,13 @@ func runCreateUser(ctx context.Context) {
|
||||||
return libraryError(user.Libraries)
|
return libraryError(user.Libraries)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
user.Libraries, err = tx.Library(ctx).GetAll()
|
user.Libraries, err = tx.Library().GetAll(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
err = tx.User(ctx).Put(&user)
|
err = tx.User().Put(ctx, &user)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -218,7 +218,7 @@ func runCreateUser(ctx context.Context) {
|
||||||
updatedIds[idx] = lib.ID
|
updatedIds[idx] = lib.ID
|
||||||
}
|
}
|
||||||
|
|
||||||
err = tx.User(ctx).SetUserLibraries(user.ID, updatedIds)
|
err = tx.User().SetUserLibraries(ctx, user.ID, updatedIds)
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -236,7 +236,7 @@ func runDeleteUser(ctx context.Context) {
|
||||||
var user *model.User
|
var user *model.User
|
||||||
|
|
||||||
err = ds.WithTx(func(tx model.DataStore) error {
|
err = ds.WithTx(func(tx model.DataStore) error {
|
||||||
count, err := tx.User(ctx).CountAll()
|
count, err := tx.User().CountAll(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -250,7 +250,7 @@ func runDeleteUser(ctx context.Context) {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return tx.User(ctx).Delete(user.ID)
|
return tx.User().Delete(ctx, user.ID)
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -276,7 +276,7 @@ func runUserEdit(ctx context.Context) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(libraryIds) > 0 && !setAdmin {
|
if len(libraryIds) > 0 && !setAdmin {
|
||||||
libraries, err := tx.Library(ctx).GetAll(model.QueryOptions{Filters: squirrel.Eq{"id": libraryIds}})
|
libraries, err := tx.Library().GetAll(ctx, model.QueryOptions{Filters: squirrel.Eq{"id": libraryIds}})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|
@ -291,7 +291,7 @@ func runUserEdit(ctx context.Context) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if setAdmin && !user.IsAdmin {
|
if setAdmin && !user.IsAdmin {
|
||||||
libraries, err := tx.Library(ctx).GetAll()
|
libraries, err := tx.Library().GetAll(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -337,7 +337,7 @@ func runUserEdit(ctx context.Context) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
err := tx.User(ctx).Put(user)
|
err := tx.User().Put(ctx, user)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -348,7 +348,7 @@ func runUserEdit(ctx context.Context) {
|
||||||
updatedIds[idx] = lib.ID
|
updatedIds[idx] = lib.ID
|
||||||
}
|
}
|
||||||
|
|
||||||
err := tx.User(ctx).SetUserLibraries(user.ID, updatedIds)
|
err := tx.User().SetUserLibraries(ctx, user.ID, updatedIds)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -393,13 +393,11 @@ func runUserList(ctx context.Context) {
|
||||||
|
|
||||||
ds, ctx := getAdminContext(ctx)
|
ds, ctx := getAdminContext(ctx)
|
||||||
|
|
||||||
users, err := ds.User(ctx).ReadAll()
|
userList, err := ds.User().ReadAll(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(ctx, "Failed to retrieve users", err)
|
log.Fatal(ctx, "Failed to retrieve users", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
userList := users.(model.Users)
|
|
||||||
|
|
||||||
if outputFormat == "csv" {
|
if outputFormat == "csv" {
|
||||||
w := csv.NewWriter(os.Stdout)
|
w := csv.NewWriter(os.Stdout)
|
||||||
_ = w.Write([]string{
|
_ = w.Write([]string{
|
||||||
|
|
@ -471,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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
29
cmd/utils.go
29
cmd/utils.go
|
|
@ -5,8 +5,11 @@ import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
"text/tabwriter"
|
"text/tabwriter"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/conf"
|
||||||
"github.com/navidrome/navidrome/core/auth"
|
"github.com/navidrome/navidrome/core/auth"
|
||||||
"github.com/navidrome/navidrome/db"
|
"github.com/navidrome/navidrome/db"
|
||||||
"github.com/navidrome/navidrome/log"
|
"github.com/navidrome/navidrome/log"
|
||||||
|
|
@ -15,6 +18,28 @@ import (
|
||||||
"github.com/navidrome/navidrome/persistence"
|
"github.com/navidrome/navidrome/persistence"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// existingDBFile returns the database file (DbPath minus DSN params), and whether it exists.
|
||||||
|
func existingDBFile() (string, bool) {
|
||||||
|
path, _, _ := strings.Cut(conf.Server().DbPath, "?")
|
||||||
|
_, err := os.Stat(path)
|
||||||
|
return path, err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// requireExistingDB aborts the command when the database file does not exist.
|
||||||
|
func requireExistingDB() {
|
||||||
|
if path, ok := existingDBFile(); !ok {
|
||||||
|
log.Fatal("No existing database", "path", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func confirmYES(warning string) bool {
|
||||||
|
fmt.Println(warning)
|
||||||
|
fmt.Printf("Please enter YES (all caps) to continue: ")
|
||||||
|
var input string
|
||||||
|
_, err := fmt.Scanln(&input)
|
||||||
|
return input == "YES" && err == nil
|
||||||
|
}
|
||||||
|
|
||||||
// newTabWriter keeps every CLI table on the same column settings.
|
// newTabWriter keeps every CLI table on the same column settings.
|
||||||
func newTabWriter(out io.Writer) *tabwriter.Writer {
|
func newTabWriter(out io.Writer) *tabwriter.Writer {
|
||||||
return tabwriter.NewWriter(out, 0, 4, 2, ' ', 0)
|
return tabwriter.NewWriter(out, 0, 4, 2, ' ', 0)
|
||||||
|
|
@ -32,14 +57,14 @@ func getAdminContext(ctx context.Context) (model.DataStore, context.Context) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func getUser(ctx context.Context, id string, ds model.DataStore) (*model.User, error) {
|
func getUser(ctx context.Context, id string, ds model.DataStore) (*model.User, error) {
|
||||||
user, err := ds.User(ctx).FindByUsername(id)
|
user, err := ds.User().FindByUsername(ctx, id)
|
||||||
|
|
||||||
if err != nil && !errors.Is(err, model.ErrNotFound) {
|
if err != nil && !errors.Is(err, model.ErrNotFound) {
|
||||||
return nil, fmt.Errorf("finding user by name: %w", err)
|
return nil, fmt.Errorf("finding user by name: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if errors.Is(err, model.ErrNotFound) {
|
if errors.Is(err, model.ErrNotFound) {
|
||||||
user, err = ds.User(ctx).Get(id)
|
user, err = ds.User().Get(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("finding user by id: %w", err)
|
return nil, fmt.Errorf("finding user by id: %w", err)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@ import (
|
||||||
"github.com/navidrome/navidrome/core/metrics"
|
"github.com/navidrome/navidrome/core/metrics"
|
||||||
"github.com/navidrome/navidrome/core/playback"
|
"github.com/navidrome/navidrome/core/playback"
|
||||||
"github.com/navidrome/navidrome/core/playlists"
|
"github.com/navidrome/navidrome/core/playlists"
|
||||||
|
"github.com/navidrome/navidrome/core/quickconnect"
|
||||||
"github.com/navidrome/navidrome/core/scrobbler"
|
"github.com/navidrome/navidrome/core/scrobbler"
|
||||||
"github.com/navidrome/navidrome/core/sonic"
|
"github.com/navidrome/navidrome/core/sonic"
|
||||||
"github.com/navidrome/navidrome/core/stream"
|
"github.com/navidrome/navidrome/core/stream"
|
||||||
|
|
@ -30,6 +31,7 @@ import (
|
||||||
"github.com/navidrome/navidrome/plugins"
|
"github.com/navidrome/navidrome/plugins"
|
||||||
"github.com/navidrome/navidrome/scanner"
|
"github.com/navidrome/navidrome/scanner"
|
||||||
"github.com/navidrome/navidrome/server"
|
"github.com/navidrome/navidrome/server"
|
||||||
|
"github.com/navidrome/navidrome/server/apiv1"
|
||||||
"github.com/navidrome/navidrome/server/events"
|
"github.com/navidrome/navidrome/server/events"
|
||||||
"github.com/navidrome/navidrome/server/jellyfin"
|
"github.com/navidrome/navidrome/server/jellyfin"
|
||||||
"github.com/navidrome/navidrome/server/nativeapi"
|
"github.com/navidrome/navidrome/server/nativeapi"
|
||||||
|
|
@ -70,7 +72,7 @@ func CreateNativeAPIRouter(ctx context.Context) *nativeapi.Router {
|
||||||
insights := metrics.GetInstance(dataStore)
|
insights := metrics.GetInstance(dataStore)
|
||||||
broker := events.GetBroker()
|
broker := events.GetBroker()
|
||||||
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
|
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
|
||||||
modelScanner := scanner.New(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics)
|
modelScanner := scanner.GetInstance(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics)
|
||||||
watcher := scanner.GetWatcher(dataStore, modelScanner)
|
watcher := scanner.GetWatcher(dataStore, modelScanner)
|
||||||
manager := plugins.GetManager(dataStore, broker, metricsMetrics)
|
manager := plugins.GetManager(dataStore, broker, metricsMetrics)
|
||||||
library := core.NewLibrary(dataStore, modelScanner, watcher, broker, manager)
|
library := core.NewLibrary(dataStore, modelScanner, watcher, broker, manager)
|
||||||
|
|
@ -79,7 +81,8 @@ func CreateNativeAPIRouter(ctx context.Context) *nativeapi.Router {
|
||||||
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(dataStore, agentsAgents, matcherMatcher, broker)
|
||||||
router := nativeapi.New(dataStore, share, playlistsPlaylists, insights, library, user, maintenance, manager, uploader, provider)
|
quickConnect := quickconnect.GetInstance()
|
||||||
|
router := nativeapi.New(dataStore, share, playlistsPlaylists, insights, library, user, maintenance, manager, uploader, provider, quickConnect)
|
||||||
return router
|
return router
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -92,8 +95,9 @@ func CreateSubsonicAPIRouter(ctx context.Context) *subsonic.Router {
|
||||||
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, imageStore, fFmpeg)
|
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, imageStore, fFmpeg)
|
||||||
transcodingCache := stream.GetTranscodingCache()
|
transcodingCache := stream.GetTranscodingCache()
|
||||||
mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache)
|
mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache)
|
||||||
|
transcodeDecider := stream.NewTranscodeDecider(dataStore, fFmpeg)
|
||||||
share := core.NewShare(dataStore)
|
share := core.NewShare(dataStore)
|
||||||
archiver := core.NewArchiver(mediaStreamer, dataStore, share)
|
archiver := core.NewArchiver(mediaStreamer, transcodeDecider, dataStore, share, artworkArtwork)
|
||||||
players := core.NewPlayers(dataStore)
|
players := core.NewPlayers(dataStore)
|
||||||
broker := events.GetBroker()
|
broker := events.GetBroker()
|
||||||
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
|
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
|
||||||
|
|
@ -103,11 +107,10 @@ func CreateSubsonicAPIRouter(ctx context.Context) *subsonic.Router {
|
||||||
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher, broker)
|
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher, broker)
|
||||||
uploader := artwork.NewUploader(dataStore)
|
uploader := artwork.NewUploader(dataStore)
|
||||||
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader)
|
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader)
|
||||||
modelScanner := scanner.New(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics)
|
modelScanner := scanner.GetInstance(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics)
|
||||||
playTracker := scrobbler.GetPlayTracker(dataStore, broker, manager)
|
playTracker := scrobbler.GetPlayTracker(dataStore, broker, manager)
|
||||||
playbackServer := playback.GetInstance(dataStore)
|
playbackServer := playback.GetInstance(dataStore)
|
||||||
lyricsLyrics := lyrics.NewLyrics(dataStore, manager)
|
lyricsLyrics := lyrics.NewLyrics(dataStore, manager)
|
||||||
transcodeDecider := stream.NewTranscodeDecider(dataStore, fFmpeg)
|
|
||||||
sonicSonic := sonic.New(dataStore, manager, matcherMatcher)
|
sonicSonic := sonic.New(dataStore, manager, matcherMatcher)
|
||||||
router := subsonic.New(dataStore, artworkArtwork, mediaStreamer, archiver, players, provider, modelScanner, broker, playlistsPlaylists, playTracker, share, playbackServer, metricsMetrics, lyricsLyrics, transcodeDecider, sonicSonic)
|
router := subsonic.New(dataStore, artworkArtwork, mediaStreamer, archiver, players, provider, modelScanner, broker, playlistsPlaylists, playTracker, share, playbackServer, metricsMetrics, lyricsLyrics, transcodeDecider, sonicSonic)
|
||||||
return router
|
return router
|
||||||
|
|
@ -135,7 +138,15 @@ func CreateJellyfinAPIRouter(ctx context.Context) *jellyfin.Router {
|
||||||
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher, broker)
|
provider := external.NewProvider(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)
|
||||||
router := jellyfin.New(dataStore, artworkArtwork, mediaStreamer, transcodeDecider, players, playTracker, playlistsPlaylists, provider, sonicSonic, lyricsLyrics, broker)
|
quickConnect := quickconnect.GetInstance()
|
||||||
|
router := jellyfin.New(dataStore, artworkArtwork, mediaStreamer, transcodeDecider, players, playTracker, playlistsPlaylists, provider, sonicSonic, lyricsLyrics, broker, quickConnect)
|
||||||
|
return router
|
||||||
|
}
|
||||||
|
|
||||||
|
func CreateAPIv1Router(ctx context.Context) *apiv1.Router {
|
||||||
|
sqlDB := db.Db()
|
||||||
|
dataStore := persistence.New(sqlDB)
|
||||||
|
router := apiv1.New(dataStore)
|
||||||
return router
|
return router
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -148,9 +159,10 @@ func CreatePublicRouter() *public.Router {
|
||||||
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, imageStore, fFmpeg)
|
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, imageStore, fFmpeg)
|
||||||
transcodingCache := stream.GetTranscodingCache()
|
transcodingCache := stream.GetTranscodingCache()
|
||||||
mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache)
|
mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache)
|
||||||
|
transcodeDecider := stream.NewTranscodeDecider(dataStore, fFmpeg)
|
||||||
share := core.NewShare(dataStore)
|
share := core.NewShare(dataStore)
|
||||||
archiver := core.NewArchiver(mediaStreamer, dataStore, share)
|
archiver := core.NewArchiver(mediaStreamer, transcodeDecider, dataStore, share, artworkArtwork)
|
||||||
router := public.New(dataStore, artworkArtwork, mediaStreamer, share, archiver)
|
router := public.New(dataStore, artworkArtwork, mediaStreamer, transcodeDecider, share, archiver)
|
||||||
return router
|
return router
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -168,6 +180,13 @@ func CreateListenBrainzRouter() *listenbrainz.Router {
|
||||||
return router
|
return router
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func CreateJellyfinDiscovery() *jellyfin.Discovery {
|
||||||
|
sqlDB := db.Db()
|
||||||
|
dataStore := persistence.New(sqlDB)
|
||||||
|
discovery := jellyfin.NewDiscovery(dataStore)
|
||||||
|
return discovery
|
||||||
|
}
|
||||||
|
|
||||||
func CreateInsights() metrics.Insights {
|
func CreateInsights() metrics.Insights {
|
||||||
sqlDB := db.Db()
|
sqlDB := db.Db()
|
||||||
dataStore := persistence.New(sqlDB)
|
dataStore := persistence.New(sqlDB)
|
||||||
|
|
@ -189,7 +208,7 @@ func CreateScanner(ctx context.Context) model.Scanner {
|
||||||
uploader := artwork.NewUploader(dataStore)
|
uploader := artwork.NewUploader(dataStore)
|
||||||
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader)
|
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader)
|
||||||
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
|
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
|
||||||
modelScanner := scanner.New(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics)
|
modelScanner := scanner.GetInstance(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics)
|
||||||
return modelScanner
|
return modelScanner
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -200,7 +219,7 @@ func CreateScanWatcher(ctx context.Context) scanner.Watcher {
|
||||||
uploader := artwork.NewUploader(dataStore)
|
uploader := artwork.NewUploader(dataStore)
|
||||||
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader)
|
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader)
|
||||||
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
|
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
|
||||||
modelScanner := scanner.New(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics)
|
modelScanner := scanner.GetInstance(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics)
|
||||||
watcher := scanner.GetWatcher(dataStore, modelScanner)
|
watcher := scanner.GetWatcher(dataStore, modelScanner)
|
||||||
return watcher
|
return watcher
|
||||||
}
|
}
|
||||||
|
|
@ -249,7 +268,7 @@ func getPluginManager() *plugins.Manager {
|
||||||
|
|
||||||
// wire_injectors.go:
|
// wire_injectors.go:
|
||||||
|
|
||||||
var allProviders = wire.NewSet(core.Set, artwork.Set, server.New, subsonic.New, jellyfin.New, nativeapi.New, public.New, persistence.New, lastfm.NewRouter, listenbrainz.NewRouter, events.GetBroker, scanner.New, scanner.GetWatcher, metrics.GetPrometheusInstance, db.Db, plugins.GetManager, sonic.New, wire.Bind(new(agents.PluginLoader), new(*plugins.Manager)), wire.Bind(new(scrobbler.PluginLoader), new(*plugins.Manager)), wire.Bind(new(lyrics.PluginLoader), new(*plugins.Manager)), wire.Bind(new(sonic.PluginLoader), new(*plugins.Manager)), wire.Bind(new(sonic.Engine), new(*sonic.Sonic)), wire.Bind(new(nativeapi.PluginManager), new(*plugins.Manager)), wire.Bind(new(core.PluginUnloader), new(*plugins.Manager)), wire.Bind(new(plugins.PluginMetricsRecorder), new(metrics.Metrics)), wire.Bind(new(core.Watcher), new(scanner.Watcher)), wire.Bind(new(playlists.ImageUploadService), new(artwork.Uploader)))
|
var allProviders = wire.NewSet(core.Set, artwork.Set, server.New, subsonic.New, jellyfin.New, jellyfin.NewDiscovery, apiv1.New, nativeapi.New, public.New, persistence.New, lastfm.NewRouter, listenbrainz.NewRouter, events.GetBroker, scanner.GetInstance, scanner.GetWatcher, metrics.GetPrometheusInstance, db.Db, plugins.GetManager, sonic.New, wire.Bind(new(agents.PluginLoader), new(*plugins.Manager)), wire.Bind(new(scrobbler.PluginLoader), new(*plugins.Manager)), wire.Bind(new(lyrics.PluginLoader), new(*plugins.Manager)), wire.Bind(new(sonic.PluginLoader), new(*plugins.Manager)), wire.Bind(new(sonic.Engine), new(*sonic.Sonic)), wire.Bind(new(nativeapi.PluginManager), new(*plugins.Manager)), wire.Bind(new(core.PluginUnloader), new(*plugins.Manager)), wire.Bind(new(plugins.PluginMetricsRecorder), new(metrics.Metrics)), wire.Bind(new(core.Watcher), new(scanner.Watcher)), wire.Bind(new(playlists.ImageUploadService), new(artwork.Uploader)))
|
||||||
|
|
||||||
func GetPluginManager(ctx context.Context) *plugins.Manager {
|
func GetPluginManager(ctx context.Context) *plugins.Manager {
|
||||||
manager := getPluginManager()
|
manager := getPluginManager()
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@ import (
|
||||||
"github.com/navidrome/navidrome/plugins"
|
"github.com/navidrome/navidrome/plugins"
|
||||||
"github.com/navidrome/navidrome/scanner"
|
"github.com/navidrome/navidrome/scanner"
|
||||||
"github.com/navidrome/navidrome/server"
|
"github.com/navidrome/navidrome/server"
|
||||||
|
"github.com/navidrome/navidrome/server/apiv1"
|
||||||
"github.com/navidrome/navidrome/server/events"
|
"github.com/navidrome/navidrome/server/events"
|
||||||
"github.com/navidrome/navidrome/server/jellyfin"
|
"github.com/navidrome/navidrome/server/jellyfin"
|
||||||
"github.com/navidrome/navidrome/server/nativeapi"
|
"github.com/navidrome/navidrome/server/nativeapi"
|
||||||
|
|
@ -36,13 +37,15 @@ var allProviders = wire.NewSet(
|
||||||
server.New,
|
server.New,
|
||||||
subsonic.New,
|
subsonic.New,
|
||||||
jellyfin.New,
|
jellyfin.New,
|
||||||
|
jellyfin.NewDiscovery,
|
||||||
|
apiv1.New,
|
||||||
nativeapi.New,
|
nativeapi.New,
|
||||||
public.New,
|
public.New,
|
||||||
persistence.New,
|
persistence.New,
|
||||||
lastfm.NewRouter,
|
lastfm.NewRouter,
|
||||||
listenbrainz.NewRouter,
|
listenbrainz.NewRouter,
|
||||||
events.GetBroker,
|
events.GetBroker,
|
||||||
scanner.New,
|
scanner.GetInstance,
|
||||||
scanner.GetWatcher,
|
scanner.GetWatcher,
|
||||||
metrics.GetPrometheusInstance,
|
metrics.GetPrometheusInstance,
|
||||||
db.Db,
|
db.Db,
|
||||||
|
|
@ -90,6 +93,12 @@ func CreateJellyfinAPIRouter(ctx context.Context) *jellyfin.Router {
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func CreateAPIv1Router(ctx context.Context) *apiv1.Router {
|
||||||
|
panic(wire.Build(
|
||||||
|
allProviders,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
func CreatePublicRouter() *public.Router {
|
func CreatePublicRouter() *public.Router {
|
||||||
panic(wire.Build(
|
panic(wire.Build(
|
||||||
allProviders,
|
allProviders,
|
||||||
|
|
@ -108,6 +117,12 @@ func CreateListenBrainzRouter() *listenbrainz.Router {
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func CreateJellyfinDiscovery() *jellyfin.Discovery {
|
||||||
|
panic(wire.Build(
|
||||||
|
allProviders,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
func CreateInsights() metrics.Insights {
|
func CreateInsights() metrics.Insights {
|
||||||
panic(wire.Build(
|
panic(wire.Build(
|
||||||
allProviders,
|
allProviders,
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,16 @@
|
||||||
package configtest
|
package configtest
|
||||||
|
|
||||||
import "github.com/navidrome/navidrome/conf"
|
import (
|
||||||
|
"github.com/navidrome/navidrome/conf"
|
||||||
|
"github.com/onsi/ginkgo/v2"
|
||||||
|
)
|
||||||
|
|
||||||
// TODO Remove this redirection and call SnapshotConfig directly from tests
|
// RestoreAfterEachSpec restores the config after every spec. Call it at the top level of a suite.
|
||||||
func SetupConfig() func() {
|
// Ordered specs are skipped so a BeforeAll can set config for its whole container.
|
||||||
return conf.SnapshotConfig()
|
func RestoreAfterEachSpec() bool {
|
||||||
|
return ginkgo.BeforeEach(func() {
|
||||||
|
if !ginkgo.CurrentSpecReport().IsInOrderedContainer {
|
||||||
|
ginkgo.DeferCleanup(conf.SnapshotConfig())
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
16
conf/configtest/configtest_suite_test.go
Normal file
16
conf/configtest/configtest_suite_test.go
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
package configtest_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/conf/configtest"
|
||||||
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
. "github.com/onsi/gomega"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestConfigtest(t *testing.T) {
|
||||||
|
RegisterFailHandler(Fail)
|
||||||
|
RunSpecs(t, "Configtest Suite")
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ = configtest.RestoreAfterEachSpec()
|
||||||
35
conf/configtest/configtest_test.go
Normal file
35
conf/configtest/configtest_test.go
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
package configtest_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/navidrome/navidrome/conf"
|
||||||
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
. "github.com/onsi/gomega"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ = Describe("RestoreAfterEachSpec", func() {
|
||||||
|
// Either spec can run first: the second one sees the first one's change if it leaks.
|
||||||
|
It("starts with the original value (A)", func() {
|
||||||
|
Expect(conf.Server().UIWelcomeMessage).To(BeEmpty())
|
||||||
|
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "A" })
|
||||||
|
})
|
||||||
|
|
||||||
|
It("starts with the original value (B)", func() {
|
||||||
|
Expect(conf.Server().UIWelcomeMessage).To(BeEmpty())
|
||||||
|
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "B" })
|
||||||
|
})
|
||||||
|
|
||||||
|
Describe("in an Ordered container", Ordered, func() {
|
||||||
|
BeforeAll(func() {
|
||||||
|
DeferCleanup(conf.SnapshotConfig())
|
||||||
|
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "ordered" })
|
||||||
|
})
|
||||||
|
|
||||||
|
It("sees the BeforeAll change in the first spec", func() {
|
||||||
|
Expect(conf.Server().UIWelcomeMessage).To(Equal("ordered"))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("still sees the BeforeAll change in later specs", func() {
|
||||||
|
Expect(conf.Server().UIWelcomeMessage).To(Equal("ordered"))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -3,7 +3,7 @@ package conf
|
||||||
import (
|
import (
|
||||||
"cmp"
|
"cmp"
|
||||||
"encoding"
|
"encoding"
|
||||||
"encoding/json"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
|
@ -30,7 +30,7 @@ import (
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
)
|
)
|
||||||
|
|
||||||
type configOptions struct {
|
type Options struct {
|
||||||
ConfigFile string `conf:"-"`
|
ConfigFile string `conf:"-"`
|
||||||
Address string
|
Address string
|
||||||
Port int
|
Port int
|
||||||
|
|
@ -102,6 +102,7 @@ type configOptions struct {
|
||||||
DefaultUIVolume int
|
DefaultUIVolume int
|
||||||
UISearchDebounceMs int
|
UISearchDebounceMs int
|
||||||
UICoverArtSize int
|
UICoverArtSize int
|
||||||
|
UIAppendRemixers bool // Whether to show remixers after the track artists in the UI
|
||||||
EnableReplayGain bool
|
EnableReplayGain bool
|
||||||
EnableCoverAnimation bool
|
EnableCoverAnimation bool
|
||||||
EnableNowPlaying bool
|
EnableNowPlaying bool
|
||||||
|
|
@ -143,6 +144,7 @@ type configOptions struct {
|
||||||
DevUIShowConfig bool
|
DevUIShowConfig bool
|
||||||
DevNewEventStream bool
|
DevNewEventStream bool
|
||||||
DevOffsetOptimize int
|
DevOffsetOptimize int
|
||||||
|
DevMaxPlaylistTracksPerRequest int
|
||||||
DevArtworkMaxRequests int
|
DevArtworkMaxRequests int
|
||||||
DevArtworkThrottleBacklogLimit int
|
DevArtworkThrottleBacklogLimit int
|
||||||
DevArtworkThrottleBacklogTimeout time.Duration
|
DevArtworkThrottleBacklogTimeout time.Duration
|
||||||
|
|
@ -161,6 +163,8 @@ type configOptions struct {
|
||||||
DevExternalArtistFetchMultiplier float64
|
DevExternalArtistFetchMultiplier float64
|
||||||
DevPreserveUnicodeInExternalCalls bool
|
DevPreserveUnicodeInExternalCalls bool
|
||||||
DevEnableMediaFileProbe bool
|
DevEnableMediaFileProbe bool
|
||||||
|
DevMatchEstimatedContentLength bool
|
||||||
|
DevAPIv1 bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type scannerOptions struct {
|
type scannerOptions struct {
|
||||||
|
|
@ -175,6 +179,7 @@ type scannerOptions struct {
|
||||||
GroupAlbumReleases bool // Deprecated: Use PID.Album instead
|
GroupAlbumReleases bool // Deprecated: Use PID.Album instead
|
||||||
FollowSymlinks bool // Whether to follow symlinks when scanning directories
|
FollowSymlinks bool // Whether to follow symlinks when scanning directories
|
||||||
IgnoreDotFolders bool // Whether to ignore folders whose name starts with a dot when scanning
|
IgnoreDotFolders bool // Whether to ignore folders whose name starts with a dot when scanning
|
||||||
|
RespectNoMedia bool // Whether to skip folders (and their subfolders) containing a .nomedia file
|
||||||
PurgeMissing string // Values: "never", "always", "full"
|
PurgeMissing string // Values: "never", "always", "full"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -205,10 +210,11 @@ type TagConf struct {
|
||||||
|
|
||||||
type lastfmOptions struct {
|
type lastfmOptions struct {
|
||||||
Enabled bool
|
Enabled bool
|
||||||
ApiKey string //nolint:gosec
|
ApiKey string
|
||||||
Secret string //nolint:gosec
|
Secret string
|
||||||
Language string
|
Language string
|
||||||
ScrobbleFirstArtistOnly bool
|
ScrobbleFirstArtistOnly bool
|
||||||
|
MinScrobbleDuration time.Duration
|
||||||
|
|
||||||
// Computed values
|
// Computed values
|
||||||
Languages []string `conf:"-"` // Computed from Language, split by comma
|
Languages []string `conf:"-"` // Computed from Language, split by comma
|
||||||
|
|
@ -235,6 +241,8 @@ type jellyfinOptions struct {
|
||||||
// ExposedPublicUsers is a comma-separated list of usernames to advertise on the unauthenticated
|
// ExposedPublicUsers is a comma-separated list of usernames to advertise on the unauthenticated
|
||||||
// GET /Users/Public, so Jellyfin clients can show a login user-picker. Empty exposes no users.
|
// GET /Users/Public, so Jellyfin clients can show a login user-picker. Empty exposes no users.
|
||||||
ExposedPublicUsers string
|
ExposedPublicUsers string
|
||||||
|
AutoDiscovery bool
|
||||||
|
QuickConnect bool
|
||||||
// MaxConcurrentStreams bounds how many collection responses can stream at once. Each holds a DB
|
// MaxConcurrentStreams bounds how many collection responses can stream at once. Each holds a DB
|
||||||
// cursor — and its pooled connection — for the whole client-paced response, so without a bound
|
// cursor — and its pooled connection — for the whole client-paced response, so without a bound
|
||||||
// enough slow clients would take the entire pool and stall the scanner, scrobbles and the UI.
|
// enough slow clients would take the entire pool and stall the scanner, scrobbles and the UI.
|
||||||
|
|
@ -248,7 +256,7 @@ type httpHeaderOptions struct {
|
||||||
type prometheusOptions struct {
|
type prometheusOptions struct {
|
||||||
Enabled bool
|
Enabled bool
|
||||||
MetricsPath string
|
MetricsPath string
|
||||||
Password string //nolint:gosec
|
Password string
|
||||||
}
|
}
|
||||||
|
|
||||||
type AudioDeviceDefinition []string
|
type AudioDeviceDefinition []string
|
||||||
|
|
@ -317,30 +325,11 @@ var currentGOOS = func() string {
|
||||||
|
|
||||||
// TLSEnabled reports whether the server serves HTTPS. Both halves are required,
|
// TLSEnabled reports whether the server serves HTTPS. Both halves are required,
|
||||||
// so callers cannot infer it from the certificate alone.
|
// so callers cannot infer it from the certificate alone.
|
||||||
func (c *configOptions) TLSEnabled() bool {
|
func (c Options) TLSEnabled() bool {
|
||||||
return c.TLSCert != "" && c.TLSKey != ""
|
return c.TLSCert != "" && c.TLSKey != ""
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var hooks []func()
|
||||||
Server = &configOptions{}
|
|
||||||
hooks []func()
|
|
||||||
)
|
|
||||||
|
|
||||||
// SnapshotConfig returns a function that restores Server to its current state.
|
|
||||||
// Uses JSON round-tripping so Dir fields get fresh sync.Once values.
|
|
||||||
func SnapshotConfig() func() {
|
|
||||||
snapshot, err := json.Marshal(Server)
|
|
||||||
if err != nil {
|
|
||||||
panic(fmt.Sprintf("SnapshotConfig: marshal failed: %v", err))
|
|
||||||
}
|
|
||||||
return func() {
|
|
||||||
var restored configOptions
|
|
||||||
if err := json.Unmarshal(snapshot, &restored); err != nil {
|
|
||||||
panic(fmt.Sprintf("SnapshotConfig: unmarshal failed: %v", err))
|
|
||||||
}
|
|
||||||
Server = &restored
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func LoadFromFile(confFile string) {
|
func LoadFromFile(confFile string) {
|
||||||
viper.SetConfigFile(confFile)
|
viper.SetConfigFile(confFile)
|
||||||
|
|
@ -369,7 +358,8 @@ func Load(noConfigDump bool) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
err := viper.Unmarshal(&Server, viper.DecodeHook(
|
s := clone(current.Load())
|
||||||
|
err := viper.Unmarshal(s, viper.DecodeHook(
|
||||||
mapstructure.ComposeDecodeHookFunc(
|
mapstructure.ComposeDecodeHookFunc(
|
||||||
mapstructure.TextUnmarshallerHookFunc(),
|
mapstructure.TextUnmarshallerHookFunc(),
|
||||||
mapstructure.StringToTimeDurationHookFunc(),
|
mapstructure.StringToTimeDurationHookFunc(),
|
||||||
|
|
@ -381,35 +371,35 @@ func Load(noConfigDump bool) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate non-root user early, before any filesystem operations
|
// Validate non-root user early, before any filesystem operations
|
||||||
if err := validateEnforceNonRootUser(); err != nil {
|
if err := s.validateEnforceNonRootUser(); err != nil {
|
||||||
logFatal(err)
|
logFatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if Server.CacheFolder.String() == "" {
|
if s.CacheFolder.String() == "" {
|
||||||
Server.CacheFolder = NewDir(filepath.Join(Server.DataFolder.String(), "cache"))
|
s.CacheFolder = NewDir(filepath.Join(s.DataFolder.String(), "cache"))
|
||||||
}
|
}
|
||||||
|
|
||||||
if Server.Plugins.Enabled {
|
if s.Plugins.Enabled {
|
||||||
if Server.Plugins.Folder.String() == "" {
|
if s.Plugins.Folder.String() == "" {
|
||||||
Server.Plugins.Folder = NewDirWithPerm(filepath.Join(Server.DataFolder.String(), "plugins"), 0700)
|
s.Plugins.Folder = NewDirWithPerm(filepath.Join(s.DataFolder.String(), "plugins"), 0700)
|
||||||
} else {
|
} else {
|
||||||
Server.Plugins.Folder = NewDirWithPerm(Server.Plugins.Folder.String(), 0700)
|
s.Plugins.Folder = NewDirWithPerm(s.Plugins.Folder.String(), 0700)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Server.ConfigFile = viper.GetViper().ConfigFileUsed()
|
s.ConfigFile = viper.GetViper().ConfigFileUsed()
|
||||||
if Server.DbPath == "" {
|
if s.DbPath == "" {
|
||||||
Server.DbPath = filepath.Join(Server.DataFolder.String(), consts.DefaultDbPath)
|
s.DbPath = filepath.Join(s.DataFolder.String(), consts.DefaultDbPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
out := os.Stderr
|
out := os.Stderr
|
||||||
if Server.LogFile != "" {
|
if s.LogFile != "" {
|
||||||
if mkErr := os.MkdirAll(filepath.Dir(Server.LogFile), os.ModePerm); mkErr != nil {
|
if mkErr := os.MkdirAll(filepath.Dir(s.LogFile), os.ModePerm); mkErr != nil {
|
||||||
logFatal(fmt.Sprintf("Error creating log file directory: %s", mkErr.Error()))
|
logFatal("Error creating log file directory: " + mkErr.Error())
|
||||||
}
|
}
|
||||||
out, err = os.OpenFile(Server.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
out, err = os.OpenFile(s.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logFatal(fmt.Sprintf("Error opening log file %s: %s", Server.LogFile, err.Error()))
|
logFatal(fmt.Sprintf("Error opening log file %s: %s", s.LogFile, err.Error()))
|
||||||
}
|
}
|
||||||
log.SetOutput(out)
|
log.SetOutput(out)
|
||||||
} else if os.Getenv("ND_SYSTEMD_PRIORITY_LOGGING") != "" && os.Getenv("JOURNAL_STREAM") != "" {
|
} else if os.Getenv("ND_SYSTEMD_PRIORITY_LOGGING") != "" && os.Getenv("JOURNAL_STREAM") != "" {
|
||||||
|
|
@ -420,24 +410,26 @@ func Load(noConfigDump bool) {
|
||||||
log.EnableJournalFormat()
|
log.EnableJournalFormat()
|
||||||
}
|
}
|
||||||
|
|
||||||
log.SetLevelString(Server.LogLevel)
|
log.SetLevelString(s.LogLevel)
|
||||||
log.SetLogLevels(Server.DevLogLevels)
|
log.SetLogLevels(s.DevLogLevels)
|
||||||
log.SetLogSourceLine(Server.DevLogSourceLine)
|
log.SetLogSourceLine(s.DevLogSourceLine)
|
||||||
log.SetRedacting(Server.EnableLogRedacting)
|
log.SetRedacting(s.EnableLogRedacting)
|
||||||
|
|
||||||
durationNonNegativeOrDefault(&Server.SessionTimeout, consts.DefaultSessionTimeout)
|
durationNonNegativeOrDefault(&s.SessionTimeout, consts.DefaultSessionTimeout)
|
||||||
durationNonNegativeOrDefault(&Server.SmartPlaylistRefreshDelay, consts.DefaultSmartRefresh)
|
durationNonNegativeOrDefault(&s.SmartPlaylistRefreshDelay, consts.DefaultSmartRefresh)
|
||||||
durationNonNegativeOrDefault(&Server.DefaultShareExpiration, consts.DefaultShareExpiration)
|
durationNonNegativeOrDefault(&s.DefaultShareExpiration, consts.DefaultShareExpiration)
|
||||||
durationNonNegativeOrDefault(&Server.UIPlaybackReportInterval, consts.DefaultUIPlaybackReportInterval)
|
durationNonNegativeOrDefault(&s.UIPlaybackReportInterval, consts.DefaultUIPlaybackReportInterval)
|
||||||
durationNonNegativeOrDefault(&Server.AuthWindowLength, consts.DefaultAuthWindowLength)
|
durationNonNegativeOrDefault(&s.AuthWindowLength, consts.DefaultAuthWindowLength)
|
||||||
durationNonNegativeOrDefault(&Server.Scanner.WatcherWait, consts.DefaultWatcherWait)
|
durationNonNegativeOrDefault(&s.Scanner.WatcherWait, consts.DefaultWatcherWait)
|
||||||
|
|
||||||
durationNonNegativeOrDefault(&Server.DevActivityPanelUpdateRate, consts.DefaultActivityPanelUpdateRate)
|
durationNonNegativeOrDefault(&s.DevActivityPanelUpdateRate, consts.DefaultActivityPanelUpdateRate)
|
||||||
durationNonNegativeOrDefault(&Server.DevArtworkThrottleBacklogTimeout, consts.RequestThrottleBacklogTimeout)
|
durationNonNegativeOrDefault(&s.DevArtworkThrottleBacklogTimeout, consts.RequestThrottleBacklogTimeout)
|
||||||
durationNonNegativeOrDefault(&Server.DevArtistInfoTimeToLive, consts.ArtistInfoTimeToLive)
|
durationNonNegativeOrDefault(&s.DevArtistInfoTimeToLive, consts.ArtistInfoTimeToLive)
|
||||||
durationNonNegativeOrDefault(&Server.DevAlbumInfoTimeToLive, consts.AlbumInfoTimeToLive)
|
durationNonNegativeOrDefault(&s.DevAlbumInfoTimeToLive, consts.AlbumInfoTimeToLive)
|
||||||
durationNonNegativeOrDefault(&Server.DevInsightsInitialDelay, consts.InsightsInitialDelay)
|
durationNonNegativeOrDefault(&s.DevInsightsInitialDelay, consts.InsightsInitialDelay)
|
||||||
durationNonNegativeOrDefault(&Server.DevPluginCompilationTimeout, consts.DefaultPluginCompilationTimeout)
|
durationNonNegativeOrDefault(&s.DevPluginCompilationTimeout, consts.DefaultPluginCompilationTimeout)
|
||||||
|
|
||||||
|
durationNonNegativeOrDefault(&s.LastFM.MinScrobbleDuration, consts.DefaultMinScrobbleDuration)
|
||||||
|
|
||||||
// Log deprecated, removed and unknown options
|
// Log deprecated, removed and unknown options
|
||||||
for _, o := range deprecatedOptions {
|
for _, o := range deprecatedOptions {
|
||||||
|
|
@ -447,35 +439,35 @@ func Load(noConfigDump bool) {
|
||||||
logUnknownOptions()
|
logUnknownOptions()
|
||||||
|
|
||||||
err = run.Sequentially(
|
err = run.Sequentially(
|
||||||
validateScanSchedule,
|
s.validateScanSchedule,
|
||||||
validateBackupSchedule,
|
s.validateBackupSchedule,
|
||||||
validatePlaylistsPath,
|
s.validatePlaylistsPath,
|
||||||
validatePurgeMissingOption,
|
s.validatePurgeMissingOption,
|
||||||
validateByteSize("MaxImageUploadSize", Server.MaxImageUploadSize),
|
validateByteSize("MaxImageUploadSize", s.MaxImageUploadSize),
|
||||||
validateByteSize("MaxImageSize", Server.MaxImageSize),
|
validateByteSize("MaxImageSize", s.MaxImageSize),
|
||||||
validateURL("ExtAuth.LogoutURL", Server.ExtAuth.LogoutURL),
|
validateURL("ExtAuth.LogoutURL", s.ExtAuth.LogoutURL),
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logFatal(err)
|
logFatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
Server.Search.Backend = normalizeSearchBackend(Server.Search.Backend)
|
s.Search.Backend = normalizeSearchBackend(s.Search.Backend)
|
||||||
|
|
||||||
if Server.BaseURL != "" {
|
if s.BaseURL != "" {
|
||||||
u, err := url.Parse(Server.BaseURL)
|
u, err := url.Parse(s.BaseURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logFatal("Invalid BaseURL:", err)
|
logFatal("Invalid BaseURL:", err)
|
||||||
}
|
}
|
||||||
Server.BasePath = u.Path
|
s.BasePath = u.Path
|
||||||
u.Path = ""
|
u.Path = ""
|
||||||
u.RawQuery = ""
|
u.RawQuery = ""
|
||||||
Server.BaseHost = u.Host
|
s.BaseHost = u.Host
|
||||||
Server.BaseScheme = u.Scheme
|
s.BaseScheme = u.Scheme
|
||||||
}
|
}
|
||||||
|
|
||||||
// Log configuration source
|
// Log configuration source
|
||||||
if Server.ConfigFile != "" {
|
if s.ConfigFile != "" {
|
||||||
log.Info("Loaded configuration", "file", Server.ConfigFile)
|
log.Info("Loaded configuration", "file", s.ConfigFile)
|
||||||
} else if hasNDEnvVars() {
|
} else if hasNDEnvVars() {
|
||||||
log.Info("No configuration file found. Loaded configuration only from environment variables")
|
log.Info("No configuration file found. Loaded configuration only from environment variables")
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -484,42 +476,49 @@ func Load(noConfigDump bool) {
|
||||||
|
|
||||||
// Print current configuration if log level is Debug
|
// Print current configuration if log level is Debug
|
||||||
if log.IsGreaterOrEqualTo(log.LevelDebug) && !noConfigDump {
|
if log.IsGreaterOrEqualTo(log.LevelDebug) && !noConfigDump {
|
||||||
prettyConf := pretty.Sprintf("Configuration: %# v", Server)
|
prettyConf := pretty.Sprintf("Configuration: %# v", s)
|
||||||
if Server.EnableLogRedacting {
|
if s.EnableLogRedacting {
|
||||||
prettyConf = log.Redact(prettyConf)
|
prettyConf = log.Redact(prettyConf)
|
||||||
}
|
}
|
||||||
_, _ = fmt.Fprintln(out, prettyConf)
|
_, _ = fmt.Fprintln(out, prettyConf)
|
||||||
}
|
}
|
||||||
|
|
||||||
if !Server.EnableExternalServices {
|
if !s.EnableExternalServices {
|
||||||
disableExternalServices()
|
s.disableExternalServices()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make sure we don't have empty PIDs
|
// Make sure we don't have empty PIDs
|
||||||
Server.PID.Album = cmp.Or(Server.PID.Album, consts.DefaultAlbumPID)
|
s.PID.Album = cmp.Or(s.PID.Album, consts.DefaultAlbumPID)
|
||||||
Server.PID.Track = cmp.Or(Server.PID.Track, consts.DefaultTrackPID)
|
s.PID.Track = cmp.Or(s.PID.Track, consts.DefaultTrackPID)
|
||||||
|
|
||||||
// Parse LastFM.Language into Languages slice (comma-separated, with fallback to DefaultInfoLanguage)
|
// Parse LastFM.Language into Languages slice (comma-separated, with fallback to DefaultInfoLanguage)
|
||||||
Server.LastFM.Languages = parseLanguages(Server.LastFM.Language)
|
s.LastFM.Languages = parseLanguages(s.LastFM.Language)
|
||||||
|
|
||||||
// Parse Deezer.Language into Languages slice (comma-separated, with fallback to DefaultInfoLanguage)
|
// Parse Deezer.Language into Languages slice (comma-separated, with fallback to DefaultInfoLanguage)
|
||||||
Server.Deezer.Languages = parseLanguages(Server.Deezer.Language)
|
s.Deezer.Languages = parseLanguages(s.Deezer.Language)
|
||||||
|
|
||||||
// Validate other options
|
// Validate other options
|
||||||
if Server.UICoverArtSize < 200 || Server.UICoverArtSize > 1200 {
|
if s.UICoverArtSize < 200 || s.UICoverArtSize > 1200 {
|
||||||
newValue := max(200, min(1200, Server.UICoverArtSize))
|
newValue := max(200, min(1200, s.UICoverArtSize))
|
||||||
log.Warn("UICoverArtSize must be between 200 and 1200, clamping", "value", Server.UICoverArtSize, "newValue", newValue)
|
log.Warn("UICoverArtSize must be between 200 and 1200, clamping", "value", s.UICoverArtSize, "newValue", newValue)
|
||||||
Server.UICoverArtSize = newValue
|
s.UICoverArtSize = newValue
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.Scanner.Extractor != consts.DefaultScannerExtractor {
|
||||||
|
log.Warn("Invalid Scanner.Extractor, using default", "value", s.Scanner.Extractor, "default", consts.DefaultScannerExtractor)
|
||||||
|
s.Scanner.Extractor = consts.DefaultScannerExtractor
|
||||||
}
|
}
|
||||||
|
|
||||||
// Floor MaxImageSize at MaxImageUploadSize so accepted uploads can always be read back.
|
// Floor MaxImageSize at MaxImageUploadSize so accepted uploads can always be read back.
|
||||||
imgSize, _ := humanize.ParseBytes(Server.MaxImageSize)
|
imgSize, _ := humanize.ParseBytes(s.MaxImageSize)
|
||||||
uploadSize, _ := humanize.ParseBytes(Server.MaxImageUploadSize)
|
uploadSize, _ := humanize.ParseBytes(s.MaxImageUploadSize)
|
||||||
if imgSize < uploadSize {
|
if imgSize < uploadSize {
|
||||||
log.Warn("MaxImageSize must be at least MaxImageUploadSize, raising", "value", Server.MaxImageSize, "newValue", Server.MaxImageUploadSize)
|
log.Warn("MaxImageSize must be at least MaxImageUploadSize, raising", "value", s.MaxImageSize, "newValue", s.MaxImageUploadSize)
|
||||||
Server.MaxImageSize = Server.MaxImageUploadSize
|
s.MaxImageSize = s.MaxImageUploadSize
|
||||||
}
|
}
|
||||||
|
|
||||||
|
current.Store(s)
|
||||||
|
|
||||||
// Call init hooks
|
// Call init hooks
|
||||||
for _, hook := range hooks {
|
for _, hook := range hooks {
|
||||||
hook()
|
hook()
|
||||||
|
|
@ -732,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,
|
||||||
|
|
@ -760,7 +759,7 @@ var configKeys = sync.OnceValues(func() (map[string]string, []string) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
collect(reflect.TypeFor[configOptions](), "")
|
collect(reflect.TypeFor[Options](), "")
|
||||||
|
|
||||||
for _, o := range deprecatedOptions {
|
for _, o := range deprecatedOptions {
|
||||||
keys[strings.ToLower(o.name)] = o.name
|
keys[strings.ToLower(o.name)] = o.name
|
||||||
|
|
@ -795,21 +794,21 @@ func parseIniFileConfiguration() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func disableExternalServices() {
|
func (s *Options) disableExternalServices() {
|
||||||
log.Info("All external integrations are DISABLED!")
|
log.Info("All external integrations are DISABLED!")
|
||||||
Server.EnableInsightsCollector = false
|
s.EnableInsightsCollector = false
|
||||||
Server.EnableM3UExternalAlbumArt = false
|
s.EnableM3UExternalAlbumArt = false
|
||||||
Server.LastFM.Enabled = false
|
s.LastFM.Enabled = false
|
||||||
Server.Deezer.Enabled = false
|
s.Deezer.Enabled = false
|
||||||
Server.ListenBrainz.Enabled = false
|
s.ListenBrainz.Enabled = false
|
||||||
Server.Agents = ""
|
s.Agents = ""
|
||||||
if Server.UILoginBackgroundURL == consts.DefaultUILoginBackgroundURL {
|
if s.UILoginBackgroundURL == consts.DefaultUILoginBackgroundURL {
|
||||||
Server.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURLOffline
|
s.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURLOffline
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func validatePlaylistsPath() error {
|
func (s *Options) validatePlaylistsPath() error {
|
||||||
for path := range strings.SplitSeq(Server.PlaylistsPath, string(filepath.ListSeparator)) {
|
for path := range strings.SplitSeq(s.PlaylistsPath, string(filepath.ListSeparator)) {
|
||||||
_, err := doublestar.Match(path, "")
|
_, err := doublestar.Match(path, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("invalid PlaylistsPath %q: %w", path, err)
|
return fmt.Errorf("invalid PlaylistsPath %q: %w", path, err)
|
||||||
|
|
@ -834,12 +833,12 @@ func parseLanguages(lang string) []string {
|
||||||
return languages
|
return languages
|
||||||
}
|
}
|
||||||
|
|
||||||
func validatePurgeMissingOption() error {
|
func (s *Options) validatePurgeMissingOption() error {
|
||||||
allowedValues := []string{consts.PurgeMissingNever, consts.PurgeMissingAlways, consts.PurgeMissingFull}
|
allowedValues := []string{consts.PurgeMissingNever, consts.PurgeMissingAlways, consts.PurgeMissingFull}
|
||||||
valid := slices.Contains(allowedValues, Server.Scanner.PurgeMissing)
|
valid := slices.Contains(allowedValues, s.Scanner.PurgeMissing)
|
||||||
if !valid {
|
if !valid {
|
||||||
err := fmt.Errorf("invalid Scanner.PurgeMissing value: '%s'. Must be one of: %v", Server.Scanner.PurgeMissing, allowedValues)
|
err := fmt.Errorf("invalid Scanner.PurgeMissing value: '%s'. Must be one of: %v", s.Scanner.PurgeMissing, allowedValues)
|
||||||
Server.Scanner.PurgeMissing = consts.PurgeMissingNever
|
s.Scanner.PurgeMissing = consts.PurgeMissingNever
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|
@ -861,35 +860,35 @@ func validateByteSize(name, value string) func() error {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func validateEnforceNonRootUser() error {
|
func (s *Options) validateEnforceNonRootUser() error {
|
||||||
if !Server.EnforceNonRootUser || currentGOOS() == "windows" {
|
if !s.EnforceNonRootUser || currentGOOS() == "windows" {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if getEUID() == 0 {
|
if getEUID() == 0 {
|
||||||
return fmt.Errorf("EnforceNonRootUser is enabled but Navidrome is running as root")
|
return errors.New("EnforceNonRootUser is enabled but Navidrome is running as root")
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func validateScanSchedule() error {
|
func (s *Options) validateScanSchedule() error {
|
||||||
if Server.Scanner.Schedule == "0" || Server.Scanner.Schedule == "" {
|
if s.Scanner.Schedule == "0" || s.Scanner.Schedule == "" {
|
||||||
Server.Scanner.Schedule = ""
|
s.Scanner.Schedule = ""
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
var err error
|
var err error
|
||||||
Server.Scanner.Schedule, err = validateSchedule(Server.Scanner.Schedule, "Scanner.Schedule")
|
s.Scanner.Schedule, err = validateSchedule(s.Scanner.Schedule, "Scanner.Schedule")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func validateBackupSchedule() error {
|
func (s *Options) validateBackupSchedule() error {
|
||||||
if Server.Backup.Path.String() == "" || Server.Backup.Schedule == "" || Server.Backup.Count == 0 {
|
if s.Backup.Path.String() == "" || s.Backup.Schedule == "" || s.Backup.Count == 0 {
|
||||||
Server.Backup.Schedule = ""
|
s.Backup.Schedule = ""
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
var err error
|
var err error
|
||||||
Server.Backup.Schedule, err = validateSchedule(Server.Backup.Schedule, "Backup.Schedule")
|
s.Backup.Schedule, err = validateSchedule(s.Backup.Schedule, "Backup.Schedule")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1023,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)
|
||||||
|
|
@ -1062,6 +1062,7 @@ func setViperDefaults() {
|
||||||
viper.SetDefault("scanner.groupalbumreleases", false)
|
viper.SetDefault("scanner.groupalbumreleases", false)
|
||||||
viper.SetDefault("scanner.followsymlinks", true)
|
viper.SetDefault("scanner.followsymlinks", true)
|
||||||
viper.SetDefault("scanner.ignoredotfolders", true)
|
viper.SetDefault("scanner.ignoredotfolders", true)
|
||||||
|
viper.SetDefault("scanner.respectnomedia", false)
|
||||||
viper.SetDefault("scanner.purgemissing", consts.PurgeMissingNever)
|
viper.SetDefault("scanner.purgemissing", consts.PurgeMissingNever)
|
||||||
viper.SetDefault("subsonic.appendsubtitle", true)
|
viper.SetDefault("subsonic.appendsubtitle", true)
|
||||||
viper.SetDefault("subsonic.appendalbumversion", true)
|
viper.SetDefault("subsonic.appendalbumversion", true)
|
||||||
|
|
@ -1079,6 +1080,7 @@ func setViperDefaults() {
|
||||||
viper.SetDefault("lastfm.apikey", "")
|
viper.SetDefault("lastfm.apikey", "")
|
||||||
viper.SetDefault("lastfm.secret", "")
|
viper.SetDefault("lastfm.secret", "")
|
||||||
viper.SetDefault("lastfm.scrobblefirstartistonly", false)
|
viper.SetDefault("lastfm.scrobblefirstartistonly", false)
|
||||||
|
viper.SetDefault("lastfm.minscrobbleduration", consts.DefaultMinScrobbleDuration)
|
||||||
viper.SetDefault("deezer.enabled", true)
|
viper.SetDefault("deezer.enabled", true)
|
||||||
viper.SetDefault("deezer.language", consts.DefaultInfoLanguage)
|
viper.SetDefault("deezer.language", consts.DefaultInfoLanguage)
|
||||||
viper.SetDefault("listenbrainz.enabled", true)
|
viper.SetDefault("listenbrainz.enabled", true)
|
||||||
|
|
@ -1087,6 +1089,8 @@ func setViperDefaults() {
|
||||||
viper.SetDefault("listenbrainz.trackalgorithm", consts.DefaultListenBrainzTrackAlgorithm)
|
viper.SetDefault("listenbrainz.trackalgorithm", consts.DefaultListenBrainzTrackAlgorithm)
|
||||||
viper.SetDefault("jellyfin.enabled", false)
|
viper.SetDefault("jellyfin.enabled", false)
|
||||||
viper.SetDefault("jellyfin.servername", "")
|
viper.SetDefault("jellyfin.servername", "")
|
||||||
|
viper.SetDefault("jellyfin.autodiscovery", false)
|
||||||
|
viper.SetDefault("jellyfin.quickconnect", true)
|
||||||
viper.SetDefault("enablescrobblehistory", true)
|
viper.SetDefault("enablescrobblehistory", true)
|
||||||
viper.SetDefault("httpheaders.frameoptions", "DENY")
|
viper.SetDefault("httpheaders.frameoptions", "DENY")
|
||||||
viper.SetDefault("backup.path", "")
|
viper.SetDefault("backup.path", "")
|
||||||
|
|
@ -1115,7 +1119,9 @@ func setViperDefaults() {
|
||||||
viper.SetDefault("devshowartistpage", true)
|
viper.SetDefault("devshowartistpage", true)
|
||||||
viper.SetDefault("devuishowconfig", true)
|
viper.SetDefault("devuishowconfig", true)
|
||||||
viper.SetDefault("devneweventstream", true)
|
viper.SetDefault("devneweventstream", true)
|
||||||
|
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))
|
||||||
|
|
@ -1141,6 +1147,7 @@ func setViperDefaults() {
|
||||||
viper.SetDefault("devexternalartistfetchmultiplier", 1.5)
|
viper.SetDefault("devexternalartistfetchmultiplier", 1.5)
|
||||||
viper.SetDefault("devpreserveunicodeinexternalcalls", false)
|
viper.SetDefault("devpreserveunicodeinexternalcalls", false)
|
||||||
viper.SetDefault("devenablemediafileprobe", true)
|
viper.SetDefault("devenablemediafileprobe", true)
|
||||||
|
viper.SetDefault("devmatchestimatedcontentlength", true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
|
@ -22,6 +23,8 @@ func TestConfiguration(t *testing.T) {
|
||||||
RunSpecs(t, "Configuration Suite")
|
RunSpecs(t, "Configuration Suite")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ = configtest.RestoreAfterEachSpec()
|
||||||
|
|
||||||
var _ = Describe("Configuration", func() {
|
var _ = Describe("Configuration", func() {
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
// Reset viper configuration
|
// Reset viper configuration
|
||||||
|
|
@ -31,10 +34,7 @@ var _ = Describe("Configuration", func() {
|
||||||
viper.SetDefault("loglevel", "error")
|
viper.SetDefault("loglevel", "error")
|
||||||
conf.ResetConf()
|
conf.ResetConf()
|
||||||
|
|
||||||
// Panic instead of exiting on fatal errors to allow testing error conditions
|
DeferCleanup(conf.PanicOnLogFatal())
|
||||||
DeferCleanup(conf.SetLogFatal(func(args ...any) {
|
|
||||||
panic(fmt.Sprint(args...))
|
|
||||||
}))
|
|
||||||
})
|
})
|
||||||
|
|
||||||
Describe("ParseLanguages", func() {
|
Describe("ParseLanguages", func() {
|
||||||
|
|
@ -66,13 +66,13 @@ var _ = Describe("Configuration", func() {
|
||||||
Describe("scheduled DB analysis", func() {
|
Describe("scheduled DB analysis", func() {
|
||||||
It("is enabled by default", func() {
|
It("is enabled by default", func() {
|
||||||
conf.Load(true)
|
conf.Load(true)
|
||||||
Expect(conf.Server.EnableScheduledDBAnalyze).To(BeTrue())
|
Expect(conf.Server().EnableScheduledDBAnalyze).To(BeTrue())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("can be disabled", func() {
|
It("can be disabled", func() {
|
||||||
viper.Set("enablescheduleddbanalyze", false)
|
viper.Set("enablescheduleddbanalyze", false)
|
||||||
conf.Load(true)
|
conf.Load(true)
|
||||||
Expect(conf.Server.EnableScheduledDBAnalyze).To(BeFalse())
|
Expect(conf.Server().EnableScheduledDBAnalyze).To(BeFalse())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -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() {
|
||||||
|
|
@ -157,9 +157,9 @@ var _ = Describe("Configuration", func() {
|
||||||
conf.InitConfig(filename, false)
|
conf.InitConfig(filename, false)
|
||||||
conf.Load(true)
|
conf.Load(true)
|
||||||
|
|
||||||
Expect(conf.Server.Address).To(Equal("127.0.0.1"))
|
Expect(conf.Server().Address).To(Equal("127.0.0.1"))
|
||||||
Expect(conf.Server.Port).To(Equal(4531))
|
Expect(conf.Server().Port).To(Equal(4531))
|
||||||
Expect(conf.Server.Scanner.Schedule).To(Equal("@every 1h"))
|
Expect(conf.Server().Scanner.Schedule).To(Equal("@every 1h"))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("exits with fatal error when both ND_ and canonical key exist", func() {
|
It("exits with fatal error when both ND_ and canonical key exist", func() {
|
||||||
|
|
@ -179,7 +179,7 @@ var _ = Describe("Configuration", func() {
|
||||||
conf.Load(true)
|
conf.Load(true)
|
||||||
|
|
||||||
// Verify normal config loading still works
|
// Verify normal config loading still works
|
||||||
Expect(conf.Server.MusicFolder).To(Equal("/toml/music"))
|
Expect(conf.Server().MusicFolder).To(Equal("/toml/music"))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -253,14 +253,14 @@ var _ = Describe("Configuration", func() {
|
||||||
conf.Load(true)
|
conf.Load(true)
|
||||||
|
|
||||||
Expect(conf.UnknownConfigKeys()).To(ConsistOf("ND_TOTALLY_BOGUS_OPTION"))
|
Expect(conf.UnknownConfigKeys()).To(ConsistOf("ND_TOTALLY_BOGUS_OPTION"))
|
||||||
Expect(conf.Server.Scanner.Schedule).To(Equal("@every 1h"))
|
Expect(conf.Server().Scanner.Schedule).To(Equal("@every 1h"))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("migrates every deprecated option that has a replacement", func() {
|
It("migrates every deprecated option that has a replacement", func() {
|
||||||
conf.InitConfig(filepath.Join("testdata", "cfg_deprecated_search.toml"), false)
|
conf.InitConfig(filepath.Join("testdata", "cfg_deprecated_search.toml"), false)
|
||||||
conf.Load(true)
|
conf.Load(true)
|
||||||
|
|
||||||
Expect(conf.Server.Search.FullString).To(BeTrue())
|
Expect(conf.Server().Search.FullString).To(BeTrue())
|
||||||
Expect(conf.UnknownConfigKeys()).To(BeEmpty())
|
Expect(conf.UnknownConfigKeys()).To(BeEmpty())
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -295,7 +295,7 @@ var _ = Describe("Configuration", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("keeps an explicit replacement over the deprecated value", func() {
|
It("keeps an explicit replacement over the deprecated value", func() {
|
||||||
Expect(conf.Server.Search.FullString).To(BeFalse())
|
Expect(conf.Server().Search.FullString).To(BeFalse())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
@ -329,6 +329,21 @@ var _ = Describe("Configuration", func() {
|
||||||
}).To(PanicWith(ContainSubstring("Error creating log file directory")))
|
}).To(PanicWith(ContainSubstring("Error creating log file directory")))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
It("creates the log file readable only by the owner", func() {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
Skip("file modes are not enforced on Windows")
|
||||||
|
}
|
||||||
|
logFile := filepath.Join(GinkgoT().TempDir(), "navidrome.log")
|
||||||
|
viper.SetDefault("datafolder", GinkgoT().TempDir())
|
||||||
|
viper.SetDefault("logfile", logFile)
|
||||||
|
DeferCleanup(log.SetOutput, os.Stderr)
|
||||||
|
conf.Load(true)
|
||||||
|
|
||||||
|
info, err := os.Stat(logFile)
|
||||||
|
Expect(err).ToNot(HaveOccurred())
|
||||||
|
Expect(info.Mode().Perm()).To(Equal(os.FileMode(0600)))
|
||||||
|
})
|
||||||
|
|
||||||
It("is called when BaseURL is invalid", func() {
|
It("is called when BaseURL is invalid", func() {
|
||||||
viper.SetDefault("datafolder", GinkgoT().TempDir())
|
viper.SetDefault("datafolder", GinkgoT().TempDir())
|
||||||
viper.SetDefault("baseurl", "://invalid")
|
viper.SetDefault("baseurl", "://invalid")
|
||||||
|
|
@ -376,13 +391,59 @@ var _ = Describe("Configuration", func() {
|
||||||
viper.SetDefault("maximagesize", "5MB")
|
viper.SetDefault("maximagesize", "5MB")
|
||||||
viper.SetDefault("maximageuploadsize", "50MB")
|
viper.SetDefault("maximageuploadsize", "50MB")
|
||||||
conf.Load(true)
|
conf.Load(true)
|
||||||
Expect(conf.Server.MaxImageSize).To(Equal("50MB"))
|
Expect(conf.Server().MaxImageSize).To(Equal("50MB"))
|
||||||
})
|
})
|
||||||
|
|
||||||
It("keeps a larger MaxImageSize unchanged", func() {
|
It("keeps a larger MaxImageSize unchanged", func() {
|
||||||
viper.SetDefault("maximagesize", "30MB")
|
viper.SetDefault("maximagesize", "30MB")
|
||||||
conf.Load(true)
|
conf.Load(true)
|
||||||
Expect(conf.Server.MaxImageSize).To(Equal("30MB"))
|
Expect(conf.Server().MaxImageSize).To(Equal("30MB"))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
Describe("MinScrobbleDuration", func() {
|
||||||
|
It("defaults to 30 seconds", func() {
|
||||||
|
conf.Load(true)
|
||||||
|
Expect(conf.Server().LastFM.MinScrobbleDuration).To(Equal(consts.DefaultMinScrobbleDuration))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("sets negative values to default", func() {
|
||||||
|
viper.SetDefault("lastfm.minscrobbleduration", "-10s")
|
||||||
|
conf.Load(true)
|
||||||
|
Expect(conf.Server().LastFM.MinScrobbleDuration).To(Equal(consts.DefaultMinScrobbleDuration))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("disables with zero value", func() {
|
||||||
|
viper.SetDefault("lastfm.minscrobbleduration", "0s")
|
||||||
|
conf.Load(true)
|
||||||
|
Expect(conf.Server().LastFM.MinScrobbleDuration).To(Equal(time.Duration(0)))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("preserves positive values", func() {
|
||||||
|
viper.SetDefault("lastfm.minscrobbleduration", "45s")
|
||||||
|
conf.Load(true)
|
||||||
|
Expect(conf.Server().LastFM.MinScrobbleDuration).To(Equal(45 * time.Second))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
Describe("Scanner.Extractor", func() {
|
||||||
|
BeforeEach(func() {
|
||||||
|
viper.Reset()
|
||||||
|
conf.SetViperDefaults()
|
||||||
|
viper.SetDefault("datafolder", GinkgoT().TempDir())
|
||||||
|
viper.SetDefault("loglevel", "error")
|
||||||
|
conf.ResetConf()
|
||||||
|
})
|
||||||
|
|
||||||
|
It("falls back to taglib for an unknown extractor", func() {
|
||||||
|
viper.SetDefault("scanner.extractor", "ffmpeg")
|
||||||
|
conf.Load(true)
|
||||||
|
Expect(conf.Server().Scanner.Extractor).To(Equal("taglib"))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("keeps taglib", func() {
|
||||||
|
conf.Load(true)
|
||||||
|
Expect(conf.Server().Scanner.Extractor).To(Equal("taglib"))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -390,7 +451,7 @@ var _ = Describe("Configuration", func() {
|
||||||
It("defaults to false", func() {
|
It("defaults to false", func() {
|
||||||
conf.Load(true)
|
conf.Load(true)
|
||||||
|
|
||||||
Expect(conf.Server.EnforceNonRootUser).To(BeFalse())
|
Expect(conf.Server().EnforceNonRootUser).To(BeFalse())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("allows startup for non-root users when enabled", func() {
|
It("allows startup for non-root users when enabled", func() {
|
||||||
|
|
@ -399,7 +460,7 @@ var _ = Describe("Configuration", func() {
|
||||||
|
|
||||||
conf.Load(true)
|
conf.Load(true)
|
||||||
|
|
||||||
Expect(conf.Server.EnforceNonRootUser).To(BeTrue())
|
Expect(conf.Server().EnforceNonRootUser).To(BeTrue())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("exits when enabled and running as root without having created a data folder", func() {
|
It("exits when enabled and running as root without having created a data folder", func() {
|
||||||
|
|
@ -425,7 +486,7 @@ var _ = Describe("Configuration", func() {
|
||||||
|
|
||||||
conf.Load(true)
|
conf.Load(true)
|
||||||
|
|
||||||
Expect(conf.Server.EnforceNonRootUser).To(BeTrue())
|
Expect(conf.Server().EnforceNonRootUser).To(BeTrue())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -439,16 +500,16 @@ var _ = Describe("Configuration", func() {
|
||||||
conf.Load(true)
|
conf.Load(true)
|
||||||
|
|
||||||
// Execute the format-specific assertions
|
// Execute the format-specific assertions
|
||||||
Expect(conf.Server.MusicFolder).To(Equal(fmt.Sprintf("/%s/music", format)))
|
Expect(conf.Server().MusicFolder).To(Equal(fmt.Sprintf("/%s/music", format)))
|
||||||
Expect(conf.Server.UIWelcomeMessage).To(Equal("Welcome " + format))
|
Expect(conf.Server().UIWelcomeMessage).To(Equal("Welcome " + format))
|
||||||
Expect(conf.Server.Tags["custom"].Aliases).To(Equal([]string{format, "test"}))
|
Expect(conf.Server().Tags["custom"].Aliases).To(Equal([]string{format, "test"}))
|
||||||
Expect(conf.Server.Tags["artist"].Split).To(Equal([]string{";"}))
|
Expect(conf.Server().Tags["artist"].Split).To(Equal([]string{";"}))
|
||||||
|
|
||||||
// Check deprecated option mapping
|
// Check deprecated option mapping
|
||||||
Expect(conf.Server.ExtAuth.UserHeader).To(Equal("X-Auth-User"))
|
Expect(conf.Server().ExtAuth.UserHeader).To(Equal("X-Auth-User"))
|
||||||
|
|
||||||
// The config file used should be the one we created
|
// The config file used should be the one we created
|
||||||
Expect(conf.Server.ConfigFile).To(Equal(filename))
|
Expect(conf.Server().ConfigFile).To(Equal(filename))
|
||||||
},
|
},
|
||||||
Entry("TOML format", "toml"),
|
Entry("TOML format", "toml"),
|
||||||
Entry("YAML format", "yaml"),
|
Entry("YAML format", "yaml"),
|
||||||
|
|
@ -461,7 +522,7 @@ var _ = Describe("Configuration", func() {
|
||||||
conf.InitConfig(filename, false)
|
conf.InitConfig(filename, false)
|
||||||
conf.Load(true)
|
conf.Load(true)
|
||||||
|
|
||||||
server := conf.Server
|
server := conf.Server()
|
||||||
Expect(server.SessionTimeout).To(Equal(consts.DefaultSessionTimeout))
|
Expect(server.SessionTimeout).To(Equal(consts.DefaultSessionTimeout))
|
||||||
Expect(server.SmartPlaylistRefreshDelay).To(Equal(consts.DefaultSmartRefresh))
|
Expect(server.SmartPlaylistRefreshDelay).To(Equal(consts.DefaultSmartRefresh))
|
||||||
Expect(server.DefaultShareExpiration).To(Equal(consts.DefaultShareExpiration))
|
Expect(server.DefaultShareExpiration).To(Equal(consts.DefaultShareExpiration))
|
||||||
|
|
@ -483,7 +544,7 @@ var _ = Describe("Configuration", func() {
|
||||||
|
|
||||||
configured := 1 * time.Second
|
configured := 1 * time.Second
|
||||||
|
|
||||||
server := conf.Server
|
server := conf.Server()
|
||||||
Expect(server.SessionTimeout).To(Equal(configured))
|
Expect(server.SessionTimeout).To(Equal(configured))
|
||||||
Expect(server.SmartPlaylistRefreshDelay).To(Equal(configured))
|
Expect(server.SmartPlaylistRefreshDelay).To(Equal(configured))
|
||||||
Expect(server.DefaultShareExpiration).To(Equal(configured))
|
Expect(server.DefaultShareExpiration).To(Equal(configured))
|
||||||
|
|
@ -501,27 +562,26 @@ var _ = Describe("Configuration", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
var _ = Describe("TLSEnabled", func() {
|
var _ = Describe("TLSEnabled", func() {
|
||||||
BeforeEach(func() {
|
|
||||||
DeferCleanup(configtest.SetupConfig())
|
|
||||||
})
|
|
||||||
|
|
||||||
It("is false when neither the certificate nor the key is set", func() {
|
It("is false when neither the certificate nor the key is set", func() {
|
||||||
Expect(conf.Server.TLSEnabled()).To(BeFalse())
|
Expect(conf.Server().TLSEnabled()).To(BeFalse())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("is true when both the certificate and the key are set", func() {
|
It("is true when both the certificate and the key are set", func() {
|
||||||
conf.Server.TLSCert = "cert.pem"
|
conf.Update(func(c *conf.Options) {
|
||||||
conf.Server.TLSKey = "key.pem"
|
c.TLSCert = "cert.pem"
|
||||||
Expect(conf.Server.TLSEnabled()).To(BeTrue())
|
c.TLSKey = "key.pem"
|
||||||
|
})
|
||||||
|
Expect(conf.Server().TLSEnabled()).To(BeTrue())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("is false when only the certificate is set", func() {
|
It("is false when only the certificate is set", func() {
|
||||||
conf.Server.TLSCert = "cert.pem"
|
conf.Update(func(c *conf.Options) { c.TLSCert = "cert.pem" })
|
||||||
Expect(conf.Server.TLSEnabled()).To(BeFalse())
|
Expect(conf.Server().TLSEnabled()).To(BeFalse())
|
||||||
})
|
})
|
||||||
|
|
||||||
It("is false when only the key is set", func() {
|
It("is false when only the key is set", func() {
|
||||||
conf.Server.TLSKey = "key.pem"
|
conf.Update(func(c *conf.Options) { c.TLSKey = "key.pem" })
|
||||||
Expect(conf.Server.TLSEnabled()).To(BeFalse())
|
Expect(conf.Server().TLSEnabled()).To(BeFalse())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -82,20 +82,14 @@ var _ = Describe("Dir", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("calls logFatal on error", func() {
|
It("calls logFatal on error", func() {
|
||||||
var fatalMsg []any
|
DeferCleanup(conf.PanicOnLogFatal())
|
||||||
restore := conf.SetLogFatal(func(args ...any) {
|
|
||||||
fatalMsg = args
|
|
||||||
panic("logFatal called")
|
|
||||||
})
|
|
||||||
DeferCleanup(restore)
|
|
||||||
|
|
||||||
f := GinkgoT().TempDir() + "/blocker"
|
f := GinkgoT().TempDir() + "/blocker"
|
||||||
Expect(os.WriteFile(f, []byte("x"), 0600)).To(Succeed())
|
Expect(os.WriteFile(f, []byte("x"), 0600)).To(Succeed())
|
||||||
invalid := f + "/subdir"
|
invalid := f + "/subdir"
|
||||||
|
|
||||||
d := conf.NewDir(invalid)
|
d := conf.NewDir(invalid)
|
||||||
Expect(func() { d.MustPath() }).To(Panic())
|
Expect(func() { d.MustPath() }).To(PanicWith(ContainSubstring("creating directory")))
|
||||||
Expect(fatalMsg).ToNot(BeEmpty())
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
package conf
|
package conf
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
func ResetConf() {
|
func ResetConf() {
|
||||||
Server = &configOptions{}
|
current.Store(&Options{})
|
||||||
}
|
}
|
||||||
|
|
||||||
var SetViperDefaults = setViperDefaults
|
var SetViperDefaults = setViperDefaults
|
||||||
|
|
@ -33,6 +35,13 @@ func SetLogFatal(f func(...any)) func() {
|
||||||
return func() { logFatal = old }
|
return func() { logFatal = old }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PanicOnLogFatal stops the caller the way os.Exit would, so specs can assert on the fatal message.
|
||||||
|
func PanicOnLogFatal() func() {
|
||||||
|
return SetLogFatal(func(args ...any) {
|
||||||
|
panic(fmt.Sprint(args...)) //nolint:forbidigo
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
var UnknownConfigKeys = unknownConfigKeys
|
var UnknownConfigKeys = unknownConfigKeys
|
||||||
|
|
||||||
var SuggestOptions = suggestOptions
|
var SuggestOptions = suggestOptions
|
||||||
|
|
|
||||||
87
conf/server.go
Normal file
87
conf/server.go
Normal file
|
|
@ -0,0 +1,87 @@
|
||||||
|
package conf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"sync/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
var current atomic.Pointer[Options]
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
current.Store(&Options{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server returns a copy of the current configuration. A published Options is never changed in place,
|
||||||
|
// so readers need no locking. Use Update to change it.
|
||||||
|
func Server() Options {
|
||||||
|
return *current.Load()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update applies fn to a deep copy of the current configuration and publishes the result.
|
||||||
|
// fn may run more than once if another change lands first, so it must only set fields.
|
||||||
|
func Update(fn func(*Options)) {
|
||||||
|
for {
|
||||||
|
old := current.Load()
|
||||||
|
next := clone(old)
|
||||||
|
fn(next)
|
||||||
|
if current.CompareAndSwap(old, next) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SnapshotConfig returns a function that restores the configuration to its current state.
|
||||||
|
func SnapshotConfig() func() {
|
||||||
|
snapshot := current.Load()
|
||||||
|
return func() { current.Store(snapshot) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func clone(o *Options) *Options {
|
||||||
|
var c Options
|
||||||
|
deepCopy(reflect.ValueOf(&c).Elem(), reflect.ValueOf(o).Elem())
|
||||||
|
return &c
|
||||||
|
}
|
||||||
|
|
||||||
|
func deepCopy(dst, src reflect.Value) {
|
||||||
|
switch src.Kind() {
|
||||||
|
case reflect.Struct:
|
||||||
|
dst.Set(src)
|
||||||
|
for i := range src.NumField() {
|
||||||
|
if dst.Field(i).CanSet() {
|
||||||
|
deepCopy(dst.Field(i), src.Field(i))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case reflect.Map:
|
||||||
|
if src.IsNil() {
|
||||||
|
dst.Set(src)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
m := reflect.MakeMapWithSize(src.Type(), src.Len())
|
||||||
|
for k, v := range src.Seq2() {
|
||||||
|
nv := reflect.New(v.Type()).Elem()
|
||||||
|
deepCopy(nv, v)
|
||||||
|
m.SetMapIndex(k, nv)
|
||||||
|
}
|
||||||
|
dst.Set(m)
|
||||||
|
case reflect.Slice:
|
||||||
|
if src.IsNil() {
|
||||||
|
dst.Set(src)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s := reflect.MakeSlice(src.Type(), src.Len(), src.Len())
|
||||||
|
for i := range src.Len() {
|
||||||
|
deepCopy(s.Index(i), src.Index(i))
|
||||||
|
}
|
||||||
|
dst.Set(s)
|
||||||
|
case reflect.Pointer:
|
||||||
|
if src.IsNil() {
|
||||||
|
dst.Set(src)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p := reflect.New(src.Type().Elem())
|
||||||
|
deepCopy(p.Elem(), src.Elem())
|
||||||
|
dst.Set(p)
|
||||||
|
default:
|
||||||
|
dst.Set(src)
|
||||||
|
}
|
||||||
|
}
|
||||||
89
conf/server_test.go
Normal file
89
conf/server_test.go
Normal file
|
|
@ -0,0 +1,89 @@
|
||||||
|
package conf_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/conf"
|
||||||
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
. "github.com/onsi/gomega"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ = Describe("Server state", func() {
|
||||||
|
BeforeEach(func() {
|
||||||
|
conf.Update(func(c *conf.Options) {
|
||||||
|
c.Tags = map[string]conf.TagConf{"genre": {Aliases: []string{"genre", "style"}}}
|
||||||
|
c.DevLogLevels = map[string]string{"scanner": "info"}
|
||||||
|
c.Scanner.ArtistSplitExceptions = []string{"AC/DC"}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
It("keeps a copy taken from Server unchanged by later updates", func() {
|
||||||
|
before := conf.Server()
|
||||||
|
|
||||||
|
conf.Update(func(c *conf.Options) {
|
||||||
|
c.Tags["genre"].Aliases[0] = "changed"
|
||||||
|
c.DevLogLevels["scanner"] = "debug"
|
||||||
|
c.Scanner.ArtistSplitExceptions[0] = "changed"
|
||||||
|
})
|
||||||
|
|
||||||
|
Expect(before.Tags["genre"].Aliases).To(Equal([]string{"genre", "style"}))
|
||||||
|
Expect(before.DevLogLevels).To(Equal(map[string]string{"scanner": "info"}))
|
||||||
|
Expect(before.Scanner.ArtistSplitExceptions).To(Equal([]string{"AC/DC"}))
|
||||||
|
Expect(conf.Server().DevLogLevels["scanner"]).To(Equal("debug"))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("restores map and slice contents changed in place by Update", func() {
|
||||||
|
restore := conf.SnapshotConfig()
|
||||||
|
conf.Update(func(c *conf.Options) {
|
||||||
|
c.Tags["genre"].Aliases[0] = "changed"
|
||||||
|
c.DevLogLevels["scanner"] = "debug"
|
||||||
|
})
|
||||||
|
|
||||||
|
restore()
|
||||||
|
|
||||||
|
Expect(conf.Server().Tags["genre"].Aliases).To(Equal([]string{"genre", "style"}))
|
||||||
|
Expect(conf.Server().DevLogLevels).To(Equal(map[string]string{"scanner": "info"}))
|
||||||
|
})
|
||||||
|
|
||||||
|
It("lets readers run while the config is updated and restored", func() {
|
||||||
|
stop := make(chan struct{})
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
wg.Go(func() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-stop:
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
_ = conf.Server().DevLogLevels["scanner"]
|
||||||
|
_ = conf.Server().Scanner.Enabled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
for range 100 {
|
||||||
|
restore := conf.SnapshotConfig()
|
||||||
|
conf.Update(func(c *conf.Options) {
|
||||||
|
c.DevLogLevels["scanner"] = "debug"
|
||||||
|
c.Scanner.Enabled = !c.Scanner.Enabled
|
||||||
|
})
|
||||||
|
restore()
|
||||||
|
}
|
||||||
|
close(stop)
|
||||||
|
wg.Wait()
|
||||||
|
})
|
||||||
|
|
||||||
|
It("keeps every change when updates run at the same time", func() {
|
||||||
|
conf.Update(func(c *conf.Options) { c.Port = 0 })
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for range 50 {
|
||||||
|
wg.Go(func() {
|
||||||
|
for range 20 {
|
||||||
|
conf.Update(func(c *conf.Options) { c.Port++ })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
Expect(conf.Server().Port).To(Equal(1000))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -49,6 +49,7 @@ const (
|
||||||
DefaultEncryptionKey = "just for obfuscation"
|
DefaultEncryptionKey = "just for obfuscation"
|
||||||
PasswordsEncryptedKey = "PasswordsEncryptedKey"
|
PasswordsEncryptedKey = "PasswordsEncryptedKey"
|
||||||
PasswordAutogenPrefix = "__NAVIDROME_AUTOGEN__" //nolint:gosec
|
PasswordAutogenPrefix = "__NAVIDROME_AUTOGEN__" //nolint:gosec
|
||||||
|
APIKeyPrefix = "nds_"
|
||||||
|
|
||||||
DevInitialUserName = "admin"
|
DevInitialUserName = "admin"
|
||||||
DevInitialName = "Dev Admin"
|
DevInitialName = "Dev Admin"
|
||||||
|
|
@ -59,6 +60,7 @@ const (
|
||||||
URLPathPublic = "/share"
|
URLPathPublic = "/share"
|
||||||
URLPathPublicImages = URLPathPublic + "/img"
|
URLPathPublicImages = URLPathPublic + "/img"
|
||||||
URLPathJellyfinAPI = "/jellyfin"
|
URLPathJellyfinAPI = "/jellyfin"
|
||||||
|
URLPathAPIv1 = "/api/v1"
|
||||||
|
|
||||||
// JellyfinServerIDKey is the Property key for the stable, persisted server Id reported by the
|
// JellyfinServerIDKey is the Property key for the stable, persisted server Id reported by the
|
||||||
// Jellyfin API. Jellyfin clients cache this value, so it must survive process restarts.
|
// Jellyfin API. Jellyfin clients cache this value, so it must survive process restarts.
|
||||||
|
|
@ -81,6 +83,8 @@ const (
|
||||||
|
|
||||||
DefaultInfoLanguage = "en"
|
DefaultInfoLanguage = "en"
|
||||||
|
|
||||||
|
DefaultMinScrobbleDuration = 30 * time.Second
|
||||||
|
|
||||||
ArtistInfoTimeToLive = 24 * time.Hour
|
ArtistInfoTimeToLive = 24 * time.Hour
|
||||||
AlbumInfoTimeToLive = 7 * 24 * time.Hour
|
AlbumInfoTimeToLive = 7 * 24 * time.Hour
|
||||||
UpdateLastAccessFrequency = time.Minute
|
UpdateLastAccessFrequency = time.Minute
|
||||||
|
|
@ -88,6 +92,7 @@ const (
|
||||||
|
|
||||||
I18nFolder = "i18n"
|
I18nFolder = "i18n"
|
||||||
ScanIgnoreFile = ".ndignore"
|
ScanIgnoreFile = ".ndignore"
|
||||||
|
NoMediaFile = ".nomedia"
|
||||||
ArtworkFolder = "artwork"
|
ArtworkFolder = "artwork"
|
||||||
// HashedArtworkFolder is a subtree of ArtworkFolder, kept apart from the name-addressed
|
// HashedArtworkFolder is a subtree of ArtworkFolder, kept apart from the name-addressed
|
||||||
// upload folders beside it so Prune's sweep never reaches them.
|
// upload folders beside it so Prune's sweep never reaches them.
|
||||||
|
|
@ -154,8 +159,6 @@ const (
|
||||||
//DefaultAlbumPID = "album_legacy"
|
//DefaultAlbumPID = "album_legacy"
|
||||||
DefaultAlbumPID = "musicbrainz_albumid|albumartistid,album,albumversion,releasedate"
|
DefaultAlbumPID = "musicbrainz_albumid|albumartistid,album,albumversion,releasedate"
|
||||||
DefaultTrackPID = "musicbrainz_trackid|albumid,discnumber,tracknumber,title"
|
DefaultTrackPID = "musicbrainz_trackid|albumid,discnumber,tracknumber,title"
|
||||||
PIDAlbumKey = "PIDAlbum"
|
|
||||||
PIDTrackKey = "PIDTrack"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
|
@ -210,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 = " • "
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -36,7 +36,7 @@ RestrictNamespaces=yes
|
||||||
RestrictRealtime=yes
|
RestrictRealtime=yes
|
||||||
SystemCallFilter=@system-service
|
SystemCallFilter=@system-service
|
||||||
SystemCallFilter=~@privileged @resources
|
SystemCallFilter=~@privileged @resources
|
||||||
SystemCallFilter=setrlimit
|
SystemCallFilter=setrlimit mbind
|
||||||
SystemCallArchitectures=native
|
SystemCallArchitectures=native
|
||||||
UMask=0066
|
UMask=0066
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -94,7 +94,7 @@ type enabledAgent struct {
|
||||||
// Each enabledAgent contains the name and whether it's a plugin (true) or built-in (false)
|
// Each enabledAgent contains the name and whether it's a plugin (true) or built-in (false)
|
||||||
func (a *Agents) getEnabledAgentNames() []enabledAgent {
|
func (a *Agents) getEnabledAgentNames() []enabledAgent {
|
||||||
// If no agents configured, ONLY use the local agent
|
// If no agents configured, ONLY use the local agent
|
||||||
if conf.Server.Agents == "" {
|
if conf.Server().Agents == "" {
|
||||||
return []enabledAgent{{name: LocalAgentName, isPlugin: false}}
|
return []enabledAgent{{name: LocalAgentName, isPlugin: false}}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -105,7 +105,7 @@ func (a *Agents) getEnabledAgentNames() []enabledAgent {
|
||||||
}
|
}
|
||||||
log.Trace("Available MetadataAgent plugins", "plugins", availablePlugins)
|
log.Trace("Available MetadataAgent plugins", "plugins", availablePlugins)
|
||||||
|
|
||||||
configuredAgents := strings.Split(conf.Server.Agents, ",")
|
configuredAgents := strings.Split(conf.Server().Agents, ",")
|
||||||
|
|
||||||
// Always add LocalAgentName if not already included
|
// Always add LocalAgentName if not already included
|
||||||
hasLocalAgent := slices.Contains(configuredAgents, LocalAgentName)
|
hasLocalAgent := slices.Contains(configuredAgents, LocalAgentName)
|
||||||
|
|
@ -157,7 +157,7 @@ func (a *Agents) getAgent(ea enabledAgent) Interface {
|
||||||
if agent != nil {
|
if agent != nil {
|
||||||
return agent
|
return agent
|
||||||
}
|
}
|
||||||
log.Debug("Built-in agent not available. Missing configuration?", "name", ea.name)
|
log.Debug("Built-in agent not available. Disabled or missing configuration?", "name", ea.name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -181,7 +181,7 @@ type AlbumImageAgent struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ArtistImageAgents returns the enabled agents implementing ArtistImageRetriever,
|
// ArtistImageAgents returns the enabled agents implementing ArtistImageRetriever,
|
||||||
// in conf.Server.Agents order (same order the aggregate dispatch uses).
|
// in conf.Server().Agents order (same order the aggregate dispatch uses).
|
||||||
func (a *Agents) ArtistImageAgents() []ArtistImageAgent {
|
func (a *Agents) ArtistImageAgents() []ArtistImageAgent {
|
||||||
var result []ArtistImageAgent
|
var result []ArtistImageAgent
|
||||||
for _, ea := range a.getEnabledAgentNames() {
|
for _, ea := range a.getEnabledAgentNames() {
|
||||||
|
|
@ -193,7 +193,7 @@ func (a *Agents) ArtistImageAgents() []ArtistImageAgent {
|
||||||
}
|
}
|
||||||
|
|
||||||
// AlbumImageAgents returns the enabled agents implementing AlbumImageRetriever,
|
// AlbumImageAgents returns the enabled agents implementing AlbumImageRetriever,
|
||||||
// in conf.Server.Agents order (same order the aggregate dispatch uses).
|
// in conf.Server().Agents order (same order the aggregate dispatch uses).
|
||||||
func (a *Agents) AlbumImageAgents() []AlbumImageAgent {
|
func (a *Agents) AlbumImageAgents() []AlbumImageAgent {
|
||||||
var result []AlbumImageAgent
|
var result []AlbumImageAgent
|
||||||
for _, ea := range a.getEnabledAgentNames() {
|
for _, ea := range a.getEnabledAgentNames() {
|
||||||
|
|
@ -256,7 +256,7 @@ func (a *Agents) GetArtistBiography(ctx context.Context, id, name, mbid string)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetSimilarArtists returns similar artists by id, name, and/or mbid. Because some artists returned from an enabled
|
// GetSimilarArtists returns similar artists by id, name, and/or mbid. Because some artists returned from an enabled
|
||||||
// agent may not exist in the database, return at most limit * conf.Server.DevExternalArtistFetchMultiplier items.
|
// agent may not exist in the database, return at most limit * conf.Server().DevExternalArtistFetchMultiplier items.
|
||||||
func (a *Agents) GetSimilarArtists(ctx context.Context, id, name, mbid string, limit int) ([]Artist, error) {
|
func (a *Agents) GetSimilarArtists(ctx context.Context, id, name, mbid string, limit int) ([]Artist, error) {
|
||||||
switch id {
|
switch id {
|
||||||
case consts.UnknownArtistID:
|
case consts.UnknownArtistID:
|
||||||
|
|
@ -265,7 +265,7 @@ func (a *Agents) GetSimilarArtists(ctx context.Context, id, name, mbid string, l
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
overLimit := int(float64(limit) * conf.Server.DevExternalArtistFetchMultiplier)
|
overLimit := int(float64(limit) * conf.Server().DevExternalArtistFetchMultiplier)
|
||||||
|
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
attempts := newAttempts(&a.cooldowns)
|
attempts := newAttempts(&a.cooldowns)
|
||||||
|
|
@ -316,7 +316,7 @@ func (a *Agents) GetArtistImages(ctx context.Context, id, name, mbid string) ([]
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetArtistTopSongs returns top songs by id, name, and/or mbid. Because some songs returned from an enabled
|
// GetArtistTopSongs returns top songs by id, name, and/or mbid. Because some songs returned from an enabled
|
||||||
// agent may not exist in the database, return at most limit * conf.Server.DevExternalArtistFetchMultiplier items.
|
// agent may not exist in the database, return at most limit * conf.Server().DevExternalArtistFetchMultiplier items.
|
||||||
func (a *Agents) GetArtistTopSongs(ctx context.Context, id, artistName, mbid string, count int) ([]Song, error) {
|
func (a *Agents) GetArtistTopSongs(ctx context.Context, id, artistName, mbid string, count int) ([]Song, error) {
|
||||||
switch id {
|
switch id {
|
||||||
case consts.UnknownArtistID:
|
case consts.UnknownArtistID:
|
||||||
|
|
@ -325,7 +325,7 @@ func (a *Agents) GetArtistTopSongs(ctx context.Context, id, artistName, mbid str
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
overLimit := int(float64(count) * conf.Server.DevExternalArtistFetchMultiplier)
|
overLimit := int(float64(count) * conf.Server().DevExternalArtistFetchMultiplier)
|
||||||
|
|
||||||
return callAgentSliceMethod(ctx, a, "GetArtistTopSongs", func(ag Interface) ([]Song, error) {
|
return callAgentSliceMethod(ctx, a, "GetArtistTopSongs", func(ag Interface) ([]Song, error) {
|
||||||
retriever, ok := ag.(ArtistTopSongsRetriever)
|
retriever, ok := ag.(ArtistTopSongsRetriever)
|
||||||
|
|
|
||||||
|
|
@ -55,10 +55,12 @@ var _ ArtistMBIDRetriever = (*MockAgent)(nil)
|
||||||
var _ PluginLoader = (*MockPluginLoader)(nil)
|
var _ PluginLoader = (*MockPluginLoader)(nil)
|
||||||
|
|
||||||
var _ = Describe("Agents with Plugin Loading", func() {
|
var _ = Describe("Agents with Plugin Loading", func() {
|
||||||
|
var ctx context.Context
|
||||||
var mockLoader *MockPluginLoader
|
var mockLoader *MockPluginLoader
|
||||||
var agents *Agents
|
var agents *Agents
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
|
ctx = GinkgoT().Context()
|
||||||
mockLoader = NewMockPluginLoader()
|
mockLoader = NewMockPluginLoader()
|
||||||
|
|
||||||
// Create the agents instance with our mock loader
|
// Create the agents instance with our mock loader
|
||||||
|
|
@ -68,7 +70,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||||
Context("Dynamic agent discovery", func() {
|
Context("Dynamic agent discovery", func() {
|
||||||
It("should include ONLY local agent when no config is specified", func() {
|
It("should include ONLY local agent when no config is specified", func() {
|
||||||
// Ensure no specific agents are configured
|
// Ensure no specific agents are configured
|
||||||
conf.Server.Agents = ""
|
conf.Update(func(c *conf.Options) { c.Agents = "" })
|
||||||
|
|
||||||
// Add some plugin agents that should be ignored
|
// Add some plugin agents that should be ignored
|
||||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent", "another_plugin")
|
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent", "another_plugin")
|
||||||
|
|
@ -82,7 +84,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||||
|
|
||||||
It("should NOT include plugin agents when no config is specified", func() {
|
It("should NOT include plugin agents when no config is specified", func() {
|
||||||
// Ensure no specific agents are configured
|
// Ensure no specific agents are configured
|
||||||
conf.Server.Agents = ""
|
conf.Update(func(c *conf.Options) { c.Agents = "" })
|
||||||
|
|
||||||
// Add a plugin agent
|
// Add a plugin agent
|
||||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent")
|
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent")
|
||||||
|
|
@ -99,13 +101,13 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent")
|
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent")
|
||||||
|
|
||||||
// With no config, should not include plugin
|
// With no config, should not include plugin
|
||||||
conf.Server.Agents = ""
|
conf.Update(func(c *conf.Options) { c.Agents = "" })
|
||||||
enabledAgents := agents.getEnabledAgentNames()
|
enabledAgents := agents.getEnabledAgentNames()
|
||||||
Expect(enabledAgents).To(HaveLen(1))
|
Expect(enabledAgents).To(HaveLen(1))
|
||||||
Expect(enabledAgents[0].name).To(Equal(LocalAgentName))
|
Expect(enabledAgents[0].name).To(Equal(LocalAgentName))
|
||||||
|
|
||||||
// When explicitly configured, should include plugin
|
// When explicitly configured, should include plugin
|
||||||
conf.Server.Agents = "plugin_agent"
|
conf.Update(func(c *conf.Options) { c.Agents = "plugin_agent" })
|
||||||
enabledAgents = agents.getEnabledAgentNames()
|
enabledAgents = agents.getEnabledAgentNames()
|
||||||
var agentNames []string
|
var agentNames []string
|
||||||
var pluginAgentFound bool
|
var pluginAgentFound bool
|
||||||
|
|
@ -125,7 +127,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_one", "plugin_two")
|
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_one", "plugin_two")
|
||||||
|
|
||||||
// Configure only one of them
|
// Configure only one of them
|
||||||
conf.Server.Agents = "plugin_one"
|
conf.Update(func(c *conf.Options) { c.Agents = "plugin_one" })
|
||||||
|
|
||||||
// Verify only the configured one is included
|
// Verify only the configured one is included
|
||||||
enabledAgents := agents.getEnabledAgentNames()
|
enabledAgents := agents.getEnabledAgentNames()
|
||||||
|
|
@ -144,10 +146,8 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("should load plugin agents on demand", func() {
|
It("should load plugin agents on demand", func() {
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
// Configure to use our plugin
|
// Configure to use our plugin
|
||||||
conf.Server.Agents = "plugin_agent"
|
conf.Update(func(c *conf.Options) { c.Agents = "plugin_agent" })
|
||||||
|
|
||||||
// Add a plugin agent
|
// Add a plugin agent
|
||||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent")
|
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent")
|
||||||
|
|
@ -177,7 +177,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// Configure to use both built-in and plugin
|
// Configure to use both built-in and plugin
|
||||||
conf.Server.Agents = "built_in,plugin_agent"
|
conf.Update(func(c *conf.Options) { c.Agents = "built_in,plugin_agent" })
|
||||||
|
|
||||||
// Add a plugin agent
|
// Add a plugin agent
|
||||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent")
|
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_agent")
|
||||||
|
|
@ -223,7 +223,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||||
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_x", "plugin_y")
|
mockLoader.pluginNames = append(mockLoader.pluginNames, "plugin_x", "plugin_y")
|
||||||
|
|
||||||
// Configure specific order - plugin first, then built-ins
|
// Configure specific order - plugin first, then built-ins
|
||||||
conf.Server.Agents = "plugin_y,agent_b,plugin_x,agent_a"
|
conf.Update(func(c *conf.Options) { c.Agents = "plugin_y,agent_b,plugin_x,agent_a" })
|
||||||
|
|
||||||
// Get the agent names
|
// Get the agent names
|
||||||
enabledAgents := agents.getEnabledAgentNames()
|
enabledAgents := agents.getEnabledAgentNames()
|
||||||
|
|
@ -236,8 +236,6 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("should NOT call LoadMediaAgent for built-in agents", func() {
|
It("should NOT call LoadMediaAgent for built-in agents", func() {
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
// Create a mock built-in agent
|
// Create a mock built-in agent
|
||||||
Register("builtin_agent", func(ds model.DataStore) Interface {
|
Register("builtin_agent", func(ds model.DataStore) Interface {
|
||||||
return &MockAgent{
|
return &MockAgent{
|
||||||
|
|
@ -250,7 +248,7 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// Configure to use only built-in agents
|
// Configure to use only built-in agents
|
||||||
conf.Server.Agents = "builtin_agent"
|
conf.Update(func(c *conf.Options) { c.Agents = "builtin_agent" })
|
||||||
|
|
||||||
// Call GetArtistMBID which should only use the built-in agent
|
// Call GetArtistMBID which should only use the built-in agent
|
||||||
mbid, err := agents.GetArtistMBID(ctx, "123", "Artist")
|
mbid, err := agents.GetArtistMBID(ctx, "123", "Artist")
|
||||||
|
|
@ -263,10 +261,8 @@ var _ = Describe("Agents with Plugin Loading", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("should NOT call LoadMediaAgent for invalid agent names", func() {
|
It("should NOT call LoadMediaAgent for invalid agent names", func() {
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
// Configure with an invalid agent name (not built-in, not a plugin)
|
// Configure with an invalid agent name (not built-in, not a plugin)
|
||||||
conf.Server.Agents = "invalid_agent"
|
conf.Update(func(c *conf.Options) { c.Agents = "invalid_agent" })
|
||||||
|
|
||||||
// This should only result in using the local agent (as the invalid one is ignored)
|
// This should only result in using the local agent (as the invalid one is ignored)
|
||||||
_, err := agents.GetArtistMBID(ctx, "123", "Artist")
|
_, err := agents.GetArtistMBID(ctx, "123", "Artist")
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ package agents
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/navidrome/navidrome/conf/configtest"
|
||||||
"github.com/navidrome/navidrome/log"
|
"github.com/navidrome/navidrome/log"
|
||||||
"github.com/navidrome/navidrome/tests"
|
"github.com/navidrome/navidrome/tests"
|
||||||
. "github.com/onsi/ginkgo/v2"
|
. "github.com/onsi/ginkgo/v2"
|
||||||
|
|
@ -15,3 +16,5 @@ func TestAgents(t *testing.T) {
|
||||||
RegisterFailHandler(Fail)
|
RegisterFailHandler(Fail)
|
||||||
RunSpecs(t, "Agents Test Suite")
|
RunSpecs(t, "Agents Test Suite")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ = configtest.RestoreAfterEachSpec()
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,6 @@ import (
|
||||||
"slices"
|
"slices"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/navidrome/navidrome/conf/configtest"
|
|
||||||
"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/tests"
|
||||||
|
|
@ -45,8 +44,7 @@ var _ = Describe("Agents", func() {
|
||||||
var ds model.DataStore
|
var ds model.DataStore
|
||||||
var mfRepo *tests.MockMediaFileRepo
|
var mfRepo *tests.MockMediaFileRepo
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
DeferCleanup(configtest.SetupConfig())
|
ctx, cancel = context.WithCancel(GinkgoT().Context())
|
||||||
ctx, cancel = context.WithCancel(context.Background())
|
|
||||||
mfRepo = tests.CreateMockMediaFileRepo()
|
mfRepo = tests.CreateMockMediaFileRepo()
|
||||||
ds = &tests.MockDataStore{MockedMediaFile: mfRepo}
|
ds = &tests.MockDataStore{MockedMediaFile: mfRepo}
|
||||||
})
|
})
|
||||||
|
|
@ -54,7 +52,7 @@ var _ = Describe("Agents", func() {
|
||||||
Describe("Local", func() {
|
Describe("Local", func() {
|
||||||
var ag *Agents
|
var ag *Agents
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
conf.Server.Agents = ""
|
conf.Update(func(c *conf.Options) { c.Agents = "" })
|
||||||
ag = createAgents(ds, nil)
|
ag = createAgents(ds, nil)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -74,7 +72,7 @@ var _ = Describe("Agents", func() {
|
||||||
Register("fake", func(model.DataStore) Interface { return mock })
|
Register("fake", func(model.DataStore) Interface { return mock })
|
||||||
Register("disabled", func(model.DataStore) Interface { return nil })
|
Register("disabled", func(model.DataStore) Interface { return nil })
|
||||||
Register("empty", func(model.DataStore) Interface { return &emptyAgent{} })
|
Register("empty", func(model.DataStore) Interface { return &emptyAgent{} })
|
||||||
conf.Server.Agents = "empty,fake,disabled"
|
conf.Update(func(c *conf.Options) { c.Agents = "empty,fake,disabled" })
|
||||||
ag = createAgents(ds, nil)
|
ag = createAgents(ds, nil)
|
||||||
Expect(ag.AgentName()).To(Equal("agents"))
|
Expect(ag.AgentName()).To(Equal("agents"))
|
||||||
})
|
})
|
||||||
|
|
@ -252,7 +250,7 @@ var _ = Describe("Agents", func() {
|
||||||
It("returns ErrNotFound when another agent answered with a definitive miss", func() {
|
It("returns ErrNotFound when another agent answered with a definitive miss", func() {
|
||||||
other := &mockAgent{Err: ErrNotFound}
|
other := &mockAgent{Err: ErrNotFound}
|
||||||
Register("fake2", func(model.DataStore) Interface { return other })
|
Register("fake2", func(model.DataStore) Interface { return other })
|
||||||
conf.Server.Agents = "fake,fake2"
|
conf.Update(func(c *conf.Options) { c.Agents = "fake,fake2" })
|
||||||
ag = createAgents(ds, nil)
|
ag = createAgents(ds, nil)
|
||||||
mock.Err = &RetryLaterError{RetryIn: time.Hour}
|
mock.Err = &RetryLaterError{RetryIn: time.Hour}
|
||||||
|
|
||||||
|
|
@ -269,7 +267,7 @@ var _ = Describe("Agents", func() {
|
||||||
It("returns ErrNotFound when another agent answered with an empty slice", func() {
|
It("returns ErrNotFound when another agent answered with an empty slice", func() {
|
||||||
empty := &testImageAgent{Name: "emptyImages"}
|
empty := &testImageAgent{Name: "emptyImages"}
|
||||||
Register("emptyImages", func(model.DataStore) Interface { return empty })
|
Register("emptyImages", func(model.DataStore) Interface { return empty })
|
||||||
conf.Server.Agents = "fake,emptyImages"
|
conf.Update(func(c *conf.Options) { c.Agents = "fake,emptyImages" })
|
||||||
ag = createAgents(ds, nil)
|
ag = createAgents(ds, nil)
|
||||||
mock.Err = &RetryLaterError{RetryIn: time.Hour}
|
mock.Err = &RetryLaterError{RetryIn: time.Hour}
|
||||||
|
|
||||||
|
|
@ -287,7 +285,7 @@ var _ = Describe("Agents", func() {
|
||||||
It("returns ErrNotFound from GetSimilarArtists when another agent answered", func() {
|
It("returns ErrNotFound from GetSimilarArtists when another agent answered", func() {
|
||||||
other := &mockAgent{Err: ErrNotFound}
|
other := &mockAgent{Err: ErrNotFound}
|
||||||
Register("fake2", func(model.DataStore) Interface { return other })
|
Register("fake2", func(model.DataStore) Interface { return other })
|
||||||
conf.Server.Agents = "fake,fake2"
|
conf.Update(func(c *conf.Options) { c.Agents = "fake,fake2" })
|
||||||
ag = createAgents(ds, nil)
|
ag = createAgents(ds, nil)
|
||||||
mock.Err = &RetryLaterError{RetryIn: time.Hour}
|
mock.Err = &RetryLaterError{RetryIn: time.Hour}
|
||||||
|
|
||||||
|
|
@ -330,7 +328,7 @@ var _ = Describe("Agents", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("falls back to the next agent on error", func() {
|
It("falls back to the next agent on error", func() {
|
||||||
conf.Server.Agents = "imgFail,imgOk"
|
conf.Update(func(c *conf.Options) { c.Agents = "imgFail,imgOk" })
|
||||||
ag = createAgents(ds, nil)
|
ag = createAgents(ds, nil)
|
||||||
|
|
||||||
images, err := ag.GetArtistImages(ctx, "id", "artist", "mbid")
|
images, err := ag.GetArtistImages(ctx, "id", "artist", "mbid")
|
||||||
|
|
@ -343,7 +341,7 @@ var _ = Describe("Agents", func() {
|
||||||
It("falls back if the first agent returns no images", func() {
|
It("falls back if the first agent returns no images", func() {
|
||||||
first.Err = nil
|
first.Err = nil
|
||||||
first.Images = []ExternalImage{}
|
first.Images = []ExternalImage{}
|
||||||
conf.Server.Agents = "imgFail,imgOk"
|
conf.Update(func(c *conf.Options) { c.Agents = "imgFail,imgOk" })
|
||||||
ag = createAgents(ds, nil)
|
ag = createAgents(ds, nil)
|
||||||
|
|
||||||
images, err := ag.GetArtistImages(ctx, "id", "artist", "mbid")
|
images, err := ag.GetArtistImages(ctx, "id", "artist", "mbid")
|
||||||
|
|
@ -379,7 +377,7 @@ var _ = Describe("Agents", func() {
|
||||||
|
|
||||||
Describe("GetArtistTopSongs", func() {
|
Describe("GetArtistTopSongs", func() {
|
||||||
It("returns on first match", func() {
|
It("returns on first match", func() {
|
||||||
conf.Server.DevExternalArtistFetchMultiplier = 1
|
conf.Update(func(c *conf.Options) { c.DevExternalArtistFetchMultiplier = 1 })
|
||||||
Expect(ag.GetArtistTopSongs(ctx, "123", "test", "mb123", 2)).To(Equal([]Song{{
|
Expect(ag.GetArtistTopSongs(ctx, "123", "test", "mb123", 2)).To(Equal([]Song{{
|
||||||
Name: "A Song",
|
Name: "A Song",
|
||||||
MBID: "mbid444",
|
MBID: "mbid444",
|
||||||
|
|
@ -387,7 +385,7 @@ var _ = Describe("Agents", func() {
|
||||||
Expect(mock.Args).To(HaveExactElements("123", "test", "mb123", 2))
|
Expect(mock.Args).To(HaveExactElements("123", "test", "mb123", 2))
|
||||||
})
|
})
|
||||||
It("skips the agent if it returns an error", func() {
|
It("skips the agent if it returns an error", func() {
|
||||||
conf.Server.DevExternalArtistFetchMultiplier = 1
|
conf.Update(func(c *conf.Options) { c.DevExternalArtistFetchMultiplier = 1 })
|
||||||
mock.Err = errors.New("error")
|
mock.Err = errors.New("error")
|
||||||
_, err := ag.GetArtistTopSongs(ctx, "123", "test", "mb123", 2)
|
_, err := ag.GetArtistTopSongs(ctx, "123", "test", "mb123", 2)
|
||||||
Expect(err).To(MatchError(ErrNotFound))
|
Expect(err).To(MatchError(ErrNotFound))
|
||||||
|
|
@ -400,7 +398,7 @@ var _ = Describe("Agents", func() {
|
||||||
Expect(mock.Args).To(BeEmpty())
|
Expect(mock.Args).To(BeEmpty())
|
||||||
})
|
})
|
||||||
It("fetches with multiplier", func() {
|
It("fetches with multiplier", func() {
|
||||||
conf.Server.DevExternalArtistFetchMultiplier = 2
|
conf.Update(func(c *conf.Options) { c.DevExternalArtistFetchMultiplier = 2 })
|
||||||
Expect(ag.GetArtistTopSongs(ctx, "123", "test", "mb123", 2)).To(Equal([]Song{{
|
Expect(ag.GetArtistTopSongs(ctx, "123", "test", "mb123", 2)).To(Equal([]Song{{
|
||||||
Name: "A Song",
|
Name: "A Song",
|
||||||
MBID: "mbid444",
|
MBID: "mbid444",
|
||||||
|
|
@ -519,7 +517,7 @@ var _ = Describe("Agents", func() {
|
||||||
|
|
||||||
Describe("ArtistImageAgents", func() {
|
Describe("ArtistImageAgents", func() {
|
||||||
It("returns only ArtistImageRetriever agents, named, in configured order", func() {
|
It("returns only ArtistImageRetriever agents, named, in configured order", func() {
|
||||||
conf.Server.Agents = "artistImg,noImages,artistImg2"
|
conf.Update(func(c *conf.Options) { c.Agents = "artistImg,noImages,artistImg2" })
|
||||||
ag = createAgents(ds, nil)
|
ag = createAgents(ds, nil)
|
||||||
|
|
||||||
result := ag.ArtistImageAgents()
|
result := ag.ArtistImageAgents()
|
||||||
|
|
@ -531,7 +529,7 @@ var _ = Describe("Agents", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("is empty when external services are disabled", func() {
|
It("is empty when external services are disabled", func() {
|
||||||
conf.Server.Agents = "" // what disableExternalServices() sets when EnableExternalServices=false
|
conf.Update(func(c *conf.Options) { c.Agents = "" }) // what disableExternalServices() sets when EnableExternalServices=false
|
||||||
ag = createAgents(ds, nil)
|
ag = createAgents(ds, nil)
|
||||||
Expect(ag.ArtistImageAgents()).To(BeEmpty())
|
Expect(ag.ArtistImageAgents()).To(BeEmpty())
|
||||||
})
|
})
|
||||||
|
|
@ -539,7 +537,7 @@ var _ = Describe("Agents", func() {
|
||||||
|
|
||||||
Describe("AlbumImageAgents", func() {
|
Describe("AlbumImageAgents", func() {
|
||||||
It("returns only AlbumImageRetriever agents, named, in configured order", func() {
|
It("returns only AlbumImageRetriever agents, named, in configured order", func() {
|
||||||
conf.Server.Agents = "albumImg,noImages,albumImg2"
|
conf.Update(func(c *conf.Options) { c.Agents = "albumImg,noImages,albumImg2" })
|
||||||
ag = createAgents(ds, nil)
|
ag = createAgents(ds, nil)
|
||||||
|
|
||||||
result := ag.AlbumImageAgents()
|
result := ag.AlbumImageAgents()
|
||||||
|
|
@ -551,7 +549,7 @@ var _ = Describe("Agents", func() {
|
||||||
})
|
})
|
||||||
|
|
||||||
It("is empty when external services are disabled", func() {
|
It("is empty when external services are disabled", func() {
|
||||||
conf.Server.Agents = "" // what disableExternalServices() sets when EnableExternalServices=false
|
conf.Update(func(c *conf.Options) { c.Agents = "" }) // what disableExternalServices() sets when EnableExternalServices=false
|
||||||
ag = createAgents(ds, nil)
|
ag = createAgents(ds, nil)
|
||||||
Expect(ag.AlbumImageAgents()).To(BeEmpty())
|
Expect(ag.AlbumImageAgents()).To(BeEmpty())
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -24,7 +24,7 @@ func (p *localAgent) AgentName() string {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *localAgent) GetArtistTopSongs(ctx context.Context, id, artistName, mbid string, count int) ([]Song, error) {
|
func (p *localAgent) GetArtistTopSongs(ctx context.Context, id, artistName, mbid string, count int) ([]Song, error) {
|
||||||
top, err := p.ds.MediaFile(ctx).GetAll(model.QueryOptions{
|
top, err := p.ds.MediaFile().GetAll(ctx, model.QueryOptions{
|
||||||
Sort: "playCount",
|
Sort: "playCount",
|
||||||
Order: "desc",
|
Order: "desc",
|
||||||
Max: count,
|
Max: count,
|
||||||
|
|
@ -43,7 +43,7 @@ func (p *localAgent) GetArtistTopSongs(ctx context.Context, id, artistName, mbid
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *localAgent) GetSimilarSongsByTrack(ctx context.Context, id, name, artist, mbid string, count int) ([]Song, error) {
|
func (p *localAgent) GetSimilarSongsByTrack(ctx context.Context, id, name, artist, mbid string, count int) ([]Song, error) {
|
||||||
seed, err := p.ds.MediaFile(ctx).Get(id)
|
seed, err := p.ds.MediaFile().Get(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
@ -53,7 +53,7 @@ func (p *localAgent) GetSimilarSongsByTrack(ctx context.Context, id, name, artis
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
// Ask for extra so we can drop the seed itself and still fill the count.
|
// Ask for extra so we can drop the seed itself and still fill the count.
|
||||||
candidates, err := p.ds.MediaFile(ctx).GetRandom(model.QueryOptions{
|
candidates, err := p.ds.MediaFile().GetRandom(ctx, model.QueryOptions{
|
||||||
Filters: squirrel.And{
|
Filters: squirrel.And{
|
||||||
persistence.SongGenres.ByID(genreIDs),
|
persistence.SongGenres.ByID(genreIDs),
|
||||||
squirrel.Eq{"missing": false},
|
squirrel.Eq{"missing": false},
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ var _ = Describe("localAgent GetSimilarSongsByTrack", func() {
|
||||||
var ctx context.Context
|
var ctx context.Context
|
||||||
|
|
||||||
BeforeEach(func() {
|
BeforeEach(func() {
|
||||||
ctx = context.Background()
|
ctx = GinkgoT().Context()
|
||||||
mfRepo = &tests.MockMediaFileRepo{}
|
mfRepo = &tests.MockMediaFileRepo{}
|
||||||
ds = &tests.MockDataStore{MockedMediaFile: mfRepo}
|
ds = &tests.MockDataStore{MockedMediaFile: mfRepo}
|
||||||
agent = &localAgent{ds: ds}
|
agent = &localAgent{ds: ds}
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue