Compare commits

..

47 commits

Author SHA1 Message Date
Deluan
14cbff5edc fix(artwork): prevent 32-bit overflow in the decode pixel guard
cfg.Width*cfg.Height in int overflows on 32-bit builds (armv5/v6/v7, 386) for
dimensions like 50000x50000, going negative and bypassing maxDecodePixels — the
exact bomb the guard exists to reject. Multiply in int64.
2026-07-18 00:12:22 -04:00
Deluan
ebaf804dbf fix(persistence): mirror the reader's remaining cheap album-root gates
The parent fold now also requires a single common parent across the album's
folders (a compilation spread over artist folders has no album root), excludes a
parent that is itself one of the album's folders, and excludes the library root,
matching albumRootParent. The subtree-audio gate stays unmirrored on purpose: it
would need a per-row LIKE prefix scan over the folder table, and with omission
plus the write-side clamp its absence can only suppress a hash briefly until the
next serve. Plan verified on a 96K-track production copy: all folder accesses
remain PK point lookups.
2026-07-18 00:05:57 -04:00
Deluan
116fc5b853 fix(artwork): bound decoded dimensions and stop the clamp at serve start
Two hardening fixes to the inline updater. The tee's 20MB cap bounds compressed
input only, so a small file declaring a huge raster could allocate GBs on decode;
DecodeConfig now rejects anything over ~36M pixels from the header alone. And the
write-side version clamp no longer advances past the serve's start time: a version
change that lands mid-serve is not provably covered by the bytes being streamed,
so the clamp stops there, the DTO omits, and the next serve of the new bytes
heals — while structural read-side over-approximation (which always predates the
serve) still clamps fully.
2026-07-17 23:53:22 -04:00
Deluan
cddc30b586 fix(persistence): gate the parent fold by the reader's album-root rule
The parent folder's images_updated_at now counts only when the reader could
actually serve the album-root cover: multiple album folders (disc layout), or a
single folder with no images of its own. This mirrors albumRootParent's first
qualification gate, so an unrelated artist-level image change no longer advances
(and temporarily suppresses) the version of every sibling album with its own
cover. The remaining gates (other-audio, library root) stay unmirrored: with
omission plus the write-side clamp, residual over-approximation only causes a
short suppression that closes on the next serve. Plan verified on a 96K-track
production copy: unchanged, all PK point lookups.
2026-07-17 23:41:08 -04:00
Deluan
9e3fc91cec test(artwork): separate the cover swap in time for Windows clock granularity
The quick-scan e2e swapped the cover milliseconds after the first serve; Windows'
~15ms timer granularity could collapse the stored version and the new folder
timestamp into equal values, failing the staleness assertion. A 50ms gap makes the
ordering deterministic on all platforms.
2026-07-17 23:36:52 -04:00
Deluan
a98bebc314 fix(artwork): clamp the persisted blurhash version to the entity's
The read-side artwork version may over-approximate the served sources (folder
parents for disc layouts), which with omission semantics suppresses a perfectly
valid stored hash. At persist time the hash is fresh for the served bytes by
construction, so the write now loads the entity and clamps blur_hash_updated_at
up to its current ArtworkUpdatedAt: after any serve the DTO accepts the stored
hash, and every omission window closes regardless of read-side precision. The
in-memory state shrinks to a pure decode cache (checksum -> hash); staleness
decisions moved to the row read, which also lets a drifted stored value be
restored from the served bytes.
2026-07-17 23:28:02 -04:00
Deluan
817baa5c1a fix(jellyfin): omit the blurhash when no current hash exists, never fabricate
Upstream Jellyfin omits ImageBlurHashes entries when no hash was computed, and
clients are built around that: redesign Finamp uses the blurhash as immutable
cover identity (year-long cache pins, download dedup) and falls back to id-keyed
caching with a short TTL when it is absent. Emitting a rotating fake seeded by
id+version fed a fabricated identity into those caches and churned them on every
version bump, and a fake accepted under an imprecise artwork version could pin a
wrong value for a year. Absence is strictly safer: no LQIP during the first-serve
gap, self-healing within the fallback TTL.

The staleness gate is kept, its job now being to suppress a stale stored hash
rather than to choose between real and fake. Songs no longer carry a fabricated
per-album value either; art resolution uses AlbumPrimaryImageTag alone.
2026-07-17 23:28:01 -04:00
Deluan
f0fe070ba1 fix(scanner): cap folder images_updated_at at scan time
A future-stamped image file (clock skew on NAS mounts) previously flowed verbatim
into folder.images_updated_at and from there into the album artwork version, while
the stored blur_hash_updated_at is capped at now on write. The DTO staleness gate
then kept emitting the fake blurhash until wall time caught up with the file mtime.
Capping at the source keeps future values out of the DB entirely; rotation is
preserved because any later change is capped to a later scan time. Capping in the
DTO instead would be worse: the version would become a moving target and the fake
seed would rotate on every request.
2026-07-17 22:47:43 -04:00
Deluan
08d83a7785 fix(persistence): include parent folders in the album artwork version
Multi-disc albums keep their cover in the album-root folder, which the artwork
reader reaches via albumRootParent but which is not in album.folder_ids (only the
disc folders hold media files). A root cover swap therefore advanced the served
cache key without moving the selected artwork version, recreating the stale-hash
deadlock for hash-keyed clients. The version subquery now also considers the
folders' parents. This slightly over-covers (an artist-folder image change can
advance a single-folder album's version), which errs on the side of one spurious
refetch instead of permanent staleness. Plan verified on a 96K-track production
copy: still PK point lookups, outer scan unchanged.
2026-07-17 22:47:42 -04:00
Deluan
9a36047096 fix(artwork): version the resized cache key to backfill blurhashes on upgrade
Resized entries cached by a pre-blurhash version serve straight from the cache:
the resized reader never runs, the original is never read, and the tee never gets
a chance to compute a hash — clients that only request sized images (Jellyfin
maxwidth) would keep receiving the fake blurhash indefinitely for those items.

Versioning the resized cache key makes every post-upgrade sized request miss and
refill. The refill pulls the original through Get, which usually hits the cached
original (original keys are unchanged), so the backfill costs one decode+re-encode
per resized variant with no source or external-provider I/O. Orphaned entries are
evicted by the cache's LRU as usual.
2026-07-17 22:30:38 -04:00
Deluan
07af29fbb4 fix(jellyfin): fold folder image mtimes into the album blurhash version
An in-place cover-file swap followed by a quick scan updates only the folder's
images_updated_at: no tracks are imported, so the album row never moves and
ArtworkUpdatedAt() stayed at the old value. The Jellyfin DTO then kept emitting
the previous stored blurhash, and clients that key their cover caches on it never
refetched the image, so the served-bytes recompute could never run.

The album select now surfaces the newest folder images_updated_at (bare-column
correlated subquery over json_each(folder_ids), so the datetime decltype survives
and scans as time.Time) and ArtworkUpdatedAt() folds it in. Benchmarked on a 96K
track production copy: ~90us/page added, no query-plan change; the subquery is a
PK point lookup per folder with at most two rows to order. Artist images and
playlist sidecars have the same theoretical gap but their timestamps cannot be
derived in SQL; they remain a documented follow-up.
2026-07-17 22:14:13 -04:00
Deluan
2499de2bac perf(artwork): key blurhash dedup by identity, plus review cleanups
The seen map was keyed by the full ArtworkID, which embeds the client token's
LastUpdate: every scan bump rotated the key, so the same-bytes dedup (and its
cheap version re-persist path) never fired in production and stale entries
accumulated forever. The key now zeroes LastUpdate, making the map bounded by
entity count and restoring the tested dedup behavior.

Cleanups from the same review: the base83 encoder is now exported from the
blurhash package and the DTO's duplicate copy is deleted; the always-set
blurHashes field lost its test-shaped nil guards; clearIfStored dropped its
inert version parameter (cleared rows never have their timestamp read); the
teeReader done flag is replaced by nilling the callback; worker-era comments
(async, cache-miss recompute) were updated to the inline design; and the e2e
specs assert directly instead of polling, since the hash is persisted before
the read helpers return.
2026-07-17 21:46:12 -04:00
Deluan
83e9bb8180 refactor(artwork): compute the blurhash inline, drop the background worker
Decode+encode is a few ms (the encoder downscales before its pixel loops), and the
tee fires on Close after the response is fully written, so the hash can be computed
in the serving goroutine: the queue, wake/stop lifecycle, lazy-start admin context,
and the e2e worker-teardown ordering all become unnecessary and are removed. This
also closes two correctness holes the queue had: a deletion signal could be dropped
behind a pending serve job, and buffered image bytes had no global cap.

The in-memory dedup now remembers a checksum of the served bytes plus the persisted
version: identical serves skip the decode and the write, but the same bytes under a
newer entity version re-persist, so blur_hash_updated_at keeps pace with row updates
and the Jellyfin DTO's staleness gate keeps emitting the stored hash after scans.
Placeholder-triggered clears check the seen map, then the stored row, so coverless
entities cost one row read once per process instead of a probe and write per serve.
UpdateBlurHash is a plain UPDATE with no user filtering, so the request context is
used directly (a client abort is survived via context.WithoutCancel).
2026-07-17 21:20:46 -04:00
Deluan
7307fd716b fix(artwork): close the underlying stream from the tee; rename to tee_reader
The tee was built around io.NopCloser(r) and teeCachedStream.Close only closed the
tee, so the underlying CachedStream (an open cache-file fd, or the raw source stream
when the image cache is disabled) was never closed — one fd leaked per teed serve,
enough to exhaust the process limit during a client's initial cover sync. The tee now
wraps the stream directly and its Close propagates; teeCachedStream is gone (all
artwork handlers io.Copy, none Seek). The file is renamed to tee_reader.go since the
wrapper is generic, not blurhash-specific.
2026-07-17 21:13:03 -04:00
Deluan
b63c9b095b test(artwork): cover playlist placeholder-clear via the tee
A playlist that loses its sidecar cover serves the bundled placeholder through
Get; those bytes flow through the tee, the runner recognizes the placeholder, and
clears the stored hash. This exercises the free deletion path (no GetOrPlaceholder
needed, since the playlist reader chain ends in fromAlbumPlaceholder).
2026-07-17 20:36:38 -04:00
Deluan
e8fac4c335 feat(artwork): trigger blurhash from the served-bytes tee
Get wraps an eligible original-size serve (album/artist/playlist) in a teeCachedStream
so the bytes streamed to the client are also captured; on a fully-consumed Close the
runner hashes exactly what was served. GetOrPlaceholder routes a vanished album/artist
cover through EnqueueClearIfGone, since no bytes flow through the tee on ErrUnavailable.
capAtNow keeps a future mtime out of the stored version. The mtime-preserved cover-swap
characterization test (previously pending) now passes, and the disappearing-cover e2e
serves through GetOrPlaceholder to match the real Jellyfin/Subsonic path.
2026-07-17 20:34:47 -04:00
Deluan
f6dd722119 refactor(artwork): compute blurhash from served bytes, drop proxy signals
The worker no longer infers whether the served bytes changed through a stack of
proxy signals (snapshot timestamp vs stored blur_hash_updated_at, freshness guard,
gone bit, idempotent-write skip, computeFromArtwork re-read). It now takes the exact
bytes captured from a serve and is a pure function of them: placeholder clears,
undecodable is left alone, otherwise encode and write with an in-memory last-hash
dedup. Deletion is a checkGone job that re-reads once and clears only if the source
is still gone, so a transient fetch failure can't clobber a valid hash.
2026-07-17 20:34:33 -04:00
Deluan
2169938b30 feat(artwork): add teeReader to capture served artwork bytes
A wrapping io.ReadCloser that mirrors read bytes into a bounded buffer and, on a
fully-consumed Close, hands the captured bytes to a callback. Partial reads and
oversized streams are skipped so the callback only ever receives a complete,
bounded image — the exact bytes the client received. This is the capture side of
the served-bytes blurhash tee.
2026-07-17 19:36:31 -04:00
Deluan
eb5ecabc5a test(artwork): characterize mtime-preserved cover swap staleness (pending)
A cover replaced in place without a mtime change is not re-hashed today: the
freshness guard skips recompute when no timestamp moved, so the stored blurhash
(and the client's cover cache keyed by it) stays stale. Marked pending until the
served-bytes tee lands, which recomputes from the exact bytes served.
2026-07-17 19:35:13 -04:00
Deluan
bf7ae5e82e fix(artwork): cap the blurhash snapshot at now to survive future mtimes
A future-dated artwork file mtime (clock skew, or a file stamped ahead of the
server clock) flowed into the reader's LastUpdated snapshot and was persisted
verbatim as blur_hash_updated_at. Both the worker's freshness guard and the
Jellyfin DTO use a !Before comparison against that timestamp, so a later
legitimate cover change whose row/mtime clock was still behind the future value
would be skipped, pinning the stored hash (and the client's cached cover) until
wall time caught up.

Cap the snapshot at time.Now() in process() before every freshness comparison
and persist, so a real later change always advances past it. Normal past mtimes
(the legitimate 'snapshot exceeds row version' case) are unaffected.
2026-07-17 15:51:01 -04:00
Deluan
5cd75503cb fix(artwork): backfill warm caches and supersede pending gone on refill
Two issues in the fill-triggered blurhash recompute:

1. Enqueuing was gated on a cache miss (!r.Cached). On an upgraded instance the
   image cache is persisted and adopted across restarts, so already-cached
   artwork serves as a cache hit and never enqueued, leaving its migrated-empty
   blur_hash as a synthetic value indefinitely. Enqueue on every original-size
   serve instead: the worker's freshness guard turns already-hashed rows into a
   cheap read and only recomputes when the hash is stale or missing.

2. Enqueue merged the gone flag with a sticky OR, so a cover restored right
   after a missing-art serve kept gone=true and took the clear-and-return path,
   never recomputing. A successful serve proves the artwork exists, so it now
   clears any pending gone for that artwork; a gone that follows a fill still
   sticks.
2026-07-17 15:36:17 -04:00
Deluan
2cd967a456 fix(artwork): keep the stored blurhash on transient recompute errors
process() cleared the stored hash whenever computeFromArtwork returned an
error OR an empty hash. A transient failure (the 30s context timeout, a flaky
cache/DB/reader read) is not evidence the artwork changed, so clearing on it
made the Jellyfin DTO fall back to a fake blurhash and churn clients' cover
caches until a later successful fill restored it.

Split the two outcomes: a compute error now leaves the stored hash intact and
lets a later fill retry, while an empty hash (a placeholder, i.e. the cover is
confirmed gone) still clears it. Deletion witnessed by a failed serve is
already handled separately by the gone path.
2026-07-17 15:18:28 -04:00
Deluan
66d6fdc1a6 test(artwork): stop the blurhash worker before spec TempDir cleanup
The artwork e2e suite stopped the worker via a DeferCleanup registered in
setupHarness's BeforeEach, which Ginkgo runs LAST — after a spec body's own
GinkgoT().TempDir() cleanups. With the cache disabled in these tests, every
artwork serve now enqueues a blurhash recompute, so the worker can still be
reading a spec-local sidecar file when its TempDir is removed. On Windows that
unlink fails ("the process cannot access the file because it is being used by
another process"), which flaked the playlist case-insensitive sidecar spec.

Move the worker shutdown to a suite-level AfterEach, which runs before any
spec-body DeferCleanup, so no artwork file is held open when TempDir removal
runs. Close() is idempotent, so the change is safe across specs.
2026-07-17 15:03:19 -04:00
Deluan
3759488db5 refactor(artwork): trigger blurhash recompute from the cache fill
The blurhash worker previously recomputed on every artwork serve and
reconciled a row-level freshness oracle against serve-time hints (force,
sourceGone, imageUpdatedAt) to decide whether the served bytes had actually
changed. Every staleness bug found in review was one case where that weak
oracle disagreed with the true one, and each fix imported one more serve-time
fragment into it.

Move the trigger to the image-cache fill instead: an original-size cache miss
is exactly when the served bytes change, so the reader's LastUpdated snapshot
is the truth and no reconciliation is needed. Resized fills recurse through
Get(size=0) and hash the original once; a disabled cache reports every original
serve as a fill, keeping real hashes available (the worker's unchanged-hash
guard keeps that write-free).

This deletes the force/sourceGone/imageUpdatedAt flags, the double-freshness
comparison, and the entire negative cache. Only the two irreducible pieces
survive: the placeholder byte-compare and the ErrUnavailable clear-hook
(EnqueueGone), since deletion-without-rescan is invisible to every passive
signal. Adds an e2e test for in-place cover swaps, the scenario that drove the
deleted machinery, now covered structurally by the fill trigger.

Schema, DTO, repositories and the blurhash encoder package are unchanged.
2026-07-17 14:47:01 -04:00
Deluan
ae36e4dfc7 fix(artwork): recompute on original serves when the image cache is disabled
With ImageCacheSize=0 every serve reads live bytes, so an in-place cover
swap without rescan changed the served image with no signal the worker
could see. Original-size serves now force on disabled caches, and a new
unchanged-hash guard skips the DB write, so the forced path costs only the
background decode those installs already pay per request.
2026-07-17 14:13:09 -04:00
Deluan
d0ac427377 ci: disable green-tea GC on the Windows test job
Go 1.26's green-tea GC crashes intermittently on Windows runners: three
distinct runtime fatal-error signatures across 1.26.4/1.26.5, always in
the persistence suite, twice in a row on this PR.
2026-07-17 14:08:44 -04:00
Deluan
7a61776c1c fix(artwork): clear a fresh-looking hash when the serve finds no source
In the window before a rescan records a deleted cover (or after cache
eviction/restart), no row or mtime signal moves, so the freshness skip kept
the stale hash. ErrUnavailable serves now carry a sourceGone signal that
bypasses the skip only while a stored hash remains to clear — afterwards
the negative cache applies, so artwork-less entities still don't re-resolve
per serve. The e2e spec now covers the no-rescan window.
2026-07-17 13:53:08 -04:00
Deluan
a7eec3afc3 fix(artwork): clear the stored hash when the artwork source disappears
A removed cover made Get error with ErrUnavailable before the enqueue, so
the worker never saw the entity and the stale hash kept being emitted. The
unavailable path now enqueues too; the worker's reader signal carries the
folder change and the existing no-result clearing applies. Covered by an
e2e spec exercising the full disappear-and-clear flow.
2026-07-17 13:33:45 -04:00
Deluan
0e74cf0ab1 fix(artwork): only force blurhash recompute on original-size cache misses
Resized cache keys vary per requested size, so a first request for a new
thumbnail size (or an evicted resized entry) forced a recompute with an
unchanged source — wasted work, and a transient failure during it could
clear a valid stored hash. Resized readers re-fetch the original through
Get, so the original-size call still carries the real change signal.
2026-07-17 13:16:07 -04:00
Deluan
9ac2c6a5e3 fix(model): exclude blur hash fields from full-row writes
Scanner and maintenance paths build fresh entities with empty blur hash
fields, so every ordinary refresh erased the computed hash and caused a
double Finamp cover refetch (fake, then real again). The fields are now
read-only projections (structs:"-"): only UpdateBlurHash writes them.
2026-07-17 12:57:33 -04:00
Deluan
c4ca3dca5e fix(artwork): clear the stored hash when a recompute yields no result
A cover deleted or corrupted in place (mtime-only signal, row unchanged)
left the old blur_hash in the DB, and the DTO kept emitting a hash for
artwork no longer served. Since the worker only reaches compute when there
is change evidence, a no-result with a stored hash now clears it, making
the DTO fall back to the rotating fake.
2026-07-17 12:48:36 -04:00
Deluan
3a8505584b fix(artwork): hash the cached artwork bytes, not a fresh source read
Generated playlist mosaics pick albums with random(), so a direct source
read produced a different image than the cached one clients download, and
the persisted blurhash described a mosaic nobody sees. The worker now reads
through the image cache and detects placeholders by byte equality with the
embedded assets (cached reads carry no source path).
2026-07-17 12:27:13 -04:00
Deluan
f9f6d36ebb fix(artwork): TTL for no-result memoization, prompt Close, no warmup force spike
- memoize every no-result outcome (ErrUnavailable can wrap transient agent
  and storage failures, so it is not a reliable definitive/transient
  discriminator) but bound it with a 1h TTL, which also un-poisons entries
  recorded under future file mtimes
- cancel the worker context and check done in the drain loop, so Close
  returns promptly instead of draining the backlog at up to 30s per item
- only force recompute when the image cache is operational: during warmup
  every serve is a miss, which caused a recompute spike at startup
2026-07-17 12:11:30 -04:00
Deluan
43500c0ffe fix(artwork): persist the image freshness signal to stop per-serve recomputes
When a cover file's mtime is newer than the entity row (common), persisting
the row version made the freshness check fail on every serve, re-encoding
and re-writing the same hash each time. The snapshot now stores the newest
signal (row version or image mtime), and both freshness checks accept a
snapshot at-or-after the row version.
2026-07-17 11:59:24 -04:00
Deluan
b040345fb0 fix(artwork): stop the blurhash worker on Close to fix test data races
CI's race detector caught the process-lifetime worker goroutine outliving
Ginkgo specs and touching mocks/fake filesystems being torn down. The
worker now has a stop() that waits for in-flight work, exposed as Close()
on the artwork service; unit suites close it up front (they don't exercise
blurhash), the artwork e2e suite closes it on cleanup.
2026-07-17 11:51:24 -04:00
Deluan
5bdeaad95e perf(artwork): eliminate per-pixel allocations in blurhash encoding
Normalize the downscaled image to *image.RGBA once and read Pix directly
(the image.At interface boxed a color per pixel — ~16k allocs/encode), and
replace per-pixel math.Pow with a 256-entry sRGB-to-linear table. ~72%
faster (3.0ms -> 0.86ms for covers >=300px), 19 allocs/op. Benchmark
included.
2026-07-17 11:33:16 -04:00
Deluan
696399dab7 fix(artwork): don't memoize transient blurhash failures; track image freshness with cache disabled
Only ErrUnavailable (definitively no artwork) is negative-cached; timeouts
and storage/agent hiccups retry on a later serve. Enqueue now carries the
reader's LastUpdated so file swaps are detected even when the image cache
is disabled (where every serve reads the source and miss-forcing is off).
2026-07-17 11:20:41 -04:00
Deluan
9ea4e22ea0 fix(artwork): address PR review bot feedback
- don't record noResult for timed-out/cancelled computations (transient
  failures must not suppress retries for the same artwork version)
- bound the noResult negative cache at 25k entries
- use context.Background for the worker's root context
- add hash:"ignore" to Artist/Playlist blurhash fields for consistency
  with Album (inert today; neither struct is hashed)
2026-07-17 11:13:59 -04:00
Deluan
4d8b486dfd Merge remote-tracking branch 'origin/master' into feat/artwork-blurhash
# Conflicts:
#	model/playlist.go
#	model/playlist_test.go
2026-07-17 11:09:09 -04:00
Deluan
e100c48102 fix(artwork): address blurhash review findings
- force recompute on image-cache miss, so in-place cover/sidecar swaps and
  agent image updates refresh the stored hash even when no entity row moved
- exclude external_info_updated_at from the artwork version: agent TTL
  refreshes bump it with an unchanged image, churning Finamp's cover cache
- lazy-start the worker goroutine and bound each computation with a 30s
  timeout; remember no-result entities per version to avoid re-decoding
  placeholders on every serve
- error (instead of silently skipping) on unknown artwork kinds in persist
2026-07-16 21:52:28 -04:00
Deluan
0b365a0090 refactor(artwork): simplify blurhash cleanup review findings
- detect placeholder artwork via the reader's source path instead of
  comparing against precomputed placeholder hashes (fragile fingerprint,
  dead artist-placeholder branch)
- collapse the three identical UpdateBlurHash repo methods into a shared
  sqlRepository.updateBlurHash helper
2026-07-16 21:52:28 -04:00
Deluan
76e1fba067 test(artwork): e2e coverage for async blurhash persistence 2026-07-16 21:52:28 -04:00
Deluan
585ac0aab3 feat(jellyfin): emit stored blurhashes with version-seeded fake fallback 2026-07-16 21:52:28 -04:00
Deluan
9f9019df07 feat(artwork): compute and persist blurhashes asynchronously on artwork serve 2026-07-16 21:51:04 -04:00
Deluan
f763ebff5b feat(persistence): add UpdateBlurHash targeted update to album/artist/playlist repos 2026-07-16 21:51:04 -04:00
Deluan
a115726e71 feat(model): add blur_hash columns and ArtworkUpdatedAt version methods 2026-07-16 21:51:04 -04:00
Deluan
470b4bdfa0 feat(artwork): add blurhash encoder package 2026-07-16 21:51:04 -04:00
1212 changed files with 30540 additions and 79515 deletions

View file

@ -4,7 +4,7 @@
"dockerfile": "Dockerfile", "dockerfile": "Dockerfile",
"args": { "args": {
// Update the VARIANT arg to pick a version of Go: 1, 1.15, 1.14 // Update the VARIANT arg to pick a version of Go: 1, 1.15, 1.14
"VARIANT": "1.27", "VARIANT": "1.26",
// Options // Options
"INSTALL_NODE": "true", "INSTALL_NODE": "true",
"NODE_VERSION": "v24" "NODE_VERSION": "v24"

6
.github/FUNDING.yml vendored
View file

@ -1,10 +1,10 @@
# These are supported funding model platforms # These are supported funding model platforms
ko_fi: deluan
github: deluan github: deluan
open_collective: navidrome
liberapay: deluan
patreon: # Replace with a single Patreon username patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: deluan
liberapay: deluan
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
issuehunt: # Replace with a single IssueHunt username issuehunt: # Replace with a single IssueHunt username

View file

@ -1,74 +1,98 @@
name: Bug report name: Bug Report
description: Report something that is not working as expected. You do not need to know the cause or how to fix it. description: Before opening a new issue, please search to see if an issue already exists for the bug you encountered.
title: "[Bug]: " title: "[Bug]: "
labels: ["triage"] labels: ["bug", "triage"]
#assignees: #assignees:
# - deluan # - deluan
body: body:
- type: markdown - type: markdown
attributes: attributes:
value: | value: |
Thanks for reporting a problem. For a possible security vulnerability, use [private reporting](https://github.com/navidrome/navidrome/security/advisories/new). ### Thanks for taking the time to fill out this bug report!
- 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) and found no matching open report. - 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
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: Navidrome version label: Version
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. description: What version of Navidrome are you running? (please try upgrading first, as your issue may have been fixed already).
validations: validations:
required: true required: true
- type: textarea - type: textarea
id: expected
attributes: attributes:
label: Expected behavior and why label: Current Behavior
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. description: A concise description of what you're experiencing.
validations: validations:
required: false required: true
- type: textarea - type: textarea
id: steps
attributes: attributes:
label: Steps to reproduce label: Expected Behavior
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. description: A concise description of what you expected to happen.
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: Relevant environment label: Environment
description: >- description: |
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. examples:
validations: - **OS**: Ubuntu 20.04
required: false - **Browser**: Chrome 110.0.5481.177 on Windows 11
- type: textarea - **Client**: DSub 5.5.1
id: config-logs value: |
- OS:
- Browser:
- Client:
render: markdown
- type: dropdown
id: distribution
attributes: attributes:
label: Relevant configuration and logs label: How Navidrome is installed?
description: >- multiple: false
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). options:
- Docker
- Binary (from downloads page)
- Package
- Built from sources
validations: validations:
required: false required: true
- type: textarea - type: textarea
id: additional-context id: config
attributes: attributes:
label: Screenshots or additional context label: Configuration
description: Add screenshots, recordings, links, or other observations that help explain the problem. Remove private information from attachments as well. 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.
validations: render: toml
required: false - type: textarea
id: logs
attributes:
label: Relevant log output
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))
render: shell
- type: textarea
attributes:
label: Anything else?
description: |
Links? References? Anything that will give us more context about the issue you are encountering!
Tip: You can attach screenshots by clicking this area to highlight it and then dragging files in.
- type: checkboxes - type: checkboxes
id: terms id: terms
attributes: attributes:

View file

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

View file

@ -68,11 +68,6 @@ runs:
- name: Set up Docker Buildx - name: Set up Docker Buildx
id: buildx id: buildx
uses: docker/setup-buildx-action@v4 uses: docker/setup-buildx-action@v4
with:
# Runner IPs are shared, so anonymous base image pulls get rate-limited.
buildkitd-config-inline: |
[registry."docker.io"]
mirrors = ["mirror.gcr.io"]
- name: Extract metadata for Docker image - name: Extract metadata for Docker image
id: meta id: meta

View file

@ -1,15 +1,8 @@
> **Before you open this PR:** read the full diff yourself and test the change. Do not submit AI output that you have not reviewed. See [Review your work before opening a PR](https://github.com/navidrome/navidrome/blob/master/CONTRIBUTING.md#review-your-work-before-opening-a-pr).
### Description ### Description
<!-- Please provide a clear and concise description of what this PR does and why it is needed. AI tools may help you draft, edit, or translate it, but review the final text and make sure you agree with it. Please be mindful of the maintainer's time. --> <!-- Please provide a clear and concise description of what this PR does and why it is needed. -->
**AI 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 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. --> <!-- List any related issues, e.g., "Fixes #123" or "Related to #456". -->
### Type of Change ### Type of Change
- [ ] Bug fix - [ ] Bug fix
@ -19,29 +12,27 @@
- [ ] Other (please describe): - [ ] Other (please describe):
### Checklist ### Checklist
Please review and check all that apply. Leave unverified items unchecked and explain them under How to Test. Please review and check all that apply:
- [ ] My code follows the project’s coding style - [ ] My code follows the project’s coding style
- [ ] I have tested the changes locally - [ ] I have tested the changes locally
- [ ] I have added or updated documentation as needed - [ ] I have added or updated documentation as needed
- [ ] I have added tests that prove my fix/feature works (or explain why not) - [ ] I have added tests that prove my fix/feature works (or explain why not)
- [ ] All existing and new tests pass - [ ] All existing and new tests pass
<!-- AI agents: never check the "I personally read and reviewed..." or "For code changes, I have the development knowledge..." boxes for the human. Only the human can make those claims. -->
- [ ] I personally read and reviewed the entire diff and relevant code before opening this PR, and have done the same for every subsequent update, if any.
- [ ] For code changes, I have the development knowledge to understand, test, and maintain the implementation, assess its security and performance implications, and answer review questions.
### How to Test ### How to Test
<!-- Describe the steps to test your changes. Include setup, commands actually run, and results actually observed before and after the change. State how you personally checked the affected functionality. List failed or unrun checks, untested cases, and limitations. --> <!-- Describe the steps to test your changes. Include setup, commands, and expected results. -->
### 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? Where relevant, explain important tradeoffs, new dependencies or ongoing maintenance costs, and simpler alternatives considered. --> <!-- Anything else the maintainer should know? Potential side effects, breaking changes, or areas of concern? -->
<!-- <!--
**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 within the agreed design and scope. - If your PR is large, consider breaking it into smaller PRs.
- Review timing depends on maintainer availability; please do not tag the maintainer for faster review. - Tag the maintainer if you need a prompt 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.
--> -->

View file

@ -1,48 +0,0 @@
#!/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
}
}'

View file

@ -1,60 +0,0 @@
name: Report coverage on PR
on:
workflow_run:
workflows: ['Pipeline: Test, Lint, Build']
types: [completed]
jobs:
comment:
name: Comment coverage report
if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success'
runs-on: ubuntu-latest
permissions:
contents: read
actions: read
pull-requests: write
env:
COVERAGE_COMMENT: 'true'
steps:
# Only the config, from the base branch: this job holds a write token, so
# it must never check out the fork.
- name: Check out the octocov config
uses: actions/checkout@v7
with:
sparse-checkout: .octocov.yml
sparse-checkout-cone-mode: false
persist-credentials: false
# Into a subdirectory. A pull_request run executes the fork's own copy of
# pipeline.yml, so every file in here is attacker-controlled.
- uses: actions/download-artifact@v8
with:
name: octocov-pr
path: untrusted
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ github.token }}
- name: Verify the artifact and take the coverage profile
id: pr
env:
GH_TOKEN: ${{ github.token }}
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
run: |
number=$(head -c 20 untrusted/pr_number | tr -d '[:space:]')
case "$number" in ''|*[!0-9]*)
echo "::error::artifact pr_number is not a number"; exit 1;;
esac
sha=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$number" --jq .head.sha)
if [ "$sha" != "$HEAD_SHA" ]; then
echo "::error::artifact claims PR #$number, but its head $sha is not $HEAD_SHA"; exit 1
fi
cp untrusted/coverage.out coverage.out
echo "number=$number" >> "$GITHUB_OUTPUT"
- uses: k1LoW/octocov-action@v1
env:
# A workflow_run job looks like a push to the default branch. Point
# octocov back at the pull request and at the run that produced it.
GITHUB_PULL_REQUEST_NUMBER: ${{ steps.pr.outputs.number }}
OCTOCOV_GITHUB_REF: refs/pull/${{ steps.pr.outputs.number }}/merge
OCTOCOV_GITHUB_SHA: ${{ github.event.workflow_run.head_sha }}
OCTOCOV_GITHUB_RUN_ID: ${{ github.event.workflow_run.id }}

View file

@ -34,19 +34,16 @@ jobs:
} }
const {data: {artifacts}} = await github.rest.actions.listWorkflowRunArtifacts({owner, repo, run_id}); const {data: {artifacts}} = await github.rest.actions.listWorkflowRunArtifacts({owner, repo, run_id});
const downloadable = artifacts.filter((art) => !art.name.startsWith('octocov-')); if (!artifacts.length) {
if (!downloadable.length) {
return core.error(`No artifacts found`); return core.error(`No artifacts found`);
} }
const header = `Download the artifacts for this pull request:`; let body = `Download the artifacts for this pull request:\n`;
let body = `${header}\n`; for (const art of artifacts) {
for (const art of downloadable) {
body += `\n* [${art.name}.zip](https://nightly.link/${owner}/${repo}/actions/artifacts/${art.id}.zip)`; body += `\n* [${art.name}.zip](https://nightly.link/${owner}/${repo}/actions/artifacts/${art.id}.zip)`;
} }
const {data: comments} = await github.rest.issues.listComments({repo, owner, issue_number}); const {data: comments} = await github.rest.issues.listComments({repo, owner, issue_number});
// Match on the body too: octocov also comments as github-actions[bot]. const existing_comment = comments.find((c) => c.user.login === 'github-actions[bot]');
const existing_comment = comments.find((c) => c.user.login === 'github-actions[bot]' && c.body.startsWith(header));
if (existing_comment) { if (existing_comment) {
core.info(`Updating comment ${existing_comment.id}`); core.info(`Updating comment ${existing_comment.id}`);
await github.rest.issues.updateComment({repo, owner, comment_id: existing_comment.id, body}); await github.rest.issues.updateComment({repo, owner, comment_id: existing_comment.id, body});

View file

@ -1,31 +0,0 @@
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

View file

@ -68,18 +68,12 @@ jobs:
with: with:
go-version-file: go.mod go-version-file: go.mod
# Keep CI on the same version `make lint` installs, so a clean local run
# cannot turn red in CI just because a new golangci-lint was released.
- name: Resolve golangci-lint version
id: golangci-version
run: echo "version=$(grep '^GOLANGCI_LINT_VERSION' Makefile | cut -d ' ' -f 3)" >> "$GITHUB_OUTPUT"
- name: golangci-lint - name: golangci-lint
uses: golangci/golangci-lint-action@v9 uses: golangci/golangci-lint-action@v9
with: with:
version: ${{ steps.golangci-version.outputs.version }} version: latest
problem-matchers: true problem-matchers: true
args: --timeout 3m args: --timeout 2m
- 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,23 +86,8 @@ 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: | run: go generate ./...
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
@ -117,12 +96,6 @@ 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
@ -158,10 +131,8 @@ jobs:
- name: Download dependencies - name: Download dependencies
run: go mod download run: go mod download
# Name must stay unique across the workflow: octocov matches step names - name: Test
# by name across every job, and waits for each match to finish. run: go test -shuffle=on -tags netgo,sqlite_fts5 -race ./... -v
- name: Test with coverage
run: go test -shuffle=on -tags netgo,sqlite_fts5 -race -v -covermode=atomic -coverprofile=coverage.out $(go list ./... | grep -v '/plugins$')
- name: Test ndpgen - name: Test ndpgen
run: | run: |
@ -170,90 +141,15 @@ jobs:
go build -o ndpgen . go build -o ndpgen .
./ndpgen --help ./ndpgen --help
- name: Upload coverage profile
uses: actions/upload-artifact@v7
with:
name: octocov-go
path: coverage.out
if-no-files-found: error
go-plugins:
name: Test Go plugins
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v7
- uses: actions/setup-go@v6
id: setup-go
with:
go-version-file: go.mod
# Without this, the suite recompiles every test plugin WASM module,
# which dominates its runtime under -race.
- name: Cache the WASM compilation cache
uses: actions/cache@v6
with:
path: plugins/testdata/.wazero-cache
key: wazero-${{ runner.os }}-go${{ steps.setup-go.outputs.go-version }}-${{ hashFiles('plugins/testdata/*/*.go', 'plugins/testdata/*/go.*', 'plugins/pdk/go/**/*.go', 'plugins/pdk/go/go.*') }}
restore-keys: wazero-${{ runner.os }}-
- name: Test plugins
run: go tool ginkgo -p -race -tags netgo,sqlite_fts5 --cover --covermode=atomic --coverprofile=coverage.out --output-dir=. ./plugins/
- name: Upload coverage profile
uses: actions/upload-artifact@v7
with:
name: octocov-plugins
path: coverage.out
if-no-files-found: error
coverage:
name: Report coverage
runs-on: ubuntu-latest
needs: [go, go-plugins]
permissions:
contents: read
actions: write
env:
COVERAGE_COMMENT: 'false'
steps:
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
with:
pattern: octocov-*
# Merge here rather than letting octocov do it: octocov reports statement
# coverage for a single profile, but switches to line counting for several.
- name: Merge coverage profiles
run: |
echo "mode: atomic" > coverage.out
awk 'FNR==1 && /^mode:/ {next} {k=$1" "$2; c[k]+=$3} END {for (k in c) print k, c[k]}' \
octocov-*/coverage.out | sort >> coverage.out
- uses: k1LoW/octocov-action@v1
- name: Save the PR number for the comment workflow
if: github.event_name == 'pull_request'
run: echo "${{ github.event.pull_request.number }}" > pr_number
- name: Upload the merged profile for the comment workflow
if: github.event_name == 'pull_request'
uses: actions/upload-artifact@v7
with:
name: octocov-pr
path: |
coverage.out
pr_number
if-no-files-found: error
go-windows: go-windows:
name: Test Go code (Windows) name: Test Go code (Windows)
runs-on: windows-2022 runs-on: windows-2022
env: env:
FFMPEG_VERSION: "7.1" FFMPEG_VERSION: "7.1"
FFMPEG_REPOSITORY: navidrome/ffmpeg-windows-builds FFMPEG_REPOSITORY: navidrome/ffmpeg-windows-builds
# Go 1.26's green-tea GC crashes intermittently on Windows runners (runtime fatal errors in
# the persistence suite, three distinct signatures across 1.26.4/1.26.5).
GOEXPERIMENT: nogreenteagc
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
@ -314,12 +210,12 @@ jobs:
run: go test -shuffle=on -tags netgo,sqlite_fts5 ./... -v run: go test -shuffle=on -tags netgo,sqlite_fts5 ./... -v
- name: Test ndpgen - name: Test ndpgen
shell: bash shell: pwsh
run: | run: |
cd plugins/cmd/ndpgen cd plugins\cmd\ndpgen
go test -shuffle=on -v go test -shuffle=on -v
go build -o ndpgen.exe . go build -o ndpgen.exe .
./ndpgen.exe --help .\ndpgen.exe --help
js: js:
name: Test JS code name: Test JS code
@ -385,7 +281,7 @@ jobs:
build: build:
name: Build name: Build
needs: [js, go, go-plugins, go-windows, go-lint, i18n-lint, git-version, check-push-enabled, validate-migrations] needs: [js, go, go-windows, go-lint, i18n-lint, git-version, check-push-enabled, validate-migrations]
strategy: strategy:
matrix: matrix:
platform: [ 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 ] platform: [ 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 ]
@ -519,18 +415,13 @@ 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 (${{ matrix.repository }}) name: Push to Docker Hub
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
@ -546,7 +437,7 @@ jobs:
id: docker id: docker
with: with:
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
hub_repository: ${{ matrix.repository }} hub_repository: ${{ vars.DOCKER_HUB_REPO }}
hub_username: ${{ secrets.DOCKER_HUB_USERNAME }} hub_username: ${{ secrets.DOCKER_HUB_USERNAME }}
hub_password: ${{ secrets.DOCKER_HUB_PASSWORD }} hub_password: ${{ secrets.DOCKER_HUB_PASSWORD }}
@ -563,7 +454,7 @@ jobs:
- name: Inspect image in Docker Hub - name: Inspect image in Docker Hub
run: | run: |
docker buildx imagetools inspect ${{ matrix.repository }}:${{ steps.docker.outputs.version }} docker buildx imagetools inspect ${{ vars.DOCKER_HUB_REPO }}:${{ steps.docker.outputs.version }}
cleanup-digests: cleanup-digests:
name: Cleanup digest artifacts name: Cleanup digest artifacts
@ -575,7 +466,7 @@ jobs:
env: env:
GH_TOKEN: ${{ github.token }} GH_TOKEN: ${{ github.token }}
run: | run: |
for artifact in $(gh api repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/artifacts | jq -r '.artifacts[] | select(.name | startswith("digests-")) | .id'); do for artifact in $(gh api repos/${{ github.repository }}/actions/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

View file

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

8
.gitignore vendored
View file

@ -40,11 +40,3 @@ openspec/
.agents .agents
go.work* go.work*
.worktrees/ .worktrees/
.playwright-mcp/
# Temp benchmark files
zz_*_test.go
# wazero compilation cache for the plugins test suite
/plugins/testdata/.wazero-cache/
/plugins/testdata/*.stage/

View file

@ -9,144 +9,24 @@ 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
- staticcheck
- thelper
- unconvert - unconvert
- usestdlibvars
- usetesting
- whitespace - whitespace
disable:
- staticcheck
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:
exclude-functions:
- (*github.com/zeebo/xxh3.Hasher).Write
errchkjson:
report-no-exported: true
ginkgolinter:
forbid-focus-container: true
force-expect-to: true
force-succeed: true
force-tonot: true
validate-async-intervals: true
godoclint:
# a doc comment that names another symbol (left behind by a move or a paste) is a bug
default: none
enable:
- start-with-name
options:
start-with-name:
include-unexported: true
gocritic: gocritic:
disable-all: true disable-all: true
enabled-checks: enabled-checks:
@ -157,9 +37,6 @@ 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$'
@ -168,52 +45,18 @@ 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
@ -226,7 +69,6 @@ linters:
- examples$ - examples$
- node_modules - node_modules
- _gen\.go$ - _gen\.go$
- .worktrees
formatters: formatters:
exclusions: exclusions:
generated: lax generated: lax

View file

@ -1,44 +0,0 @@
# Code coverage reporting for pull requests. See https://github.com/k1LoW/octocov
# The 30s default is not enough: scanning this repo's artifacts for the baseline
# eats most of it, leaving none for the report upload.
timeout: 5m
coverage:
# A single pre-merged profile: octocov reports statements for one path, but
# switches to line counting when it merges several itself.
paths:
- coverage.out
# Not code under test: tests/ holds the mocks and helpers, *_gen.go is generated.
# Both patterns need the '**/' prefix: the comment workflow has no source tree,
# so octocov cannot shorten the profile's import paths to repo-relative ones.
exclude:
- '**/tests/**'
- '**/*_gen.go'
codeToTestRatio:
# Needs the pull request's own source, which the comment workflow must not
# check out: it holds a write token.
if: env.COVERAGE_COMMENT != 'true'
code:
- '**/*.go'
- '!**/*_test.go'
- '!**/*_gen.go'
test:
- '**/*_test.go'
testExecutionTime:
if: true
steps:
- Test with coverage
- Test plugins
diff:
datastores:
- artifact://${GITHUB_REPOSITORY}
comment:
# Only the 'Report coverage on PR' workflow sets this: a pull_request run from
# a fork gets a read-only token, so commenting from here 403s.
if: env.COVERAGE_COMMENT == 'true'
updatePrevious: true
summary:
if: true
report:
if: is_default_branch
datastores:
- artifact://${GITHUB_REPOSITORY}

View file

@ -1,72 +1,93 @@
# Navidrome Contribution Guide # Navidrome Contribution Guide
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. 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.
## Support and conduct - [Asking Support Questions](#asking-support-questions)
- [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).
## Issues and ideas ## Asking Support Questions
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.
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. ## Code of Conduct
Please read the following [Code of Conduct](https://github.com/navidrome/navidrome/blob/master/CODE_OF_CONDUCT.md).
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. ## Issues
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.
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). **Before opening a new issue, please check if the issue has not been already made by searching
the [issues](https://github.com/navidrome/navidrome/issues)**
## Agree on the change before implementation ## Pull requests
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.
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. ### Commit Conventions
Each commit message must adhere to the following format:
```
<type>(scope): <description>
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. [optional body]
```
This improves the readability of the messages
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. #### Type
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
## Review your work before opening a PR If there is a breaking change in your Pull Request, please add `BREAKING CHANGE` in the optional body section
Before opening any pull request, including a draft, you must personally read and review the entire diff and the relevant surrounding code, understand the implementation, and verify the affected behavior. This applies when an AI agent writes the code or creates the PR for you. An agent's summary or review does not satisfy this requirement. Personally review each subsequent update and verify its effects before pushing it or asking an agent to push it. A PR that looks like unreviewed AI output may be closed without review. #### Scope
The file or folder where the changes are made. If there are more than one, you can mention any
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. #### Description
A short description of the issue
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. #### Issue number
The issue fixed by this Pull Request.
## AI Disclosure The body is optional. It may contain short description of changes made.
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. Following all the guidelines an ideal commit will look like:
```
git commit --signoff -m "feat(themes): New-theme - #834"
```
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. After committing, push your commits to your forked branch and create a Pull Request from there.
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>
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. Description (What does the pull request do)
An AI agent must never check the personal review or development knowledge boxes in the PR template for you. A non-draft PR from an outside contributor gets the `review-attestation-missing` label and a reminder comment when the personal review box is unchecked, the PR template is missing, or a coding agent account opened the PR. 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.
## UI strings and translations
Add new or changed UI strings in English to `ui/src/i18n/en.json`. You may also add the translation for a language you speak in its file under `resources/i18n/`. Leave the other languages alone, and do not add machine translations for them. Translators update those languages through the [localization process](https://www.navidrome.org/docs/developers/translations/) on POEditor.
<a id="pull-requests"></a>
## Submitting and review
- Check existing [open and closed PRs](https://github.com/navidrome/navidrome/pulls?q=is%3Apr) to avoid duplicate work. If the issue author or another contributor has offered to submit a fix, ask in the issue before you start.
- Use the [development environment instructions](https://www.navidrome.org/docs/developers/dev-environment/). Work on a branch in your fork.
- Complete the [PR template](.github/pull_request_template.md) with the scope agreement or why agreement is not needed, verification evidence, and maintenance implications. Keep each PR focused.
- Follow the [commit conventions and DCO requirements](#commit-conventions-and-dco) below.
Review and merge are discretionary. Proposals may be declined, simplified, split, or deferred. PRs that do not fit Navidrome's direction, the agreed scope, or the maintainer's capacity to maintain them may be closed without detailed code review or prolonged discussion. PRs lacking evidence or left with unresolved questions may also be closed. Agreement to pursue work does not guarantee review or merge. Please do not tag the maintainer, send private messages, or post status requests to obtain faster review.
## Commit conventions and DCO
Use this commit format: `<type>(scope): <description>`, with an optional body.
Allowed types: `feat`, `fix`, `sec`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `revert`, `chore`.
Use a relevant file or folder as the scope and a concise description. Reference the related issue when one exists, and include `BREAKING CHANGE` in the body for breaking changes. Sign off every commit using `git commit --signoff`. These requirements apply equally to AI-assisted work.

View file

@ -2,7 +2,7 @@ FROM --platform=$BUILDPLATFORM ghcr.io/crazy-max/osxcross:14.5-debian AS osxcros
######################################################################################################################## ########################################################################################################################
### Build xx (original image: tonistiigi/xx) ### Build xx (original image: tonistiigi/xx)
FROM --platform=$BUILDPLATFORM alpine:3.22 AS xx-build FROM --platform=$BUILDPLATFORM public.ecr.aws/docker/library/alpine:3.20 AS xx-build
# v1.9.0 # v1.9.0
ENV XX_VERSION=a5592eab7a57895e8d385394ff12241bc65ecd50 ENV XX_VERSION=a5592eab7a57895e8d385394ff12241bc65ecd50
@ -26,7 +26,7 @@ COPY --from=xx-build /out/ /usr/bin/
######################################################################################################################## ########################################################################################################################
### Build Navidrome UI ### Build Navidrome UI
FROM --platform=$BUILDPLATFORM node:lts-alpine AS ui FROM --platform=$BUILDPLATFORM public.ecr.aws/docker/library/node:lts-alpine AS ui
WORKDIR /app WORKDIR /app
# Install node dependencies # Install node dependencies
@ -43,7 +43,7 @@ COPY --from=ui /build /build
######################################################################################################################## ########################################################################################################################
### Build Navidrome binary for Docker image (dynamic musl, enables native libwebp via dlopen) ### Build Navidrome binary for Docker image (dynamic musl, enables native libwebp via dlopen)
FROM --platform=$BUILDPLATFORM golang:1.27-alpine AS build-alpine FROM --platform=$BUILDPLATFORM public.ecr.aws/docker/library/golang:1.26-alpine AS build-alpine
COPY --from=xx / / COPY --from=xx / /
ARG TARGETPLATFORM ARG TARGETPLATFORM
@ -85,7 +85,7 @@ EOT
######################################################################################################################## ########################################################################################################################
### Build Navidrome binary for standalone distribution (static glibc, cross-compiled) ### Build Navidrome binary for standalone distribution (static glibc, cross-compiled)
FROM --platform=$BUILDPLATFORM golang:1.27-trixie AS base FROM --platform=$BUILDPLATFORM public.ecr.aws/docker/library/golang:1.26-trixie AS base
RUN apt-get update && apt-get install -y clang lld RUN apt-get update && apt-get install -y clang lld
COPY --from=xx / / COPY --from=xx / /
WORKDIR /workspace WORKDIR /workspace
@ -152,52 +152,19 @@ RUN xx-verify --static /out/navidrome*
FROM scratch AS binary FROM scratch AS binary
COPY --from=build /out / COPY --from=build /out /
########################################################################################################################
### Build no-op stubs for mpv's video-output libraries
# mpv links libEGL/libgbm for video output only; Navidrome drives it headless, for audio.
# Real mesa pulls in LLVM + gallium (+218MB uncompressed), so ship stubs it never calls.
FROM --platform=$BUILDPLATFORM alpine:3.22 AS mpv-stubs
COPY --from=xx / /
RUN apk add --no-cache clang lld binutils mesa-egl mesa-gbm
ARG TARGETPLATFORM
RUN xx-apk add --no-cache musl-dev
RUN <<EOT
set -e
mkdir -p /out
for so in libEGL.so.1 libgbm.so.1; do
readelf -sW /usr/lib/$so \
| awk '$5 == "GLOBAL" && $7 != "UND" { print $8 }' \
| sed 's/@.*//' \
| grep -vE '^(_init|_fini|_edata|_end|__bss_start|_GLOBAL_OFFSET_TABLE_)$' \
| sort -u \
| awk '{ print "void " $1 "(void) {}" }' > /tmp/stub.c
test -s /tmp/stub.c
xx-clang -shared -nostdlib -fPIC -Wl,-soname,$so -o /out/$so /tmp/stub.c
xx-verify /out/$so
done
EOT
######################################################################################################################## ########################################################################################################################
### Build Final Image ### Build Final Image
FROM alpine:3.22 AS final FROM public.ecr.aws/docker/library/alpine:3.20 AS final
LABEL maintainer="deluan@navidrome.org" LABEL maintainer="deluan@navidrome.org"
LABEL org.opencontainers.image.source="https://github.com/navidrome/navidrome" LABEL org.opencontainers.image.source="https://github.com/navidrome/navidrome"
# Install runtime dependencies # Install runtime dependencies
# - 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, RUN apk add -U --no-cache ffmpeg mpv sqlite libwebp libwebpdemux libwebpmux && \
# otherwise the deleted bytes still ship in the image.
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; \
done && \ done
rm -rf /usr/lib/gallium-pipe /usr/lib/dri \
/usr/lib/libEGL.so* /usr/lib/libgbm.so* /usr/lib/libgallium*.so /usr/lib/libLLVM.so* \
/usr/lib/libGL.so* /usr/lib/libGLESv2.so* /usr/lib/libglapi.so*
COPY --from=mpv-stubs /out/ /usr/lib/
RUN mpv --no-video --ao=null --version > /dev/null
# Copy navidrome binary (musl build for Docker, enables native libwebp) # Copy navidrome binary (musl build for Docker, enables native libwebp)
COPY --from=build-alpine /out/navidrome /app/ COPY --from=build-alpine /out/navidrome /app/

View file

@ -18,13 +18,9 @@ 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 ?= navidrome/navidrome:develop DOCKER_TAG ?= deluan/navidrome:develop
GOLANGCI_LINT_VERSION ?= v2.14.0 GOLANGCI_LINT_VERSION ?= v2.12.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/*")
@ -96,45 +92,6 @@ 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
@ -154,7 +111,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 api-gen ##@Development Run go generate for code generation gen: check_go_env ##@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
@ -223,7 +180,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 `navidrome/navidrome:develop`, override with DOCKER_TAG var. Use IMAGE_PLATFORMS to specify target platforms docker-image: ##@Cross_Compilation Build Docker image, tagged as `deluan/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

View file

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

View file

@ -13,26 +13,15 @@ import (
"strings" "strings"
"github.com/microcosm-cc/bluemonday" "github.com/microcosm-cc/bluemonday"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
) )
const apiBaseURL = "https://api.deezer.com" const apiBaseURL = "https://api.deezer.com"
const authBaseURL = "https://auth.deezer.com" const authBaseURL = "https://auth.deezer.com"
// errCodeQuota is Deezer's "Quota limit exceeded"; it arrives in the body, with HTTP 200 var (
// and no rate-limit headers, so the body code is the only signal. ErrNotFound = errors.New("deezer: not found")
const errCodeQuota = 4 )
type deezerError struct {
Type string `json:"type"`
Message string `json:"message"`
Code int `json:"code"`
}
func (e *deezerError) Error() string {
return fmt.Sprintf("deezer error(%d): %s", e.Code, e.Message)
}
type httpDoer interface { type httpDoer interface {
Do(req *http.Request) (*http.Response, error) Do(req *http.Request) (*http.Response, error)
@ -54,7 +43,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, http.MethodGet, apiBaseURL+"/search/artist", nil) req, err := http.NewRequestWithContext(ctx, "GET", apiBaseURL+"/search/artist", nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -67,7 +56,7 @@ func (c *client) searchArtists(ctx context.Context, name string, limit int) ([]A
} }
if len(results.Data) == 0 { if len(results.Data) == 0 {
return nil, agents.ErrNotFound return nil, ErrNotFound
} }
return results.Data, nil return results.Data, nil
} }
@ -85,35 +74,24 @@ func (c *client) makeRequest(req *http.Request, response any) error {
return err return err
} }
// Checked before the status: a throttled request still answers 200, and decoding its body if resp.StatusCode != 200 {
// into a result type yields an empty one, which reads as "nothing found". return c.parseError(data)
if err := parseBodyError(data); err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("deezer http status: (%d)", resp.StatusCode)
} }
return json.Unmarshal(data, response) return json.Unmarshal(data, response)
} }
// parseBodyError returns the error Deezer reported in the body, or nil when it reported none. func (c *client) parseError(data []byte) error {
func parseBodyError(data []byte) error { var deezerError Error
var body errorResponse err := json.Unmarshal(data, &deezerError)
// Discarded: a payload that is not an error object leaves Error nil, which is the "none" answer. if err != nil {
_ = json.Unmarshal(data, &body) return err
switch {
case body.Error == nil:
return nil
case body.Error.Code == errCodeQuota:
return errors.Join(body.Error, agents.ErrRetryLater)
default:
return body.Error
} }
return fmt.Errorf("deezer error(%d): %s", deezerError.Error.Code, deezerError.Error.Message)
} }
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, http.MethodGet, fmt.Sprintf("%s/artist/%d/related", apiBaseURL, artistID), nil) req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("%s/artist/%d/related", apiBaseURL, artistID), nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -130,7 +108,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, http.MethodGet, fmt.Sprintf("%s/artist/%d/top", apiBaseURL, artistID), nil) req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("%s/artist/%d/top", apiBaseURL, artistID), nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -174,7 +152,7 @@ func (c *client) getArtistBio(ctx context.Context, artistID int, lang string) (s
return "", err return "", err
} }
req, err := http.NewRequestWithContext(ctx, http.MethodPost, pipeAPIURL, bytes.NewReader(body)) req, err := http.NewRequestWithContext(ctx, "POST", pipeAPIURL, bytes.NewReader(body))
if err != nil { if err != nil {
return "", err return "", err
} }
@ -190,7 +168,7 @@ func (c *client) getArtistBio(ctx context.Context, artistID int, lang string) (s
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != 200 {
return "", fmt.Errorf("deezer: failed to fetch biography: %s", resp.Status) return "", fmt.Errorf("deezer: failed to fetch biography: %s", resp.Status)
} }

View file

@ -43,7 +43,7 @@ func (c *client) getJWT(ctx context.Context) (string, error) {
} }
// Fetch a new anonymous token // Fetch a new anonymous token
req, err := http.NewRequestWithContext(ctx, http.MethodGet, authBaseURL+"/login/anonymous?jo=p&rto=c", nil) req, err := http.NewRequestWithContext(ctx, "GET", 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 != http.StatusOK { if resp.StatusCode != 200 {
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"` JWT string `json:"jwt"` //nolint:gosec
} }
var result authResponse var result authResponse

View file

@ -20,9 +20,9 @@ var _ = Describe("JWT Authentication", func() {
var ctx context.Context var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context()
httpClient = &fakeHttpClient{} httpClient = &fakeHttpClient{}
client = newClient(httpClient) client = newClient(httpClient)
ctx = context.Background()
}) })
Describe("getJWT", func() { Describe("getJWT", func() {
@ -30,32 +30,32 @@ var _ = Describe("JWT Authentication", func() {
It("successfully fetches and caches a JWT token", func() { It("successfully fetches and caches a JWT token", func() {
testJWT := createTestJWT(5 * time.Minute) testJWT := createTestJWT(5 * time.Minute)
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: http.StatusOK, StatusCode: 200,
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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: http.StatusOK, StatusCode: 200,
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature()) testJWT, err := jwt.Sign(testToken, jwt.WithInsecureNoSignature())
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: http.StatusOK, StatusCode: 200,
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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: http.StatusOK, StatusCode: 200,
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: http.StatusOK, StatusCode: 200,
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: http.StatusOK, StatusCode: 200,
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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: http.StatusInternalServerError, StatusCode: 500,
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: http.StatusOK, StatusCode: 200,
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: http.StatusOK, StatusCode: 200,
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: http.StatusOK, StatusCode: 200,
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
// 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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{ httpClient.mock("https://auth.deezer.com/login/anonymous", http.Response{
StatusCode: http.StatusOK, StatusCode: 200,
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: http.StatusOK, StatusCode: 200,
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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: http.StatusOK, StatusCode: 200,
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
Expect(token2).To(Equal(secondJWT)) Expect(token2).To(Equal(secondJWT))
Expect(token2).ToNot(Equal(token1)) Expect(token2).ToNot(Equal(token1))
}) })
@ -280,12 +280,15 @@ 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()
Expect(err).ToNot(HaveOccurred()) if err != nil {
panic(fmt.Sprintf("failed to create test JWT: %v", err))
}
signed, err := jwt.Sign(token, jwt.WithInsecureNoSignature()) signed, err := jwt.Sign(token, jwt.WithInsecureNoSignature())
Expect(err).ToNot(HaveOccurred()) if err != nil {
panic(fmt.Sprintf("failed to sign test JWT: %v", err))
}
return string(signed) return string(signed)
} }

View file

@ -2,14 +2,12 @@ package deezer
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"os" "os"
"time" "time"
"github.com/navidrome/navidrome/core/agents"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
) )
@ -26,11 +24,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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: http.StatusOK}) httpClient.mock("https://api.deezer.com/search/artist", http.Response{Body: f, StatusCode: 200})
artists, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20) artists, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20)
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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,53 +36,23 @@ 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: http.StatusOK, StatusCode: 200,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)), Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
}) })
_, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20) _, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20)
Expect(err).To(MatchError(agents.ErrNotFound)) Expect(err).To(MatchError(ErrNotFound))
})
// Deezer answers 200 with no rate-limit headers when throttling, so this body is the only signal.
It("reports an exhausted quota as a retryable error, not as a missing artist", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(
`{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)),
})
_, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20)
Expect(err).To(HaveOccurred())
Expect(err).ToNot(MatchError(agents.ErrNotFound),
"a throttled lookup would otherwise settle the artist as having no image")
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
Expect(err.Error()).To(ContainSubstring("Quota limit exceeded"))
})
It("reports a non-quota body error as a plain error", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(
`{"error":{"type":"Exception","message":"Invalid query","code":100}}`)),
})
_, err := client.searchArtists(GinkgoT().Context(), "Michael Jackson", 20)
Expect(err).To(HaveOccurred())
Expect(err).ToNot(MatchError(agents.ErrNotFound))
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeFalse(),
"only a throttle asks the caller to come back later")
}) })
}) })
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: http.StatusOK}) httpClient.mock("https://api.deezer.com/artist/27/top", http.Response{Body: f, StatusCode: 200})
tracks, err := client.getTopTracks(GinkgoT().Context(), 27, 5) tracks, err := client.getTopTracks(GinkgoT().Context(), 27, 5)
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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 +72,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: http.StatusOK, StatusCode: 200,
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK}) httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
bio, err := client.getArtistBio(GinkgoT().Context(), 27, "en") bio, err := client.getArtistBio(GinkgoT().Context(), 27, "en")
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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 +91,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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK}) httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
_, err = client.getArtistBio(GinkgoT().Context(), 27, "fr") _, err = client.getArtistBio(GinkgoT().Context(), 27, "fr")
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: http.StatusOK}) httpClient.mock("https://pipe.deezer.com/api", http.Response{Body: f, StatusCode: 200})
_, err = client.getArtistBio(GinkgoT().Context(), 27, "en") _, err = client.getArtistBio(GinkgoT().Context(), 27, "en")
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
// 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 +131,7 @@ var _ = Describe("client", func() {
] ]
}` }`
httpClient.mock("https://pipe.deezer.com/api", http.Response{ httpClient.mock("https://pipe.deezer.com/api", http.Response{
StatusCode: http.StatusOK, StatusCode: 200,
Body: io.NopCloser(bytes.NewBufferString(errorResponse)), Body: io.NopCloser(bytes.NewBufferString(errorResponse)),
}) })
@ -185,7 +153,7 @@ var _ = Describe("client", func() {
} }
}` }`
httpClient.mock("https://pipe.deezer.com/api", http.Response{ httpClient.mock("https://pipe.deezer.com/api", http.Response{
StatusCode: http.StatusOK, StatusCode: 200,
Body: io.NopCloser(bytes.NewBufferString(emptyBioResponse)), Body: io.NopCloser(bytes.NewBufferString(emptyBioResponse)),
}) })
@ -195,7 +163,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: http.StatusInternalServerError, StatusCode: 500,
Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":"Internal server error"}`)),
}) })
@ -208,7 +176,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: http.StatusOK, StatusCode: 200,
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,6 +206,5 @@ 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
} }
Fail("URL not mocked: " + u.String()) panic("URL not mocked: " + u.String())
return nil, nil
} }

View file

@ -1,11 +1,10 @@
package deezer package deezer
import ( import (
"cmp"
"context" "context"
"errors" "errors"
"fmt" "fmt"
"slices" "net/http"
"strings" "strings"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
@ -14,7 +13,6 @@ import (
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils/cache" "github.com/navidrome/navidrome/utils/cache"
"github.com/navidrome/navidrome/utils/httpclient"
"github.com/navidrome/navidrome/utils/slice" "github.com/navidrome/navidrome/utils/slice"
) )
@ -34,9 +32,11 @@ 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 := &http.Client{
Timeout: consts.DefaultHttpClientTimeOut,
} }
httpClient := httpclient.New(consts.DefaultHttpClientTimeOut)
cachedHttpClient := cache.NewHTTPClient(httpClient, consts.DefaultHttpClientTimeOut) cachedHttpClient := cache.NewHTTPClient(httpClient, consts.DefaultHttpClientTimeOut)
agent.client = newClient(cachedHttpClient) agent.client = newClient(cachedHttpClient)
return agent return agent
@ -68,29 +68,21 @@ func (s *deezerAgent) GetArtistImages(ctx context.Context, _, name, _ string) ([
{artist.PictureSmall, deezerApiPictureSmallSize}, {artist.PictureSmall, deezerApiPictureSmallSize},
} }
for _, imgData := range possibleImages { for _, imgData := range possibleImages {
if imgData.URL != "" && !isPlaceholderPicture(imgData.URL) { if imgData.URL != "" {
res = append(res, agents.ExternalImage{ res = append(res, agents.ExternalImage{
URL: imgData.URL, URL: imgData.URL,
Size: imgData.Size, Size: imgData.Size,
}) })
} }
} }
if len(res) == 0 {
return nil, agents.ErrNotFound
}
return res, nil return res, nil
} }
// deezerEmptyPicturePath is Deezer's empty-image-id path shape for artists with no picture
// (…/images/artist//1000x1000-…), which serves a generic silhouette on any CDN host.
const deezerEmptyPicturePath = "/images/artist//"
func isPlaceholderPicture(url string) bool {
return strings.Contains(url, deezerEmptyPicturePath)
}
func (s *deezerAgent) searchArtist(ctx context.Context, name string) (*Artist, error) { func (s *deezerAgent) searchArtist(ctx context.Context, name string) (*Artist, error) {
artists, err := s.client.searchArtists(ctx, name, deezerArtistSearchLimit) artists, err := s.client.searchArtists(ctx, name, deezerArtistSearchLimit)
if errors.Is(err, ErrNotFound) || len(artists) == 0 {
return nil, agents.ErrNotFound
}
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -103,32 +95,13 @@ func (s *deezerAgent) searchArtist(ctx context.Context, name string) (*Artist, e
} }
} }
// Deezer's RANKING order isn't reliable for homonyms: rank name matches // If the first one has the same name, that's the one
// ahead of non-matches, prefer an exact-case match, then the most fans. if !strings.EqualFold(artists[0].Name, name) {
rank := func(a Artist) int { log.Trace(ctx, "Top artist do not match", "searched_name", name, "found_name", artists[0].Name)
switch {
case a.Name == name:
return 2
case strings.EqualFold(a.Name, name):
return 1
default:
return 0
}
}
slices.SortFunc(artists, func(a, b Artist) int {
return cmp.Or(
cmp.Compare(rank(b), rank(a)),
cmp.Compare(b.NbFan, a.NbFan),
cmp.Compare(a.ID, b.ID),
)
})
best := artists[0]
if !strings.EqualFold(best.Name, name) {
log.Trace(ctx, "No artist matched the searched name", "searched_name", name, "found_name", artists[0].Name)
return nil, agents.ErrNotFound return nil, agents.ErrNotFound
} }
log.Trace(ctx, "Found artist", "name", best.Name, "id", best.ID, "link", best.Link, "nb_fan", best.NbFan) log.Trace(ctx, "Found artist", "name", artists[0].Name, "id", artists[0].ID, "link", artists[0].Link)
return new(best), nil return &artists[0], err
} }
func (s *deezerAgent) GetSimilarArtists(ctx context.Context, _, name, _ string, limit int) ([]agents.Artist, error) { func (s *deezerAgent) GetSimilarArtists(ctx context.Context, _, name, _ string, limit int) ([]agents.Artist, error) {
@ -192,7 +165,7 @@ func (s *deezerAgent) GetArtistBiography(ctx context.Context, _, name, _ string)
func init() { func init() {
conf.AddHook(func() { conf.AddHook(func() {
if conf.Server().Deezer.Enabled { if conf.Server.Deezer.Enabled {
agents.Register(deezerAgentName, deezerConstructor) agents.Register(deezerAgentName, deezerConstructor)
} }
}) })

View file

@ -3,7 +3,6 @@ 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"
@ -16,5 +15,3 @@ func TestDeezer(t *testing.T) {
RegisterFailHandler(Fail) RegisterFailHandler(Fail)
RunSpecs(t, "Deezer Test Suite") RunSpecs(t, "Deezer Test Suite")
} }
var _ = configtest.RestoreAfterEachSpec()

View file

@ -3,7 +3,6 @@ package deezer
import ( import (
"bytes" "bytes"
"context" "context"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -11,8 +10,9 @@ 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/model" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
) )
@ -21,140 +21,19 @@ var _ = Describe("deezerAgent", func() {
var ctx context.Context var ctx context.Context
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context() ctx = context.Background()
conf.Update(func(c *conf.Options) { c.Deezer.Enabled = true }) DeferCleanup(configtest.SetupConfig())
conf.Server.Deezer.Enabled = true
}) })
Describe("deezerConstructor", func() { Describe("deezerConstructor", func() {
It("uses configured languages", func() { It("uses configured languages", func() {
conf.Update(func(c *conf.Options) { c.Deezer.Languages = []string{"pt", "en"} }) conf.Server.Deezer.Languages = []string{"pt", "en"}
agent := deezerConstructor(struct{ model.DataStore }{}).(*deezerAgent) agent := deezerConstructor(&tests.MockDataStore{}).(*deezerAgent)
Expect(agent.languages).To(Equal([]string{"pt", "en"})) Expect(agent.languages).To(Equal([]string{"pt", "en"}))
}) })
}) })
Describe("searchArtist", func() {
var agent *deezerAgent
var httpClient *fakeHttpClient
BeforeEach(func() {
httpClient = &fakeHttpClient{}
agent = &deezerAgent{
client: newClient(httpClient),
}
})
It("picks the exact-name match with the most fans when several share the name", func() {
// Deezer RANKING order returns a low-popularity homonym first (see issue #5802)
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":61045802,"name":"Queen","nb_fan":75},
{"id":141954732,"name":"Queen","nb_fan":397},
{"id":135041032,"name":"Queen(Ares)","nb_fan":133},
{"id":183179807,"name":"Queen","nb_fan":53},
{"id":412,"name":"Queen","nb_fan":12744378}
],"total":5}`)),
})
artist, err := agent.searchArtist(ctx, "Queen")
Expect(err).ToNot(HaveOccurred())
Expect(artist.ID).To(Equal(412))
})
It("matches the name case-insensitively", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":1,"name":"QUEEN","nb_fan":10},
{"id":2,"name":"queen","nb_fan":20}
],"total":2}`)),
})
artist, err := agent.searchArtist(ctx, "Queen")
Expect(err).ToNot(HaveOccurred())
Expect(artist.ID).To(Equal(2))
})
// The artwork worker settles an artist as "no image" on agents.ErrNotFound, so a throttled
// lookup reaching that here would record a permanent absence.
It("surfaces an exhausted quota instead of reporting the artist as not found", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(
`{"error":{"type":"Exception","message":"Quota limit exceeded","code":4}}`)),
})
_, err := agent.searchArtist(ctx, "Queen")
Expect(err).To(HaveOccurred())
Expect(err).ToNot(MatchError(agents.ErrNotFound))
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
})
It("returns ErrNotFound when no result matches the name exactly", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":1,"name":"Queens of the Stone Age","nb_fan":100}
],"total":1}`)),
})
_, err := agent.searchArtist(ctx, "Queen")
Expect(err).To(MatchError(agents.ErrNotFound))
})
})
Describe("GetArtistImages", func() {
var agent *deezerAgent
var httpClient *fakeHttpClient
BeforeEach(func() {
httpClient = &fakeHttpClient{}
agent = &deezerAgent{
client: newClient(httpClient),
}
})
It("returns the real images when the artist has a picture", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":412,"name":"Queen","nb_fan":12744378,
"picture_xl":"https://cdn-images.dzcdn.net/images/artist/abc/1000x1000-000000-80-0-0.jpg",
"picture_big":"https://cdn-images.dzcdn.net/images/artist/abc/500x500-000000-80-0-0.jpg"}
],"total":1}`)),
})
images, err := agent.GetArtistImages(ctx, "", "Queen", "")
Expect(err).ToNot(HaveOccurred())
Expect(images).To(HaveLen(2))
Expect(images[0].URL).To(ContainSubstring("1000x1000"))
})
It("returns ErrNotFound when the artist only has empty-id placeholder pictures", func() {
httpClient.mock("https://api.deezer.com/search/artist", http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[
{"id":412,"name":"Queen","nb_fan":12744378,
"picture_xl":"https://cdn-images.dzcdn.net/images/artist//1000x1000-000000-80-0-0.jpg",
"picture_big":"https://cdn-images.dzcdn.net/images/artist//500x500-000000-80-0-0.jpg",
"picture_medium":"https://cdn-images.dzcdn.net/images/artist//250x250-000000-80-0-0.jpg",
"picture_small":"https://cdn-images.dzcdn.net/images/artist//56x56-000000-80-0-0.jpg"}
],"total":1}`)),
})
images, err := agent.GetArtistImages(ctx, "", "Queen", "")
Expect(err).To(MatchError(agents.ErrNotFound))
Expect(images).To(BeEmpty())
})
})
Describe("GetArtistBiography - Language Fallback", func() { Describe("GetArtistBiography - Language Fallback", func() {
var agent *deezerAgent var agent *deezerAgent
var httpClient *langAwareHttpClient var httpClient *langAwareHttpClient
@ -164,19 +43,20 @@ 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: http.StatusOK} httpClient.searchResponse = &http.Response{Body: fSearch, StatusCode: 200}
// 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: http.StatusOK, StatusCode: 200,
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.Update(func(c *conf.Options) { c.Deezer.Languages = languages }) conf.Server.Deezer.Languages = languages
agent = &deezerAgent{ agent = &deezerAgent{
dataStore: &tests.MockDataStore{},
client: newClient(httpClient), client: newClient(httpClient),
languages: languages, languages: languages,
} }
@ -187,7 +67,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: http.StatusOK} httpClient.bioResponses["fr"] = &http.Response{Body: fFr, StatusCode: 200}
bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "") bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
@ -202,10 +82,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: http.StatusOK} httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: 200}
// 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: http.StatusOK} httpClient.bioResponses["en"] = &http.Response{Body: fEn, StatusCode: 200}
bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "") bio, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
@ -221,9 +101,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: http.StatusOK} httpClient.bioResponses["ja"] = &http.Response{Body: fJa, StatusCode: 200}
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: http.StatusOK} httpClient.bioResponses["xx"] = &http.Response{Body: fXx, StatusCode: 200}
_, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "") _, err := agent.GetArtistBiography(ctx, "", "Michael Jackson", "")
@ -256,7 +136,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: http.StatusOK, StatusCode: 200,
Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)), Body: io.NopCloser(bytes.NewBufferString(`{"data":[],"total":0}`)),
}, nil }, nil
} }
@ -267,7 +147,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: http.StatusInternalServerError, StatusCode: 500,
Body: io.NopCloser(bytes.NewBufferString(`{"error":"no mock"}`)), Body: io.NopCloser(bytes.NewBufferString(`{"error":"no mock"}`)),
}, nil }, nil
} }
@ -282,11 +162,10 @@ 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: http.StatusOK, StatusCode: 200,
Body: io.NopCloser(bytes.NewBufferString(`{"data":{"artist":{"bio":{"full":""}}}}`)), Body: io.NopCloser(bytes.NewBufferString(`{"data":{"artist":{"bio":{"full":""}}}}`)),
}, nil }, nil
} }
Fail("URL not mocked: " + req.URL.String()) panic("URL not mocked: " + req.URL.String())
return nil, nil
} }

View file

@ -22,8 +22,12 @@ type Artist struct {
Type string `json:"type"` Type string `json:"type"`
} }
type errorResponse struct { type Error struct {
Error *deezerError `json:"error"` Error struct {
Type string `json:"type"`
Message string `json:"message"`
Code int `json:"code"`
} `json:"error"`
} }
type RelatedArtists struct { type RelatedArtists struct {

View file

@ -13,9 +13,9 @@ var _ = Describe("Responses", func() {
It("parses the artist search result correctly ", func() { It("parses the artist search result correctly ", func() {
var resp SearchArtistResults var resp SearchArtistResults
body, err := os.ReadFile("tests/fixtures/deezer.search.artist.json") body, err := os.ReadFile("tests/fixtures/deezer.search.artist.json")
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
err = json.Unmarshal(body, &resp) err = json.Unmarshal(body, &resp)
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
Expect(resp.Data).To(HaveLen(17)) Expect(resp.Data).To(HaveLen(17))
michael := resp.Data[0] michael := resp.Data[0]
@ -26,10 +26,10 @@ var _ = Describe("Responses", func() {
Describe("Error", func() { Describe("Error", func() {
It("parses the error response correctly", func() { It("parses the error response correctly", func() {
var errorResp errorResponse var errorResp Error
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
err = json.Unmarshal(body, &resp) err = json.Unmarshal(body, &resp)
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
err = json.Unmarshal(body, &resp) err = json.Unmarshal(body, &resp)
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
Expect(resp.Data).To(HaveLen(5)) Expect(resp.Data).To(HaveLen(5))
track := resp.Data[0] track := resp.Data[0]

View file

@ -20,13 +20,13 @@ func (t testFileInfo) BirthTime() time.Time {
if ts := times.Get(t.FileInfo); ts.HasBirthTime() { if ts := times.Get(t.FileInfo); ts.HasBirthTime() {
return ts.BirthTime() return ts.BirthTime()
} }
return t.ModTime() return t.FileInfo.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{
Name: name, SortArtistName: sortName, MbzArtistID: mbid, Artist: model.Artist{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(model.Library{ID: 1}, "folderID")) return new(metadata.ToMediaFile(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).ToNot(HaveOccurred()) Expect(err).To(Not(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(BeEmpty()) Expect(actual).To(HaveLen(0))
continue continue
} }

View file

@ -246,7 +246,7 @@ func parseASFAttributes(rawAttrs map[string][]string, tags map[string][]string)
} }
} }
// tiplMapping lists the only roles we support, based on Picard's tag map: // These are the only roles we support, based on Picard's tag map:
// https://picard-docs.musicbrainz.org/downloads/MusicBrainz_Picard_Tag_Map.html // https://picard-docs.musicbrainz.org/downloads/MusicBrainz_Picard_Tag_Map.html
var tiplMapping = map[string]string{ var tiplMapping = map[string]string{
"arranger": "arranger", "arranger": "arranger",

View file

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

View file

@ -18,7 +18,6 @@ import (
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils/cache" "github.com/navidrome/navidrome/utils/cache"
"github.com/navidrome/navidrome/utils/httpclient"
"golang.org/x/net/html" "golang.org/x/net/html"
) )
@ -49,19 +48,20 @@ 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 := &http.Client{
Timeout: consts.DefaultHttpClientTimeOut,
}
chc := cache.NewHTTPClient(hc, consts.DefaultHttpClientTimeOut) chc := cache.NewHTTPClient(hc, consts.DefaultHttpClientTimeOut)
l.httpClient = chc l.httpClient = chc
l.client = newClient(l.apiKey, l.secret, chc) l.client = newClient(l.apiKey, l.secret, chc)
@ -93,7 +93,7 @@ func (l *lastfmAgent) GetAlbumInfo(ctx context.Context, name, artist, mbid strin
var resp agents.AlbumInfo var resp agents.AlbumInfo
for _, lang := range l.languages { for _, lang := range l.languages {
var err error var err error
a, err = l.callAlbumGetInfo(ctx, name, artist, lang) a, err = l.callAlbumGetInfo(ctx, name, artist, mbid, lang)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -114,7 +114,7 @@ func (l *lastfmAgent) GetAlbumInfo(ctx context.Context, name, artist, mbid strin
} }
func (l *lastfmAgent) GetAlbumImages(ctx context.Context, name, artist, mbid string) ([]agents.ExternalImage, error) { func (l *lastfmAgent) GetAlbumImages(ctx context.Context, name, artist, mbid string) ([]agents.ExternalImage, error) {
a, err := l.callAlbumGetInfo(ctx, name, artist, l.languages[0]) a, err := l.callAlbumGetInfo(ctx, name, artist, mbid, l.languages[0])
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -242,10 +242,6 @@ 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) {
@ -272,9 +268,7 @@ 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 {
// A real artist page always has og:image; its absence means a bot challenge or a redesign. return res, nil
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" {
@ -292,18 +286,22 @@ func (l *lastfmAgent) GetArtistImages(ctx context.Context, _, name, mbid string)
return res, nil return res, nil
} }
// callAlbumGetInfo matches on name+artist only. Last.fm's album.getInfo by MBID is unreliable — func (l *lastfmAgent) callAlbumGetInfo(ctx context.Context, name, artist, mbid string, lang string) (*Album, error) {
// a correct MBID can return a different album (or none) — so the MBID is deliberately not passed. a, err := l.client.albumGetInfo(ctx, name, artist, mbid, lang)
func (l *lastfmAgent) callAlbumGetInfo(ctx context.Context, name, artist, lang string) (*Album, error) { var lfErr *lastFMError
a, err := l.client.albumGetInfo(ctx, name, artist, "", lang) isLastFMError := errors.As(err, &lfErr)
if err != nil {
if lfErr, ok := errors.AsType[*lastFMError](err); ok && lfErr.Code == 6 { if mbid != "" && (isLastFMError && lfErr.Code == 6) {
// A not-found is a definitive absence, not a fault: return the shared sentinel so the log.Debug(ctx, "LastFM/album.getInfo could not find album by mbid, trying again", "album", name, "mbid", mbid)
// artwork worker's breaker/transient checks don't retry it, and log it at Debug. return l.callAlbumGetInfo(ctx, name, artist, "", lang)
log.Debug(ctx, "Album not found in Last.fm", "album", name, "artist", artist) }
return nil, agents.ErrNotFound
if err != nil {
if isLastFMError && lfErr.Code == 6 {
log.Debug(ctx, "Album not found", "album", name, "mbid", mbid, err)
} else {
log.Error(ctx, "Error calling LastFM/album.getInfo", "album", name, "mbid", mbid, err)
} }
log.Error(ctx, "Error calling LastFM/album.getInfo", "album", name, "artist", artist, err)
return nil, err return nil, err
} }
return a, nil return a, nil
@ -315,12 +313,6 @@ func (l *lastfmAgent) callArtistGetInfo(ctx context.Context, name string, lang s
a, err := l.client.artistGetInfo(ctx, name, lang) a, err := l.client.artistGetInfo(ctx, name, lang)
if err != nil { if err != nil {
if lfErr, ok := errors.AsType[*lastFMError](err); ok && lfErr.Code == 6 {
// A not-found is a definitive absence, not a fault: return the shared sentinel so it
// doesn't trip the artwork worker's breaker, and log at Debug instead of Error.
log.Debug(ctx, "Artist not found in Last.fm", "artist", name)
return nil, agents.ErrNotFound
}
log.Error(ctx, "Error calling LastFM/artist.getInfo", "artist", name, err) log.Error(ctx, "Error calling LastFM/artist.getInfo", "artist", name, err)
return nil, err return nil, err
} }
@ -355,7 +347,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
@ -389,11 +381,10 @@ 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 <= float32(conf.Server().LastFM.MinScrobbleDuration.Seconds()) { if s.Duration <= 30 {
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,
@ -413,8 +404,7 @@ func (l *lastfmAgent) Scrobble(ctx context.Context, userId string, s scrobbler.S
log.Warn(ctx, "Last.fm client.scrobble returned error", "track", s.Title, err) log.Warn(ctx, "Last.fm client.scrobble returned error", "track", s.Title, err)
return errors.Join(err, scrobbler.ErrRetryLater) return errors.Join(err, scrobbler.ErrRetryLater)
} }
// 11: service offline; 16: temporarily unavailable. Rate limiting is mapped by the client. if lfErr.Code == 11 || lfErr.Code == 16 {
if lfErr.Code == 11 || lfErr.Code == 16 || errors.Is(err, scrobbler.ErrRetryLater) {
return errors.Join(err, scrobbler.ErrRetryLater) return errors.Join(err, scrobbler.ErrRetryLater)
} }
return errors.Join(err, scrobbler.ErrUnrecoverable) return errors.Join(err, scrobbler.ErrUnrecoverable)
@ -432,16 +422,22 @@ 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 {
if !lastFMEnabled() { // This is a workaround for the fact that a (Interface)(nil) is not the same as a (*lastfmAgent)(nil)
return nil // See https://go.dev/doc/faq#nil_error
a := lastFMConstructor(ds)
if a != nil {
return a
} }
return lastFMConstructor(ds) return nil
}) })
scrobbler.Register(lastFMAgentName, func(ds model.DataStore) scrobbler.Scrobbler { scrobbler.Register(lastFMAgentName, func(ds model.DataStore) scrobbler.Scrobbler {
if !lastFMEnabled() { // Same as above - this is a workaround for the fact that a (Scrobbler)(nil) is not the same as a (*lastfmAgent)(nil)
// See https://go.dev/doc/faq#nil_error
a := lastFMConstructor(ds)
if a != nil {
return a
}
return nil return nil
}
return lastFMConstructor(ds)
}) })
}) })
} }

View file

@ -12,11 +12,10 @@ import (
"time" "time"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/scrobbler" "github.com/navidrome/navidrome/core/scrobbler"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -31,39 +30,41 @@ 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 = persistence.New(db.Db()) 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.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"pt", "en"} }) conf.Server.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() {
@ -78,7 +79,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
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"))
@ -93,21 +94,12 @@ 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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
_, 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))
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("U2")) Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("U2"))
}) })
It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)),
StatusCode: http.StatusOK,
}
_, err := agent.GetArtistBiography(ctx, "123", "U2", "")
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
})
}) })
Describe("Language Fallback", func() { Describe("Language Fallback", func() {
@ -120,13 +112,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.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"pt", "en"} }) conf.Server.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: http.StatusOK} httpClient.responses["pt"] = http.Response{Body: f, StatusCode: 200}
bio, err := agent.GetArtistBiography(ctx, "123", "U2", "") bio, err := agent.GetArtistBiography(ctx, "123", "U2", "")
@ -137,16 +129,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.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "en"} }) conf.Server.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: http.StatusOK} httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
// 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: http.StatusOK} httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: 200}
bio, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "") bio, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "")
@ -158,16 +150,16 @@ var _ = Describe("lastfmAgent", func() {
}) })
It("returns ErrNotFound when all languages return empty", func() { It("returns ErrNotFound when all languages return empty", func() {
conf.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "xx"} }) conf.Server.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: http.StatusOK} httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
// 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: http.StatusOK} httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: 200}
_, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "") _, err := agent.GetArtistBiography(ctx, "123", "Legião Urbana", "")
@ -185,16 +177,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.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "en"} }) conf.Server.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: http.StatusOK} httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
// 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: http.StatusOK} httpClient.responses["en"] = http.Response{Body: fEn, StatusCode: 200}
albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "") albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "")
@ -207,15 +199,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.Update(func(c *conf.Options) { c.LastFM.Languages = []string{"ja", "xx"} }) conf.Server.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: http.StatusOK} httpClient.responses["ja"] = http.Response{Body: fJa, StatusCode: 200}
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: http.StatusOK} httpClient.responses["xx"] = http.Response{Body: fXx, StatusCode: 200}
albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "") albumInfo, err := agent.GetAlbumInfo(ctx, "Dois", "Legião Urbana", "")
@ -239,7 +231,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
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"},
@ -257,7 +249,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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
_, 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))
@ -277,7 +269,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
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"},
@ -295,7 +287,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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
_, 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))
@ -315,7 +307,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
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"}}},
@ -330,7 +322,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
_, 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))
@ -344,7 +336,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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
_, 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))
@ -356,8 +348,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() {
Expect(ds.User().Put(ctx, &model.User{ID: "user-1", UserName: "user-1"})).To(Succeed()) _ = ds.UserProps(ctx).Put("user-1", sessionKeyProperty, "SK-1")
Expect(ds.UserProps().Put(ctx, "user-1", sessionKeyProperty, "SK-1")).To(Succeed())
httpClient = &tests.FakeHttpClient{} httpClient = &tests.FakeHttpClient{}
client := newClient("API_KEY", "SECRET", httpClient) client := newClient("API_KEY", "SECRET", httpClient)
agent = lastFMConstructor(ds) agent = lastFMConstructor(ds)
@ -373,12 +364,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{
{ID: "ar-1", Name: "First Artist"}, {Artist: model.Artist{ID: "ar-1", Name: "First Artist"}},
{ID: "ar-2", Name: "Second Artist"}, {Artist: model.Artist{ID: "ar-2", Name: "Second Artist"}},
}, },
model.RoleAlbumArtist: []model.Participant{ model.RoleAlbumArtist: []model.Participant{
{ID: "ar-1", Name: "First Album Artist"}, {Artist: model.Artist{ID: "ar-1", Name: "First Album Artist"}},
{ID: "ar-2", Name: "Second Album Artist"}, {Artist: model.Artist{ID: "ar-2", Name: "Second Album Artist"}},
}, },
}, },
} }
@ -386,7 +377,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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
err := agent.NowPlaying(ctx, "user-1", track, 0) err := agent.NowPlaying(ctx, "user-1", track, 0)
@ -412,11 +403,11 @@ var _ = Describe("lastfmAgent", func() {
When("ScrobbleFirstArtistOnly is true", func() { When("ScrobbleFirstArtistOnly is true", func() {
BeforeEach(func() { BeforeEach(func() {
conf.Update(func(c *conf.Options) { c.LastFM.ScrobbleFirstArtistOnly = true }) conf.Server.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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
err := agent.NowPlaying(ctx, "user-1", track, 0) err := agent.NowPlaying(ctx, "user-1", track, 0)
@ -432,7 +423,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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
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 +445,12 @@ var _ = Describe("lastfmAgent", func() {
When("ScrobbleFirstArtistOnly is true", func() { When("ScrobbleFirstArtistOnly is true", func() {
BeforeEach(func() { BeforeEach(func() {
conf.Update(func(c *conf.Options) { c.LastFM.ScrobbleFirstArtistOnly = true }) conf.Server.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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
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,54 +462,14 @@ var _ = Describe("lastfmAgent", func() {
}) })
}) })
It("skips songs at the 30-second minimum", func() { It("skips songs with less than 31 seconds", func() {
track.Duration = 30
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK}
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
Expect(err).ToNot(HaveOccurred())
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 track.Duration = 29
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString("{}")), StatusCode: 200}
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()})
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(httpClient.SavedRequest).ToNot(BeNil()) Expect(httpClient.SavedRequest).To(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() {
@ -529,7 +480,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: http.StatusBadRequest, StatusCode: 400,
} }
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()})
@ -539,27 +490,17 @@ 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: http.StatusBadRequest, StatusCode: 400,
} }
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()})
Expect(err).To(MatchError(scrobbler.ErrRetryLater)) Expect(err).To(MatchError(scrobbler.ErrRetryLater))
}) })
It("returns ErrRetryLater on error 29 (rate limit exceeded)", func() {
httpClient.Res = http.Response{
Body: io.NopCloser(bytes.NewBufferString(`{"error":29,"message":"Rate limit exceeded"}`)),
StatusCode: http.StatusOK,
}
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
Expect(errors.Is(err, scrobbler.ErrRetryLater)).To(BeTrue())
})
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: http.StatusInternalServerError, StatusCode: 500,
} }
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()})
@ -569,7 +510,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: http.StatusBadRequest, StatusCode: 400,
} }
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()})
@ -590,7 +531,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
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",
@ -598,15 +539,12 @@ var _ = Describe("lastfmAgent", func() {
URL: "https://www.last.fm/music/Cher/Believe", URL: "https://www.last.fm/music/Cher/Believe",
})) }))
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
// MBID is deliberately not sent — album.getInfo matches on name+artist only. Expect(httpClient.SavedRequest.URL.Query().Get("mbid")).To(Equal("03c91c40-49a6-44a7-90e7-a700edf97a62"))
Expect(httpClient.SavedRequest.URL.Query().Get("mbid")).To(BeEmpty())
Expect(httpClient.SavedRequest.URL.Query().Get("album")).To(Equal("Believe"))
Expect(httpClient.SavedRequest.URL.Query().Get("artist")).To(Equal("Cher"))
}) })
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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
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",
@ -620,27 +558,33 @@ var _ = Describe("lastfmAgent", func() {
_, 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))
Expect(httpClient.SavedRequest.URL.Query().Get("mbid")).To(BeEmpty()) Expect(httpClient.SavedRequest.URL.Query().Get("mbid")).To(Equal("mbid-1234"))
}) })
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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError3)), StatusCode: 200}
_, 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))
Expect(httpClient.SavedRequest.URL.Query().Get("mbid")).To(BeEmpty()) Expect(httpClient.SavedRequest.URL.Query().Get("mbid")).To(Equal("mbid-1234"))
}) })
It("returns an error when Last.fm returns an error 6 (album not found)", func() { It("returns an error if Last.fm call returns an error 6 and mbid is empty", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: 200}
_, err := agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234") _, err := agent.GetAlbumInfo(ctx, "123", "U2", "")
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
// A definitive not-found must satisfy the sentinel, or the artwork worker retries it.
Expect(errors.Is(err, agents.ErrNotFound)).To(BeTrue())
Expect(httpClient.RequestCount).To(Equal(1)) Expect(httpClient.RequestCount).To(Equal(1))
})
Context("MBID non existent in Last.fm", func() {
It("calls again when last.fm returns an error 6", func() {
httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(lastfmError6)), StatusCode: 200}
_, _ = agent.GetAlbumInfo(ctx, "123", "U2", "mbid-1234")
Expect(httpClient.RequestCount).To(Equal(2))
Expect(httpClient.SavedRequest.URL.Query().Get("mbid")).To(BeEmpty()) Expect(httpClient.SavedRequest.URL.Query().Get("mbid")).To(BeEmpty())
}) })
}) })
})
Describe("GetArtistImages", func() { Describe("GetArtistImages", func() {
var agent *lastfmAgent var agent *lastfmAgent
@ -658,10 +602,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: http.StatusOK} apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
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: http.StatusOK} httpClient.Res = http.Response{Body: fScraper, StatusCode: 200}
images, err := agent.GetArtistImages(ctx, "123", "U2", "") images, err := agent.GetArtistImages(ctx, "123", "U2", "")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -669,60 +613,30 @@ var _ = Describe("lastfmAgent", func() {
Expect(images[0].URL).To(Equal("https://lastfm.freetls.fastly.net/i/u/ar0/818148bf682d429dc21b59a73ef6f68e.png")) Expect(images[0].URL).To(Equal("https://lastfm.freetls.fastly.net/i/u/ar0/818148bf682d429dc21b59a73ef6f68e.png"))
}) })
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: http.StatusOK}
_, err := agent.GetArtistImages(ctx, "123", "Nonexistent Artist", "")
// Not a fault: runs of missing artists must not trip the worker's circuit breaker.
Expect(errors.Is(err, agents.ErrNotFound)).To(BeTrue())
})
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: http.StatusOK} apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
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: http.StatusOK} httpClient.Res = http.Response{Body: fScraper, StatusCode: 200}
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("errors when the page has no meta tags", func() { It("returns empty list if 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: http.StatusOK} apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
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: http.StatusOK} httpClient.Res = http.Response{Body: fScraper, StatusCode: 200}
_, 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).To(MatchError(errNoArtistPage)) Expect(err).ToNot(HaveOccurred())
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", "")
@ -732,7 +646,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: http.StatusOK} apiClient.Res = http.Response{Body: fApi, StatusCode: 200}
httpClient.Err = errors.New("scraper error") httpClient.Err = errors.New("scraper error")
_, err := agent.GetArtistImages(ctx, "123", "U2", "") _, err := agent.GetArtistImages(ctx, "123", "U2", "")
@ -765,7 +679,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: http.StatusOK, StatusCode: 200,
Body: io.NopCloser(bytes.NewBufferString(`{}`)), Body: io.NopCloser(bytes.NewBufferString(`{}`)),
}, nil }, nil
} }

View file

@ -18,7 +18,6 @@ import (
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/server" "github.com/navidrome/navidrome/server"
"github.com/navidrome/navidrome/utils/httpclient"
"github.com/navidrome/navidrome/utils/req" "github.com/navidrome/navidrome/utils/req"
) )
@ -37,12 +36,14 @@ 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()
hc := httpclient.New(consts.DefaultHttpClientTimeOut) hc := &http.Client{
Timeout: consts.DefaultHttpClientTimeOut,
}
r.client = newClient(r.apiKey, r.secret, hc) r.client = newClient(r.apiKey, r.secret, hc)
return r return r
} }
@ -122,7 +123,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))) _, _ = w.Write([]byte("An error occurred while authorizing with Last.fm. \n\nRequest ID: " + middleware.GetReqID(ctx))) //nolint:gosec
return return
} }
@ -132,7 +133,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, log.Error(ctx, "Could not fetch LastFM session key", "userId", uid, "token", token,
"requestId", middleware.GetReqID(ctx), err) "requestId", middleware.GetReqID(ctx), err)
return err return err
} }

View file

@ -10,10 +10,8 @@ import (
"github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -21,7 +19,8 @@ import (
var _ = Describe("auth_router", func() { var _ = Describe("auth_router", func() {
var ( var (
ds model.DataStore ds *tests.MockDataStore
userProps *tests.MockedUserPropsRepo
httpClient *tests.FakeHttpClient httpClient *tests.FakeHttpClient
router *Router router *Router
) )
@ -32,10 +31,10 @@ var _ = Describe("auth_router", func() {
) )
BeforeEach(func() { BeforeEach(func() {
ctx := GinkgoT().Context() userProps = &tests.MockedUserPropsRepo{}
ds = persistence.New(db.Db()) ds = &tests.MockDataStore{
for _, id := range []string{victimID, attackerID} { MockedProperty: &tests.MockedPropertyRepo{},
Expect(ds.User().Put(ctx, &model.User{ID: id, UserName: id})).To(Succeed()) MockedUserProps: userProps,
} }
auth.Init(ds) auth.Init(ds)
@ -51,14 +50,14 @@ var _ = Describe("auth_router", func() {
}) })
storedSessionKey := func(userID string) string { storedSessionKey := func(userID string) string {
key, _ := ds.UserProps().Get(GinkgoT().Context(), userID, sessionKeyProperty) key, _ := userProps.Get(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: http.StatusOK, StatusCode: 200,
} }
} }
@ -75,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(BeFalse()) Expect(body["status"]).To(Equal(false))
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())
@ -215,14 +214,5 @@ var _ = Describe("auth_router", func() {
_, err = verifyLinkToken(nonExpiringToken) _, err = verifyLinkToken(nonExpiringToken)
Expect(err).To(MatchError("link token missing expiration")) Expect(err).To(MatchError("link token missing expiration"))
}) })
It("rejects a Jellyfin access token", func() {
usr := &model.User{ID: "u1", UserName: "johndoe"}
tokenStr, err := auth.CreateAPIToken(usr, auth.AudienceJellyfin)
Expect(err).ToNot(HaveOccurred())
_, err = verifyLinkToken(tokenStr)
Expect(err).To(HaveOccurred())
})
}) })
}) })

View file

@ -5,7 +5,6 @@ import (
"crypto/md5" "crypto/md5"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"net/http" "net/http"
"net/url" "net/url"
@ -15,15 +14,11 @@ import (
"strings" "strings"
"time" "time"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
) )
const ( const (
apiBaseUrl = "https://ws.audioscrobbler.com/2.0/" apiBaseUrl = "https://ws.audioscrobbler.com/2.0/"
// errCodeRateLimit is Last.fm's "rate limit exceeded"; it arrives in the body, with HTTP 200
// and no rate-limit headers, so the body code is the only signal.
errCodeRateLimit = 29
) )
type lastFMError struct { type lastFMError struct {
@ -49,12 +44,6 @@ 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")
@ -72,7 +61,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", escapePlus(name)) params.Add("artist", 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 {
@ -84,7 +73,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", escapePlus(name)) params.Add("artist", 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 {
@ -96,7 +85,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", escapePlus(name)) params.Add("artist", 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 {
@ -108,8 +97,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", escapePlus(name)) params.Add("track", name)
params.Add("artist", escapePlus(artist)) params.Add("artist", 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 {
@ -182,14 +171,7 @@ 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)
@ -236,18 +218,14 @@ 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 != http.StatusOK && jsonErr != nil { if resp.StatusCode != 200 && 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 {
return nil, jsonErr return nil, jsonErr
} }
if response.Error != 0 { if response.Error != 0 {
var err error = &lastFMError{Code: response.Error, Message: response.Message} return &response, &lastFMError{Code: response.Error, Message: response.Message}
if response.Error == errCodeRateLimit {
err = errors.Join(err, &agents.RetryLaterError{})
}
return &response, err
} }
return &response, nil return &response, nil

View file

@ -19,10 +19,8 @@ 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)
}) })
@ -30,88 +28,70 @@ 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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
album, err := client.albumGetInfo(ctx, "Believe", "U2", "mbid-1234", "pt") album, err := client.albumGetInfo(context.Background(), "Believe", "U2", "mbid-1234", "pt")
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
artist, err := client.artistGetInfo(ctx, "U2", "pt") artist, err := client.artistGetInfo(context.Background(), "U2", "pt")
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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: http.StatusInternalServerError, StatusCode: 500,
} }
_, err := client.artistGetInfo(ctx, "U2", "pt") _, err := client.artistGetInfo(context.Background(), "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: http.StatusBadRequest, StatusCode: 400,
} }
_, err := client.artistGetInfo(ctx, "U2", "pt") _, err := client.artistGetInfo(context.Background(), "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: http.StatusOK, StatusCode: 200,
} }
_, err := client.artistGetInfo(ctx, "U2", "pt") _, err := client.artistGetInfo(context.Background(), "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(ctx, "U2", "pt") _, err := client.artistGetInfo(context.Background(), "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: http.StatusOK, StatusCode: 200,
} }
_, err := client.artistGetInfo(ctx, "U2", "pt") _, err := client.artistGetInfo(context.Background(), "U2", "pt")
Expect(err).To(MatchError("invalid character '<' looking for beginning of value")) Expect(err).To(MatchError("invalid character '<' looking for beginning of value"))
}) })
@ -120,76 +100,47 @@ 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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
similar, err := client.artistGetSimilar(ctx, "U2", 2) similar, err := client.artistGetSimilar(context.Background(), "U2", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
Expect(similar.Artists).To(HaveLen(2)) Expect(len(similar.Artists)).To(Equal(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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
top, err := client.artistGetTopTracks(ctx, "U2", 2) top, err := client.artistGetTopTracks(context.Background(), "U2", 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
Expect(top.Track).To(HaveLen(2)) Expect(len(top.Track)).To(Equal(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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
similar, err := client.trackGetSimilar(ctx, "Just Can't Get Enough", "Depeche Mode", 5) similar, err := client.trackGetSimilar(context.Background(), "Just Can't Get Enough", "Depeche Mode", 5)
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
Expect(similar.Track).To(HaveLen(5)) Expect(len(similar.Track)).To(Equal(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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
similar, err := client.trackGetSimilar(ctx, "UnknownTrack", "UnknownArtist", 3) similar, err := client.trackGetSimilar(context.Background(), "UnknownTrack", "UnknownArtist", 3)
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
Expect(similar.Track).To(BeEmpty()) Expect(similar.Track).To(BeEmpty())
}) })
}) })
@ -198,10 +149,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: http.StatusOK, StatusCode: 200,
} }
Expect(client.GetToken(ctx)).To(Equal("TOKEN")) Expect(client.GetToken(context.Background())).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"))
@ -214,10 +165,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: http.StatusOK, StatusCode: 200,
} }
Expect(client.getSession(ctx, "TOKEN")).To(Equal("SESSION_KEY")) Expect(client.getSession(context.Background(), "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"))
@ -231,7 +182,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: http.StatusOK, StatusCode: 200,
} }
info := ScrobbleInfo{ info := ScrobbleInfo{
@ -242,8 +193,8 @@ var _ = Describe("client", func() {
duration: 276, duration: 276,
albumArtist: "U2", albumArtist: "U2",
} }
err := client.scrobble(ctx, "SESSION_KEY", info) err := client.scrobble(context.Background(), "SESSION_KEY", info)
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
req := httpClient.SavedRequest req := httpClient.SavedRequest
Expect(req.Method).To(Equal(http.MethodPost)) Expect(req.Method).To(Equal(http.MethodPost))
@ -265,7 +216,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: http.StatusOK, StatusCode: 200,
} }
info := ScrobbleInfo{ info := ScrobbleInfo{
@ -276,8 +227,8 @@ var _ = Describe("client", func() {
duration: 276, duration: 276,
albumArtist: "U2", albumArtist: "U2",
} }
err := client.updateNowPlaying(ctx, "SESSION_KEY", info) err := client.updateNowPlaying(context.Background(), "SESSION_KEY", info)
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
req := httpClient.SavedRequest req := httpClient.SavedRequest
Expect(req.Method).To(Equal(http.MethodPost)) Expect(req.Method).To(Equal(http.MethodPost))

View file

@ -3,9 +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/persistence/persistencetest"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -14,10 +12,6 @@ import (
func TestLastFM(t *testing.T) { func TestLastFM(t *testing.T) {
tests.Init(t, false) tests.Init(t, false)
log.SetLevel(log.LevelFatal) log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail) RegisterFailHandler(Fail)
RunSpecs(t, "LastFM Test Suite") RunSpecs(t, "LastFM Test Suite")
} }
var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

View file

@ -14,7 +14,7 @@ var _ = Describe("LastFM responses", func() {
var resp Response var resp Response
body, _ := os.ReadFile("tests/fixtures/lastfm.artist.getinfo.json") body, _ := os.ReadFile("tests/fixtures/lastfm.artist.getinfo.json")
err := json.Unmarshal(body, &resp) err := json.Unmarshal(body, &resp)
Expect(err).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
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).ToNot(HaveOccurred()) Expect(err).To(BeNil())
Expect(error.Error).To(Equal(3)) Expect(error.Error).To(Equal(3))
Expect(error.Message).To(Equal("Invalid Method - No method with that name in this package")) Expect(error.Message).To(Equal("Invalid Method - No method with that name in this package"))

View file

@ -3,6 +3,7 @@ package listenbrainz
import ( import (
"context" "context"
"errors" "errors"
"net/http"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/consts"
@ -11,7 +12,6 @@ import (
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils/cache" "github.com/navidrome/navidrome/utils/cache"
"github.com/navidrome/navidrome/utils/httpclient"
"github.com/navidrome/navidrome/utils/slice" "github.com/navidrome/navidrome/utils/slice"
) )
@ -31,9 +31,11 @@ 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 := &http.Client{
Timeout: consts.DefaultHttpClientTimeOut,
} }
hc := httpclient.New(consts.DefaultHttpClientTimeOut)
chc := cache.NewHTTPClient(hc, consts.DefaultHttpClientTimeOut) chc := cache.NewHTTPClient(hc, consts.DefaultHttpClientTimeOut)
l.client = newClient(l.baseURL, chc) l.client = newClient(l.baseURL, chc)
return l return l
@ -228,30 +230,29 @@ func (l *listenBrainzAgent) PlaybackReport(context.Context, scrobbler.PlaybackSe
} }
func init() { func init() {
conf.AddHook(register) conf.AddHook(func() {
if conf.Server.ListenBrainz.Enabled {
scrobbler.Register(listenBrainzAgentName, func(ds model.DataStore) scrobbler.Scrobbler {
// This is a workaround for the fact that a (Interface)(nil) is not the same as a (*listenBrainzAgent)(nil)
// See https://go.dev/doc/faq#nil_error
a := listenBrainzConstructor(ds)
if a != nil {
return a
} }
func register() {
scrobbler.Register(listenBrainzAgentName, newScrobbler)
agents.Register(listenBrainzAgentName, newAgent)
}
func listenBrainzEnabled() bool {
return conf.Server().ListenBrainz.Enabled
}
func newScrobbler(ds model.DataStore) scrobbler.Scrobbler {
if !listenBrainzEnabled() {
return nil return nil
} })
return listenBrainzConstructor(ds)
}
func newAgent(ds model.DataStore) agents.Interface { agents.Register(listenBrainzAgentName, func(ds model.DataStore) agents.Interface {
if !listenBrainzEnabled() { // This is a workaround for the fact that a (Interface)(nil) is not the same as a (*listenBrainzAgent)(nil)
return nil // See https://go.dev/doc/faq#nil_error
a := listenBrainzConstructor(ds)
if a != nil {
return a
} }
return listenBrainzConstructor(ds) return nil
})
}
})
} }
var ( var (

View file

@ -8,16 +8,12 @@ import (
"io" "io"
"net/http" "net/http"
"os" "os"
"reflect"
"time" "time"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/scrobbler" "github.com/navidrome/navidrome/core/scrobbler"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -32,10 +28,9 @@ var _ = Describe("listenBrainzAgent", func() {
var track *model.MediaFile var track *model.MediaFile
BeforeEach(func() { BeforeEach(func() {
ctx = GinkgoT().Context() ds = &tests.MockDataStore{}
ds = persistence.New(db.Db()) ctx = context.Background()
Expect(ds.User().Put(ctx, &model.User{ID: "user-1", UserName: "user-1"})).To(Succeed()) _ = ds.UserProps(ctx).Put("user-1", sessionKeyProperty, "SK-1")
Expect(ds.UserProps().Put(ctx, "user-1", sessionKeyProperty, "SK-1")).To(Succeed())
httpClient = &tests.FakeHttpClient{} httpClient = &tests.FakeHttpClient{}
agent = listenBrainzConstructor(ds) agent = listenBrainzConstructor(ds)
agent.client = newClient("http://localhost:8080", httpClient) agent.client = newClient("http://localhost:8080", httpClient)
@ -51,8 +46,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{
{ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"}, {Artist: model.Artist{ID: "ar-1", Name: "Artist 1", MbzArtistID: "mbz-111"}},
{ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"}, {Artist: model.Artist{ID: "ar-2", Name: "Artist 2", MbzArtistID: "mbz-222"}},
}, },
}, },
} }
@ -85,7 +80,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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
err := agent.NowPlaying(ctx, "user-1", track, 0) err := agent.NowPlaying(ctx, "user-1", track, 0)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -105,14 +100,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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(`{"status": "ok"}`)), StatusCode: 200}
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -133,7 +128,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: http.StatusServiceUnavailable, StatusCode: 503,
} }
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
@ -143,7 +138,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: http.StatusInternalServerError, StatusCode: 500,
} }
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
@ -153,7 +148,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: http.StatusInternalServerError, StatusCode: 500,
} }
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
@ -163,25 +158,12 @@ 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: http.StatusBadRequest, StatusCode: 400,
} }
err := agent.Scrobble(ctx, "user-1", sc) err := agent.Scrobble(ctx, "user-1", sc)
Expect(err).To(MatchError(scrobbler.ErrUnrecoverable)) Expect(err).To(MatchError(scrobbler.ErrUnrecoverable))
}) })
It("keeps a 429 scrobble for retry and carries the delay", func() {
httpClient.Res = http.Response{
StatusCode: http.StatusTooManyRequests,
Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}},
Body: io.NopCloser(bytes.NewBufferString(`{"code":429,"error":"rate limited"}`)),
}
err := agent.Scrobble(ctx, "user-1", scrobbler.Scrobble{MediaFile: *track, TimeStamp: time.Now()})
Expect(errors.Is(err, scrobbler.ErrRetryLater)).To(BeTrue())
retry, ok := errors.AsType[*agents.RetryLaterError](err)
Expect(ok).To(BeTrue())
Expect(retry.RetryIn).To(Equal(7 * time.Second))
})
}) })
Describe("GetArtistUrl", func() { Describe("GetArtistUrl", func() {
@ -196,7 +178,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
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"))
@ -204,7 +186,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
_, 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))
@ -222,7 +204,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: http.StatusBadRequest, StatusCode: 400,
} }
_, 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())
@ -252,7 +234,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: http.StatusBadRequest, StatusCode: 400,
} }
_, err := agent.GetArtistTopSongs(ctx, "", "", "1", 1) _, err := agent.GetArtistTopSongs(ctx, "", "", "1", 1)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
@ -262,7 +244,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
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{
@ -289,7 +271,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
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{
@ -315,7 +297,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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: 200}
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))
@ -327,7 +309,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: http.StatusOK} httpClient.Res = http.Response{Body: io.NopCloser(bytes.NewBufferString(body)), StatusCode: 200}
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))
@ -359,7 +341,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: http.StatusBadRequest, StatusCode: 400,
} }
_, err := agent.GetSimilarArtists(ctx, "", "", "1", 1) _, err := agent.GetSimilarArtists(ctx, "", "", "1", 1)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
@ -369,7 +351,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
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())
@ -383,7 +365,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
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())
@ -419,7 +401,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: http.StatusBadRequest, StatusCode: 400,
} }
_, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", "1", 1) _, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", "1", 1)
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
@ -429,7 +411,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 2) resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 2)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -461,7 +443,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 1) resp, err := agent.GetSimilarSongsByTrack(ctx, "", "", "", mbid, 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
@ -482,43 +464,3 @@ var _ = Describe("listenBrainzAgent", func() {
}) })
}) })
}) })
var _ = Describe("register", func() {
var ds model.DataStore
BeforeEach(func() {
ds = struct{ model.DataStore }{}
delete(agents.Map, listenBrainzAgentName)
scrobbler.Unregister(listenBrainzAgentName)
})
When("ListenBrainz is disabled", func() {
BeforeEach(func() {
conf.Update(func(c *conf.Options) { c.ListenBrainz.Enabled = false })
register()
})
It("still registers the builtin name", func() {
Expect(scrobbler.IsBuiltinScrobbler(listenBrainzAgentName)).To(BeTrue())
Expect(agents.Map).To(HaveKey(listenBrainzAgentName))
})
It("builds no scrobbler and no agent", func() {
// TypeOf is nil only for an untyped nil; a typed nil would pass callers' != nil checks
Expect(reflect.TypeOf(newScrobbler(ds))).To(BeNil())
Expect(reflect.TypeOf(agents.Map[listenBrainzAgentName](ds))).To(BeNil())
})
})
When("ListenBrainz is enabled", func() {
BeforeEach(func() {
conf.Update(func(c *conf.Options) { c.ListenBrainz.Enabled = true })
register()
})
It("builds the scrobbler and the agent", func() {
Expect(newScrobbler(ds)).To(BeAssignableToTypeOf(&listenBrainzAgent{}))
Expect(agents.Map[listenBrainzAgentName](ds)).To(BeAssignableToTypeOf(&listenBrainzAgent{}))
})
})
})

View file

@ -16,7 +16,6 @@ import (
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/server" "github.com/navidrome/navidrome/server"
"github.com/navidrome/navidrome/utils/httpclient"
) )
type sessionKeysRepo interface { type sessionKeysRepo interface {
@ -38,8 +37,10 @@ func NewRouter(ds model.DataStore) *Router {
sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty}, sessionKeys: &agents.SessionKeys{DataStore: ds, KeyName: sessionKeyProperty},
} }
r.Handler = r.routes() r.Handler = r.routes()
hc := httpclient.New(consts.DefaultHttpClientTimeOut) hc := &http.Client{
r.client = newClient(conf.Server().ListenBrainz.BaseURL, hc) Timeout: consts.DefaultHttpClientTimeOut,
}
r.client = newClient(conf.Server.ListenBrainz.BaseURL, hc)
return r return r
} }

View file

@ -34,28 +34,28 @@ var _ = Describe("ListenBrainz Auth Router", func() {
Describe("getLinkStatus", func() { Describe("getLinkStatus", func() {
It("returns false when there is no stored session key", func() { It("returns false when there is no stored session key", func() {
req = httptest.NewRequest(http.MethodGet, "/listenbrainz/link", nil) req = httptest.NewRequest("GET", "/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(Succeed()) Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil())
Expect(parsed["status"]).To(BeFalse()) Expect(parsed["status"]).To(Equal(false))
}) })
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(http.MethodGet, "/listenbrainz/link", nil) req = httptest.NewRequest("GET", "/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(Succeed()) Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil())
Expect(parsed["status"]).To(BeTrue()) Expect(parsed["status"]).To(Equal(true))
}) })
}) })
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(http.MethodPut, "/listenbrainz/link", strings.NewReader(`{}`)) req = httptest.NewRequest("PUT", "/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: http.StatusOK, StatusCode: 200,
} }
req = httptest.NewRequest(http.MethodPut, "/listenbrainz/link", strings.NewReader(`{"token": "invalid-tok-1"}`)) req = httptest.NewRequest("PUT", "/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: http.StatusOK, StatusCode: 200,
} }
req = httptest.NewRequest(http.MethodPut, "/listenbrainz/link", strings.NewReader(`{"token": "tok-1"}`)) req = httptest.NewRequest("PUT", "/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(Succeed()) Expect(json.Unmarshal(resp.Body.Bytes(), &parsed)).To(BeNil())
Expect(parsed["status"]).To(BeTrue()) Expect(parsed["status"]).To(Equal(true))
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: http.StatusOK, StatusCode: 200,
} }
req = httptest.NewRequest(http.MethodPut, "/listenbrainz/link", strings.NewReader(`{"token": "tok-1"}`)) req = httptest.NewRequest("PUT", "/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(http.MethodDelete, "/listenbrainz/link", nil) req = httptest.NewRequest("DELETE", "/listenbrainz/link", nil)
r.unlink(resp, req) r.unlink(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK)) Expect(resp.Code).To(Equal(http.StatusOK))
Expect(sk.KeyValue).To(Equal("")) Expect(sk.KeyValue).To(Equal(""))

View file

@ -13,7 +13,6 @@ import (
"slices" "slices"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
) )
@ -22,12 +21,6 @@ const (
labsBase = "https://labs.api.listenbrainz.org/" labsBase = "https://labs.api.listenbrainz.org/"
) )
// retryLaterErr reads the wait ListenBrainz asked for. It sends X-RateLimit-Reset-In
// (delta-seconds) on every response, including the 429, and never Retry-After.
func retryLaterErr(h http.Header) *agents.RetryLaterError {
return &agents.RetryLaterError{RetryIn: agents.ParseRetryIn(h.Get("X-RateLimit-Reset-In"))}
}
var ( var (
ErrorNotFound = errors.New("listenbrainz: not found") ErrorNotFound = errors.New("listenbrainz: not found")
) )
@ -64,7 +57,7 @@ type listenBrainzResponse struct {
} }
type listenBrainzRequest struct { type listenBrainzRequest struct {
ApiKey string ApiKey string //nolint:gosec
Body listenBrainzRequestBody Body listenBrainzRequestBody
} }
@ -162,10 +155,7 @@ 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, err := json.Marshal(r.Body) b, _ := 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
@ -174,7 +164,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", "Token "+r.ApiKey) req.Header.Add("Authorization", fmt.Sprintf("Token %s", 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)
@ -184,24 +174,17 @@ func (c *client) makeAuthenticatedRequest(ctx context.Context, method string, en
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode == http.StatusTooManyRequests {
return nil, retryLaterErr(resp.Header)
}
decoder := json.NewDecoder(resp.Body) decoder := json.NewDecoder(resp.Body)
var response listenBrainzResponse var response listenBrainzResponse
jsonErr := decoder.Decode(&response) jsonErr := decoder.Decode(&response)
if resp.StatusCode != http.StatusOK && jsonErr != nil { if resp.StatusCode != 200 && 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 {
return nil, jsonErr return nil, jsonErr
} }
if response.Code != 0 && response.Code != 200 { if response.Code != 0 && response.Code != 200 {
// LB also reports rate limiting as a body code, not only as an HTTP status.
if response.Code == http.StatusTooManyRequests {
return &response, retryLaterErr(resp.Header)
}
return &response, &listenBrainzError{Code: response.Code, Message: response.Error} return &response, &listenBrainzError{Code: response.Code, Message: response.Error}
} }
@ -226,11 +209,8 @@ 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 != http.StatusOK { if resp.StatusCode != 200 {
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode == http.StatusTooManyRequests {
return nil, retryLaterErr(resp.Header)
}
decoder := json.NewDecoder(resp.Body) decoder := json.NewDecoder(resp.Body)
var lbzError lbzHttpError var lbzError lbzHttpError
@ -318,7 +298,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)
@ -357,7 +337,7 @@ func (c *client) getSimilarRecordings(ctx context.Context, mbid string, limit in
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-recordings/json", nil) req, _ := http.NewRequestWithContext(ctx, http.MethodGet, labsBase+"similar-recordings/json", nil)
req.Header.Add("Content-Type", "application/json; charset=UTF-8") req.Header.Add("Content-Type", "application/json; charset=UTF-8")
req.URL.RawQuery = url.Values{ req.URL.RawQuery = url.Values{
"recording_mbids": []string{mbid}, "algorithm": []string{conf.Server().ListenBrainz.TrackAlgorithm}, "recording_mbids": []string{mbid}, "algorithm": []string{conf.Server.ListenBrainz.TrackAlgorithm},
}.Encode() }.Encode()
log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL) log.Trace(ctx, fmt.Sprintf("Sending ListenBrainz Labs %s request", req.Method), "url", req.URL)

View file

@ -4,16 +4,13 @@ import (
"bytes" "bytes"
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"os" "os"
"strings"
"time"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -22,9 +19,7 @@ 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)
}) })
@ -48,12 +43,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: http.StatusOK, StatusCode: 200,
} }
}) })
It("formats the request properly", func() { It("formats the request properly", func() {
_, err := client.validateToken(ctx, "LB-TOKEN") _, err := client.validateToken(context.Background(), "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"))
@ -62,9 +57,9 @@ var _ = Describe("client", func() {
}) })
It("parses and returns the response", func() { It("parses and returns the response", func() {
res, err := client.validateToken(ctx, "LB-TOKEN") res, err := client.validateToken(context.Background(), "LB-TOKEN")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(res.Valid).To(BeTrue()) Expect(res.Valid).To(Equal(true))
Expect(res.UserName).To(Equal("ListenBrainzUser")) Expect(res.UserName).To(Equal("ListenBrainzUser"))
}) })
}) })
@ -74,7 +69,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: http.StatusOK, StatusCode: 200,
} }
li = listenInfo{ li = listenInfo{
TrackMetadata: trackMetadata{ TrackMetadata: trackMetadata{
@ -95,7 +90,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(ctx, "LB-TOKEN", li)).To(Succeed()) Expect(client.updateNowPlaying(context.Background(), "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"))
@ -113,7 +108,7 @@ var _ = Describe("client", func() {
}) })
It("formats the request properly", func() { It("formats the request properly", func() {
Expect(client.scrobble(ctx, "LB-TOKEN", li)).To(Succeed()) Expect(client.scrobble(context.Background(), "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"))
@ -131,9 +126,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: http.StatusBadRequest, StatusCode: 400,
} }
_, err := client.getArtistUrl(ctx, "1") _, err := client.getArtistUrl(context.Background(), "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"))
@ -143,9 +138,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: http.StatusNotImplemented, StatusCode: 501,
} }
_, err := client.getArtistUrl(ctx, "1") _, err := client.getArtistUrl(context.Background(), "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"))
@ -154,8 +149,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
_, err := client.getArtistUrl(ctx, "7c2cc610-f998-43ef-a08f-dae3344b8973") _, err := client.getArtistUrl(context.Background(), "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"))
@ -164,8 +159,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
url, err := client.getArtistUrl(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56") url, err := client.getArtistUrl(context.Background(), "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))
@ -180,9 +175,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: http.StatusBadRequest, StatusCode: 400,
} }
_, err := client.getArtistTopSongs(ctx, "1", 50) _, err := client.getArtistTopSongs(context.Background(), "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"))
@ -192,9 +187,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: http.StatusInternalServerError, StatusCode: 500,
} }
_, err := client.getArtistTopSongs(ctx, "1", 1) _, err := client.getArtistTopSongs(context.Background(), "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"))
@ -203,8 +198,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 5) data, err := client.getArtistTopSongs(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 5)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]trackInfo{ Expect(data).To(Equal([]trackInfo{
{ {
@ -233,8 +228,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
data, err := client.getArtistTopSongs(ctx, "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1) data, err := client.getArtistTopSongs(context.Background(), "d2a92ee2-27ce-4e71-bfc5-12e34fe8ef56", 1)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]trackInfo{ Expect(data).To(Equal([]trackInfo{
{ {
@ -258,6 +253,7 @@ 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 +265,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: http.StatusBadRequest, StatusCode: 400,
} }
_, err := client.getSimilarArtists(ctx, "1", 2) _, err := client.getSimilarArtists(context.Background(), "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 +276,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
resp, err := client.getSimilarArtists(ctx, mbid, 2) resp, err := client.getSimilarArtists(context.Background(), 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 +290,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
resp, err := client.getSimilarArtists(ctx, "db92a151-1ac2-438b-bc43-b82e149ddd50", 1) resp, err := client.getSimilarArtists(context.Background(), "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 +303,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.Update(func(c *conf.Options) { c.ListenBrainz.ArtistAlgorithm = algorithm }) conf.Server.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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
resp, err := client.getSimilarArtists(ctx, mbid, 2) resp, err := client.getSimilarArtists(context.Background(), 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,6 +324,7 @@ 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 {
@ -339,9 +336,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: http.StatusBadRequest, StatusCode: 400,
} }
_, err := client.getSimilarRecordings(ctx, "1", 2) _, err := client.getSimilarRecordings(context.Background(), "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")))
@ -350,8 +347,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
resp, err := client.getSimilarRecordings(ctx, mbid, 2) resp, err := client.getSimilarRecordings(context.Background(), 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)))
@ -378,8 +375,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
resp, err := client.getSimilarRecordings(ctx, mbid, 1) resp, err := client.getSimilarRecordings(context.Background(), 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)))
@ -398,9 +395,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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
// There are actually 5 items. The dedup should happen FIRST // There are actually 5 items. The dedup should happen FIRST
resp, err := client.getSimilarRecordings(ctx, mbid, 4) resp, err := client.getSimilarRecordings(context.Background(), 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)))
@ -443,11 +440,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.Update(func(c *conf.Options) { c.ListenBrainz.TrackAlgorithm = algorithm }) conf.Server.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: http.StatusOK} httpClient.Res = http.Response{Body: f, StatusCode: 200}
resp, err := client.getSimilarRecordings(ctx, mbid, 1) resp, err := client.getSimilarRecordings(context.Background(), 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)))
@ -464,73 +461,4 @@ var _ = Describe("client", func() {
})) }))
}) })
}) })
Describe("rate limiting", func() {
It("returns RetryLaterError with the header delay on 429", func() {
httpClient.Res = http.Response{
StatusCode: http.StatusTooManyRequests,
Header: http.Header{"X-Ratelimit-Reset-In": []string{"3"}},
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)),
}
_, err := client.validateToken(ctx, "token")
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
retry, ok := errors.AsType[*agents.RetryLaterError](err)
Expect(ok).To(BeTrue())
Expect(retry.RetryIn).To(Equal(3 * time.Second))
})
It("returns RetryLaterError with zero delay when no header is present", func() {
httpClient.Res = http.Response{
StatusCode: http.StatusTooManyRequests,
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
}
_, err := client.validateToken(ctx, "token")
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
retry, _ := errors.AsType[*agents.RetryLaterError](err)
Expect(retry.RetryIn).To(BeZero())
})
DescribeTable("caps absurd header values at one hour",
func(header string) {
httpClient.Res = http.Response{
StatusCode: http.StatusTooManyRequests,
Header: http.Header{"X-Ratelimit-Reset-In": []string{header}},
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
}
_, err := client.validateToken(ctx, "token")
retry, _ := errors.AsType[*agents.RetryLaterError](err)
Expect(retry.RetryIn).To(Equal(time.Hour))
},
Entry("a large value", "999999"),
Entry("a huge value", "99999999999"),
// Scaling this to nanoseconds before capping wraps past 2^64, landing on ~0.29s.
Entry("a value that overflows int64 nanoseconds", "18446744074"),
)
It("maps a body-level 429 sent with a non-429 status", func() {
httpClient.Res = http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"X-Ratelimit-Reset-In": []string{"7"}},
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"You have exceeded your rate limit."}`)),
}
_, err := client.validateToken(ctx, "token")
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
retry, ok := errors.AsType[*agents.RetryLaterError](err)
Expect(ok).To(BeTrue())
Expect(retry.RetryIn).To(Equal(7 * time.Second))
})
It("returns RetryLaterError on a 429 from makeGenericRequest", func() {
httpClient.Res = http.Response{
StatusCode: http.StatusTooManyRequests,
Header: http.Header{"X-Ratelimit-Reset-In": []string{"5"}},
Body: io.NopCloser(strings.NewReader(`{"code":429,"error":"rate limited"}`)),
}
_, err := client.getArtistUrl(ctx, "1")
Expect(errors.Is(err, agents.ErrRetryLater)).To(BeTrue())
retry, ok := errors.AsType[*agents.RetryLaterError](err)
Expect(ok).To(BeTrue())
Expect(retry.RetryIn).To(Equal(5 * time.Second))
})
})
}) })

View file

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

View file

@ -1 +0,0 @@
response-property-enum-value-added INFO

View file

@ -1,155 +0,0 @@
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

View file

@ -1,262 +0,0 @@
{
"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"
}
}
}
}
}

View file

@ -1,194 +0,0 @@
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

View file

@ -1,35 +0,0 @@
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()
}

View file

@ -1,37 +0,0 @@
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())
})
})

View file

@ -1,3 +0,0 @@
description: Entity tag for `If-None-Match` revalidation.
schema:
type: string

View file

@ -1,9 +0,0 @@
name: limit
in: query
description: Maximum number of items to return.
required: false
schema:
type: integer
minimum: 1
maximum: 2000
default: 100

View file

@ -1,8 +0,0 @@
name: offset
in: query
description: Zero-based index of the first item to return.
required: false
schema:
type: integer
minimum: 0
default: 0

View file

@ -1,5 +0,0 @@
description: The request is malformed or fails validation.
content:
application/problem+json:
schema:
$ref: ../schemas/Problem.yaml

View file

@ -1,5 +0,0 @@
description: The caller is authenticated but not allowed to do this.
content:
application/problem+json:
schema:
$ref: ../schemas/Problem.yaml

View file

@ -1,5 +0,0 @@
description: Unexpected server failure. Details are in the server log.
content:
application/problem+json:
schema:
$ref: ../schemas/Problem.yaml

View file

@ -1,5 +0,0 @@
description: No such resource or endpoint.
content:
application/problem+json:
schema:
$ref: ../schemas/Problem.yaml

View file

@ -1,4 +0,0 @@
description: Not modified.
headers:
ETag:
$ref: ../headers/ETag.yaml

View file

@ -1,5 +0,0 @@
description: Missing, invalid, or expired credentials.
content:
application/problem+json:
schema:
$ref: ../schemas/Problem.yaml

View file

@ -1,13 +0,0 @@
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.

View file

@ -1,35 +0,0 @@
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

View file

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

View file

@ -1,10 +0,0 @@
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.

View file

@ -1,39 +0,0 @@
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.

View file

@ -1,42 +0,0 @@
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

View file

@ -1,19 +0,0 @@
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

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -2,7 +2,9 @@ package cmd
import ( import (
"context" "context"
"path/filepath" "fmt"
"os"
"strings"
"time" "time"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
@ -15,7 +17,6 @@ var (
backupCount int backupCount int
backupDir string backupDir string
force bool force bool
integrityCheck bool
restorePath string restorePath string
) )
@ -30,9 +31,8 @@ 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", "", "file name of the backup database to restore (resolved against the backup directory unless it is an absolute path)") restoreCommand.Flags().StringVarP(&restorePath, "backup-file", "b", "", "path of backup database to restore")
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,15 +75,27 @@ var (
func runBackup(ctx context.Context) { func runBackup(ctx context.Context) {
if backupDir != "" { if backupDir != "" {
conf.Update(func(c *conf.Options) { c.Backup.Path = conf.NewDir(backupDir) }) conf.Server.Backup.Path = conf.NewDir(backupDir)
} }
requireExistingDB() idx := strings.LastIndex(conf.Server.DbPath, "?")
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", "backupPath", conf.Server().Backup.Path, err) log.Fatal("Error backing up database", "backup path", conf.Server.BasePath, err)
} }
elapsed := time.Since(start) elapsed := time.Since(start)
@ -91,26 +103,44 @@ 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 != "" {
c.Backup.Path = conf.NewDir(backupDir) conf.Server.Backup.Path = conf.NewDir(backupDir)
} }
if backupCount != -1 {
c.Backup.Count = backupCount
}
})
if conf.Server().Backup.Count == 0 && !force && !confirmYES("Warning: pruning ALL backups") { if backupCount != -1 {
conf.Server.Backup.Count = backupCount
}
if conf.Server.Backup.Count == 0 && !force {
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
} }
}
requireExistingDB() idx := strings.LastIndex(conf.Server.DbPath, "?")
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 database", "backupPath", conf.Server().Backup.Path, err) log.Fatal("Error pruning up database", "backup path", conf.Server.BasePath, err)
} }
elapsed := time.Since(start) elapsed := time.Since(start)
@ -119,29 +149,36 @@ func runPrune(ctx context.Context) {
} }
func runRestore(ctx context.Context) { func runRestore(ctx context.Context) {
requireExistingDB() idx := strings.LastIndex(conf.Server.DbPath, "?")
var path string
// A relative --backup-file is resolved against Backup.Path, the same folder if idx == -1 {
// `backup create` writes to. Without this, the value was treated as relative path = conf.Server.DbPath
// to the working directory, where the file does not exist. } else {
if !filepath.IsAbs(restorePath) { path = conf.Server.DbPath[:idx]
backupPath, err := conf.Server().Backup.Path.Path() }
if err != nil {
log.Fatal("Backup directory not available", "backupPath", conf.Server().Backup.Path, err) if _, err := os.Stat(path); os.IsNotExist(err) {
log.Fatal("No existing database", "path", path)
return return
} }
restorePath = filepath.Join(backupPath, restorePath)
}
if !force && !confirmYES("Warning: restoring the Navidrome database should only be done offline, especially if your backup is very old.") { if !force {
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, integrityCheck) err := db.Restore(ctx, restorePath)
if err != nil { if err != nil {
log.Fatal("Error restoring database", "backupFile", restorePath, err) log.Fatal("Error restoring database", "backup path", conf.Server.BasePath, err)
} }
elapsed := time.Since(start) elapsed := time.Since(start)

View file

@ -3,9 +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/persistence/persistencetest"
"github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -14,10 +12,6 @@ import (
func TestCmd(t *testing.T) { func TestCmd(t *testing.T) {
tests.Init(t, false) tests.Init(t, false)
log.SetLevel(log.LevelFatal) log.SetLevel(log.LevelFatal)
persistencetest.Init(t)
RegisterFailHandler(Fail) RegisterFailHandler(Fail)
RunSpecs(t, "Cmd Suite") RunSpecs(t, "Cmd Suite")
} }
var _ = configtest.RestoreAfterEachSpec()
var _ = persistencetest.ResetBeforeEachSpec()

View file

@ -1,99 +0,0 @@
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
}

View file

@ -1,124 +0,0 @@
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"))
})
})

View file

@ -1,17 +1,13 @@
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"
@ -32,7 +28,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(cmd.Context(), args) runInspector(args)
}, },
} }
@ -50,33 +46,27 @@ 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 {
fmt.Fprintf(&res, "====================\nFile: %s\n\n", out[i].File) res.WriteString(fmt.Sprintf("====================\nFile: %s\n\n", out[i].File))
t, _ := toml.Marshal(out[i].RawTags) t, _ := toml.Marshal(out[i].RawTags)
fmt.Fprintf(&res, "Raw tags:\n%s\n\n", t) res.WriteString(fmt.Sprintf("Raw tags:\n%s\n\n", t))
t, _ = toml.Marshal(out[i].MappedTags) t, _ = toml.Marshal(out[i].MappedTags)
fmt.Fprintf(&res, "Mapped tags:\n%s\n\n", t) res.WriteString(fmt.Sprintf("Mapped tags:\n%s\n\n", t))
} }
return []byte(res.String()), nil return []byte(res.String()), nil
} }
func runInspector(ctx context.Context, args []string) { func runInspector(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
} }
lib, ok := libraryForFile(matcher, filePath) output, err := core.Inspect(filePath, 1, "")
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
@ -87,33 +77,3 @@ func runInspector(ctx context.Context, 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
}

View file

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

View file

@ -1,174 +0,0 @@
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
}

View file

@ -1,81 +0,0 @@
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))
})
})

View file

@ -6,14 +6,13 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io"
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
"strings" "strings"
"github.com/Masterminds/squirrel" "github.com/Masterminds/squirrel"
"github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core"
"github.com/navidrome/navidrome/core/playlists" "github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model"
@ -109,7 +108,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().GetAll(ctx, options) pls, err := ds.Playlist(ctx).GetAll(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 +116,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().GetWithTracks(ctx, nameOrID, true, false) playlist, err := ds.Playlist(ctx).GetWithTracks(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().GetAll(ctx, model.QueryOptions{Filters: squirrel.Eq{"playlist.name": nameOrID}}) playlists, err := ds.Playlist(ctx).GetAll(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().GetWithTracks(ctx, playlists[0].ID, true, false) playlist, err = ds.Playlist(ctx).GetWithTracks(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)
} }
@ -142,16 +141,14 @@ func findPlaylist(ctx context.Context, ds model.DataStore, nameOrID string) *mod
func runExporter(ctx context.Context) { func runExporter(ctx context.Context) {
ds, ctx := getAdminContext(ctx) ds, ctx := getAdminContext(ctx)
playlist := findPlaylist(ctx, ds, playlistID) playlist := findPlaylist(ctx, ds, playlistID)
writePlaylist(playlist.ToM3U8(), os.Stdout, outputFile) pls := playlist.ToM3U8()
} if outputFile == "-" || outputFile == "" {
println(pls)
func writePlaylist(m3u string, out io.Writer, file string) {
if file == "" || file == "-" {
fmt.Fprint(out, m3u)
return return
} }
if err := os.WriteFile(file, []byte(m3u), 0600); err != nil { err := os.WriteFile(outputFile, []byte(pls), 0600)
log.Fatal("Error writing to the output file", "file", file, err) if err != nil {
log.Fatal("Error writing to the output file", "file", outputFile, err)
} }
} }
@ -160,7 +157,7 @@ func runExport(ctx context.Context) {
if playlistID != "" && outputFile == "" { if playlistID != "" && outputFile == "" {
playlist := findPlaylist(ctx, ds, playlistID) playlist := findPlaylist(ctx, ds, playlistID)
writePlaylist(playlist.ToM3U8(), os.Stdout, outputFile) println(playlist.ToM3U8())
return return
} }
@ -194,7 +191,7 @@ func runExport(ctx context.Context) {
exported := 0 exported := 0
for _, pls := range allPls { for _, pls := range allPls {
plsWithTracks, err := ds.Playlist().GetWithTracks(ctx, pls.ID, true, false) plsWithTracks, err := ds.Playlist(ctx).GetWithTracks(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,10 +244,7 @@ func runList(ctx context.Context) {
display[idx].Public = playlist.Public display[idx].Public = playlist.Public
} }
j, err := json.Marshal(display) j, _ := json.Marshal(display)
if err != nil {
log.Fatal(ctx, "Failed to encode playlists", err)
}
fmt.Printf("%s\n", j) fmt.Printf("%s\n", j)
} }
} }
@ -266,7 +260,7 @@ func runImport(ctx context.Context, files []string) {
ctx = request.WithUser(ctx, *user) ctx = request.WithUser(ctx, *user)
} }
pls := playlists.NewPlaylists(ds, artwork.NewUploader(ds)) pls := playlists.NewPlaylists(ds, core.NewImageUploadService())
for _, file := range files { for _, file := range files {
absPath, err := filepath.Abs(file) absPath, err := filepath.Abs(file)

View file

@ -1,35 +0,0 @@
package cmd
import (
"fmt"
"os"
"path/filepath"
"strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("writePlaylist", func() {
const m3u = "#EXTM3U\n#PLAYLIST:DJ Wave\n#EXTINF:364,Bel Canto - Dreaming Girl\n"
plsFile := filepath.Join(os.TempDir(), fmt.Sprintf("navidrome-pls-%d.m3u8", os.Getpid()))
BeforeEach(func() {
DeferCleanup(func() { _ = os.Remove(plsFile) })
})
DescribeTable("writes the playlist to exactly one destination",
func(file, wantStream, wantFile string) {
var out strings.Builder
writePlaylist(m3u, &out, file)
written, _ := os.ReadFile(plsFile)
Expect(out.String()).To(Equal(wantStream))
Expect(string(written)).To(Equal(wantFile))
},
Entry("no file name writes to the stream", "", m3u, ""),
Entry("a dash writes to the stream", "-", m3u, ""),
Entry("a path writes to the file", plsFile, "", m3u),
)
})

View file

@ -4,12 +4,12 @@ import (
"context" "context"
"encoding/csv" "encoding/csv"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
"strconv" "strconv"
"strings" "strings"
"text/tabwriter"
"time" "time"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
@ -244,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().Get(ctx, arg) p, err := ds.Plugin(ctx).Get(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)
} }
@ -265,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().Get(ctx, arg) p, err := ds.Plugin(ctx).Get(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)
} }
@ -308,13 +308,13 @@ 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, strconv.FormatBool(p.Enabled), p.LastError}) _ = w.Write([]string{p.ID, name, version, fmt.Sprintf("%t", p.Enabled), p.LastError})
} }
w.Flush() w.Flush()
return sb.String(), w.Error() return sb.String(), w.Error()
case "table": case "table":
var sb strings.Builder var sb strings.Builder
w := newTabWriter(&sb) w := tabwriter.NewWriter(&sb, 0, 4, 2, ' ', 0)
fmt.Fprintln(w, "ID\tNAME\tVERSION\tENABLED\tLAST ERROR") fmt.Fprintln(w, "ID\tNAME\tVERSION\tENABLED\tLAST ERROR")
for _, p := range list { for _, p := range list {
name, version := manifestSummary(p) name, version := manifestSummary(p)
@ -330,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().GetAll(ctx) list, err := ds.Plugin(ctx).GetAll()
if err != nil { if err != nil {
log.Fatal(ctx, "Failed to list plugins", err) log.Fatal(ctx, "Failed to list plugins", err)
} }
@ -344,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)")
} }
} }
@ -373,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().Get(ctx, args[0]) cur, err := ds.Plugin(ctx).Get(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)
} }
@ -441,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 errors.New("nothing to update: provide at least one of --config/--users/--libraries/--write-access") return fmt.Errorf("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 {
@ -500,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 "", errors.New("invalid JSON in --users") return "", fmt.Errorf("invalid JSON in --users")
} }
return value, nil return value, nil
} }
var names []string var names []string
for u := range strings.SplitSeq(value, ",") { for _, u := range strings.Split(value, ",") {
if u = strings.TrimSpace(u); u != "" { if u = strings.TrimSpace(u); u != "" {
names = append(names, u) names = append(names, u)
} }
} }
b, err := json.Marshal(names) b, _ := json.Marshal(names)
return string(b), err return string(b), nil
} }
// librariesToJSON accepts either a JSON array (starts with '[') or a // librariesToJSON accepts either a JSON array (starts with '[') or a
@ -522,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 "", errors.New("invalid JSON in --libraries") return "", fmt.Errorf("invalid JSON in --libraries")
} }
return value, nil return value, nil
} }
ids := []int{} ids := []int{}
for l := range strings.SplitSeq(value, ",") { for _, l := range strings.Split(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 {
@ -536,8 +536,8 @@ func librariesToJSON(value string) (string, error) {
ids = append(ids, id) ids = append(ids, id)
} }
} }
b, err := json.Marshal(ids) b, _ := json.Marshal(ids)
return string(b), err return string(b), nil
} }
var pluginRescanCmd = &cobra.Command{ var pluginRescanCmd = &cobra.Command{

View file

@ -65,21 +65,16 @@ 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(ctx, mgr, "alpha") err := enablePlugin(context.Background(), 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(ctx, mgr, "beta") err := disablePlugin(context.Background(), mgr, "beta")
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(mgr.DisablePluginCalls).To(Equal([]string{"beta"})) Expect(mgr.DisablePluginCalls).To(Equal([]string{"beta"}))
}) })
@ -87,16 +82,14 @@ 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(ctx, mgr, cur, pluginEditOptions{config: &cfg}) err := applyPluginEdit(context.Background(), 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))
@ -107,7 +100,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(ctx, mgr, cur, err := applyPluginEdit(context.Background(), 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))
@ -118,7 +111,7 @@ var _ = Describe("applyPluginEdit", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
all := true all := true
wr := true wr := true
err := applyPluginEdit(ctx, mgr, cur, err := applyPluginEdit(context.Background(), 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))
@ -129,7 +122,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(ctx, mgr, cur, pluginEditOptions{writeAccess: &no}) err := applyPluginEdit(context.Background(), 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
@ -139,7 +132,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(ctx, mgr, cur, pluginEditOptions{allUsers: &all}) err := applyPluginEdit(context.Background(), 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
}) })
@ -147,7 +140,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(ctx, mgr, cur, pluginEditOptions{users: &users}) err := applyPluginEdit(context.Background(), 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"]`))
}) })
@ -155,7 +148,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(ctx, mgr, cur, pluginEditOptions{users: &users}) err := applyPluginEdit(context.Background(), 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"]`))
}) })
@ -163,7 +156,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(ctx, mgr, cur, pluginEditOptions{users: &users}) err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{users: &users})
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(mgr.UpdatePluginUsersCalls).To(BeEmpty()) Expect(mgr.UpdatePluginUsersCalls).To(BeEmpty())
}) })
@ -171,7 +164,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(ctx, mgr, cur, pluginEditOptions{libraries: &libs}) err := applyPluginEdit(context.Background(), 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]`))
}) })
@ -179,7 +172,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(ctx, mgr, cur, pluginEditOptions{libraries: &libs}) err := applyPluginEdit(context.Background(), mgr, cur, pluginEditOptions{libraries: &libs})
Expect(err).To(HaveOccurred()) Expect(err).To(HaveOccurred())
Expect(mgr.UpdatePluginLibrariesCalls).To(BeEmpty()) Expect(mgr.UpdatePluginLibrariesCalls).To(BeEmpty())
}) })
@ -188,7 +181,7 @@ var _ = Describe("applyPluginEdit", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
cur.AllUsers = true cur.AllUsers = true
users := "alice" users := "alice"
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{users: &users}) err := applyPluginEdit(context.Background(), 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())
@ -198,7 +191,7 @@ var _ = Describe("applyPluginEdit", func() {
mgr := &tests.MockPluginManager{} mgr := &tests.MockPluginManager{}
cur.AllLibraries = true cur.AllLibraries = true
libs := "1" libs := "1"
err := applyPluginEdit(ctx, mgr, cur, pluginEditOptions{libraries: &libs}) err := applyPluginEdit(context.Background(), 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())
@ -206,14 +199,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(ctx, mgr, cur, pluginEditOptions{}) err := applyPluginEdit(context.Background(), 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(ctx, mgr, cur, pluginEditOptions{config: &cfg}) err := applyPluginEdit(context.Background(), 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())
@ -360,7 +353,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(GinkgoT().Context(), mgr) err := rescanPlugins(context.Background(), mgr)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(mgr.RescanPluginsCalls).To(Equal(1)) Expect(mgr.RescanPluginsCalls).To(Equal(1))
}) })

View file

@ -2,7 +2,6 @@ package cmd
import ( import (
"context" "context"
"net/http"
"os" "os"
"os/signal" "os/signal"
"strings" "strings"
@ -12,7 +11,6 @@ import (
"github.com/go-chi/chi/v5/middleware" "github.com/go-chi/chi/v5/middleware"
"github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/artwork"
"github.com/navidrome/navidrome/db" "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"
@ -44,9 +42,7 @@ 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) {
if err := runNavidrome(cmd.Context()); err != nil { runNavidrome(cmd.Context())
log.Fatal("Fatal error in Navidrome. Aborting", err)
}
}, },
PostRun: func(cmd *cobra.Command, args []string) { PostRun: func(cmd *cobra.Command, args []string) {
postRun() postRun()
@ -78,37 +74,31 @@ 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 stops the others and returns that error, so the caller can // If any of the services returns an error, it will log it and exit. If the process receives a signal to exit,
// exit with a non-zero code. If the context is cancelled (a signal or a service stop), it returns nil. // it will cancel the context and exit gracefully.
func runNavidrome(parentCtx context.Context) error { func runNavidrome(ctx context.Context) {
defer db.Init(parentCtx)() defer db.Init(ctx)()
g, ctx := errgroup.WithContext(parentCtx) g, ctx := errgroup.WithContext(ctx)
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))
g.Go(startPluginManager(ctx)) g.Go(startPluginManager(ctx))
artworkWorker := CreateArtworkWorker()
g.Go(startArtworkWorker(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")
} }
// Errors caused by a normal shutdown are not failures if err := g.Wait(); err != nil {
if err := g.Wait(); err != nil && parentCtx.Err() == nil { log.Error("Fatal error in Navidrome. Aborting", err)
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.
@ -128,46 +118,35 @@ func startServer(ctx context.Context) func() error {
a.MountRouter("Native API", consts.URLPathNativeAPI, CreateNativeAPIRouter(ctx)) a.MountRouter("Native API", consts.URLPathNativeAPI, CreateNativeAPIRouter(ctx))
a.MountRouter("Subsonic API", consts.URLPathSubsonicAPI, CreateSubsonicAPIRouter(ctx)) a.MountRouter("Subsonic API", consts.URLPathSubsonicAPI, CreateSubsonicAPIRouter(ctx))
a.MountRouter("Public Endpoints", consts.URLPathPublic, CreatePublicRouter()) a.MountRouter("Public Endpoints", consts.URLPathPublic, CreatePublicRouter())
if conf.Server().LastFM.Enabled { if conf.Server.LastFM.Enabled {
a.MountRouter("LastFM Auth", consts.URLPathNativeAPI+"/lastfm", CreateLastFMRouter()) a.MountRouter("LastFM Auth", consts.URLPathNativeAPI+"/lastfm", CreateLastFMRouter())
} }
if conf.Server().ListenBrainz.Enabled { if conf.Server.ListenBrainz.Enabled {
a.MountRouter("ListenBrainz Auth", consts.URLPathNativeAPI+"/listenbrainz", CreateListenBrainzRouter()) a.MountRouter("ListenBrainz Auth", consts.URLPathNativeAPI+"/listenbrainz", CreateListenBrainzRouter())
} }
if conf.Server().Jellyfin.Enabled { if conf.Server.Jellyfin.Enabled {
a.MountRouter("Jellyfin API", consts.URLPathJellyfinAPI, CreateJellyfinAPIRouter(ctx)) a.MountRouter("Jellyfin API", consts.URLPathJellyfinAPI, CreateJellyfinAPIRouter(ctx))
} }
if conf.Server().DevAPIv1 { if conf.Server.Prometheus.Enabled {
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", middleware.Profiler())
} }
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)
} }
} }
// profilerHandler returns the pprof handler. net/http/pprof resolves the profile
// name from the raw request path, so the BasePath has to come off first.
func profilerHandler() http.Handler {
// A trailing or root slash would make StripPrefix drop the leading slash chi needs.
basePath := strings.TrimRight(conf.Server().BasePath, "/")
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
@ -190,50 +169,46 @@ func schedulePeriodicScan(ctx context.Context) func() error {
} }
} }
// librariesWithChangedPID returns the names of the libraries whose effective PID config differs from func pidHashChanged(ds model.DataStore) (bool, error) {
// the one used by their last finished scan pidAlbum, err := ds.Property(context.Background()).DefaultGet(consts.PIDAlbumKey, "")
func librariesWithChangedPID(ctx context.Context, ds model.DataStore) ([]string, error) {
libs, err := ds.Library().GetAll(ctx)
if err != nil { if err != nil {
return nil, err return false, err
} }
var names []string pidTrack, err := ds.Property(context.Background()).DefaultGet(consts.PIDTrackKey, "")
for _, lib := range libs { if err != nil {
if lib.PIDChanged() { return false, err
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().DefaultGet(ctx, consts.FullScanAfterMigrationFlagKey, "0") fullScanRequired, err := ds.Property(ctx).DefaultGet(consts.FullScanAfterMigrationFlagKey, "0")
if err != nil { if err != nil {
return err return err
} }
inProgress, err := ds.Library().ScanInProgress(ctx) inProgress, err := ds.Library(ctx).ScanInProgress()
if err != nil { if err != nil {
return err return err
} }
pidChangedLibs, err := librariesWithChangedPID(ctx, ds) pidHasChanged, err := pidHashChanged(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" || len(pidChangedLibs) > 0 scanNeeded := scanOnStartup || inProgress || fullScanRequired == "1" || pidHasChanged
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().Delete(ctx, consts.FullScanAfterMigrationFlagKey) _ = ds.Property(ctx).Delete(consts.FullScanAfterMigrationFlagKey)
case len(pidChangedLibs) > 0: case pidHasChanged:
// Includes never-scanned libraries. The scanner rescans in full only the ones that need it log.Warn(ctx, "PID config changed, performing full scan")
log.Warn(ctx, "Libraries with a new or changed PID config, scanning", "libraries", pidChangedLibs) fullScanRequired = "1"
case inProgress: case inProgress:
log.Warn(ctx, "Resuming interrupted scan") log.Warn(ctx, "Resuming interrupted scan")
default: default:
@ -255,7 +230,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
} }
@ -270,7 +245,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
@ -305,7 +280,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
} }
@ -339,13 +314,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
} }
@ -355,23 +330,11 @@ 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
} }
@ -381,65 +344,11 @@ func startPlaybackServer(ctx context.Context) func() error {
} }
} }
// startArtworkWorker starts the background artwork acquisition worker. It always
// runs; the queue is simply empty until something enqueues work into it.
func startArtworkWorker(ctx context.Context, worker *artwork.Worker) func() error {
return func() error {
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)
}
}
// 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
// reports an artwork config change without acting on it.
func scheduleArtworkHousekeeping(ctx context.Context, worker *artwork.Worker) func() error {
return func() error {
schedulerInstance := scheduler.GetInstance()
if _, err := schedulerInstance.Add(consts.ArtworkEnqueueMissingSchedule, func() {
outsideScan(ctx, "artwork missing-state recheck", worker.EnqueueMissingAll)
}); err != nil {
log.Error(ctx, "Error scheduling artwork missing-state recheck", err)
}
if _, err := schedulerInstance.Add(consts.ArtworkPruneSchedule, func() {
outsideScan(ctx, "artwork prune", worker.RunPrune)
}); err != nil {
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
// immediately, not only on the next hourly tick (e.g. after enabling the feature).
outsideScan(ctx, "artwork missing-state recheck", worker.EnqueueMissingAll)
if err := worker.ReconcileConfig(ctx); err != nil {
log.Error(ctx, "Error checking the artwork config fingerprint", err)
}
return nil
}
}
// startPluginManager starts the plugin manager, if configured. // startPluginManager starts the plugin manager, if configured.
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
} }
@ -449,7 +358,6 @@ 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)
@ -486,7 +394,7 @@ func init() {
rootCmd.Flags().String("albumplaycountmode", viper.GetString("albumplaycountmode"), "how to compute playcount for albums. absolute (default) or normalized") rootCmd.Flags().String("albumplaycountmode", viper.GetString("albumplaycountmode"), "how to compute playcount for albums. absolute (default) or normalized")
rootCmd.Flags().Bool("autoimportplaylists", viper.GetBool("autoimportplaylists"), "enable/disable .m3u playlist auto-import`") rootCmd.Flags().Bool("autoimportplaylists", viper.GetBool("autoimportplaylists"), "enable/disable .m3u playlist auto-import`")
rootCmd.Flags().Bool("prometheus.enabled", viper.GetBool("prometheus.enabled"), "enable/disable prometheus metrics endpoint") rootCmd.Flags().Bool("prometheus.enabled", viper.GetBool("prometheus.enabled"), "enable/disable prometheus metrics endpoint`")
rootCmd.Flags().String("prometheus.metricspath", viper.GetString("prometheus.metricspath"), "http endpoint for prometheus metrics") rootCmd.Flags().String("prometheus.metricspath", viper.GetString("prometheus.metricspath"), "http endpoint for prometheus metrics")
_ = viper.BindPFlag("address", rootCmd.Flags().Lookup("address")) _ = viper.BindPFlag("address", rootCmd.Flags().Lookup("address"))

View file

@ -1,89 +0,0 @@
package cmd
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"path"
"runtime/pprof"
"github.com/go-chi/chi/v5"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
"github.com/navidrome/navidrome/persistence/persistencetest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = pprof.NewProfile("nd-profiler-test")
var _ = Describe("profilerHandler", func() {
// Mirrors how server.MountRouter mounts the handler.
mount := func() http.Handler {
router := chi.NewRouter()
router.Mount(path.Join(conf.Server().BasePath, "/debug"), profilerHandler())
return router
}
DescribeTable("serves a named profile",
func(basePath string) {
conf.Update(func(c *conf.Options) { c.BasePath = basePath })
w := httptest.NewRecorder()
target := path.Join(basePath, "/debug/pprof/nd-profiler-test") + "?debug=1"
mount().ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil))
Expect(w.Code).To(Equal(http.StatusOK))
Expect(w.Body.String()).To(HavePrefix("nd-profiler-test profile: total 0"))
},
Entry("without a BasePath", ""),
Entry("with a BasePath", "/music"),
Entry("with a root BasePath", "/"),
Entry("with a trailing-slash BasePath", "/music/"),
)
})
type failingLibraryRepo struct {
model.LibraryRepository
err error
}
func (r failingLibraryRepo) GetAll(context.Context, ...model.QueryOptions) (model.Libraries, error) {
return nil, r.err
}
var _ = Describe("librariesWithChangedPID", func() {
var ctx context.Context
var ds model.DataStore
BeforeEach(func() {
ctx = GinkgoT().Context()
ds = persistence.New(db.Db())
})
It("returns only the libraries whose PID config changed", func() {
pid := model.Library{}.EffectivePID()
persistencetest.SetLibraries(ctx, ds, "/music/same", "/music/changed", "/music/never")
same, err := ds.Library().Get(ctx, 1)
Expect(err).ToNot(HaveOccurred())
same.Name = "Same"
Expect(ds.Library().Put(ctx, same)).To(Succeed())
Expect(ds.Library().Put(ctx, &model.Library{ID: 2, Name: "Changed", Path: "/music/changed", PIDAlbum: "folder"})).To(Succeed())
Expect(ds.Library().Put(ctx, &model.Library{ID: 3, Name: "Never scanned", Path: "/music/never"})).To(Succeed())
Expect(ds.Library().SetScannedPID(ctx, 1, pid)).To(Succeed())
Expect(ds.Library().SetScannedPID(ctx, 2, pid)).To(Succeed())
Expect(librariesWithChangedPID(ctx, ds)).To(ConsistOf("Changed", "Never scanned"))
})
It("returns the error from the repository", func() {
ds = persistencetest.Stub(ds, persistencetest.Repos{Library: func(r model.LibraryRepository) model.LibraryRepository {
return failingLibraryRepo{LibraryRepository: r, err: errors.New("db down")}
}})
_, err := librariesWithChangedPID(ctx, ds)
Expect(err).To(MatchError("db down"))
})
})

View file

@ -9,7 +9,7 @@ import (
"os" "os"
"strings" "strings"
"github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core"
"github.com/navidrome/navidrome/core/playlists" "github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
@ -82,7 +82,7 @@ func runScanner(ctx context.Context) {
sqlDB := db.Db() sqlDB := db.Db()
defer db.Db().Close() defer db.Db().Close()
ds := persistence.New(sqlDB) ds := persistence.New(sqlDB)
pls := playlists.NewPlaylists(ds, artwork.NewUploader(ds)) pls := playlists.NewPlaylists(ds, core.NewImageUploadService())
// Parse targets from command line or file // Parse targets from command line or file
var scanTargets []model.ScanTarget var scanTargets []model.ScanTarget

View file

@ -1,6 +1,7 @@
package cmd package cmd
import ( import (
"context"
"os" "os"
"path/filepath" "path/filepath"
@ -17,7 +18,7 @@ var _ = Describe("trackScanInteractively", func() {
progress <- &scanner.ProgressInfo{Error: "scan failed"} progress <- &scanner.ProgressInfo{Error: "scan failed"}
close(progress) close(progress)
changesDetected, err := trackScanInteractively(GinkgoT().Context(), progress) changesDetected, err := trackScanInteractively(context.Background(), progress)
Expect(changesDetected).To(BeTrue()) Expect(changesDetected).To(BeTrue())
Expect(err).To(MatchError("scan failed")) Expect(err).To(MatchError("scan failed"))
}) })

View file

@ -1,55 +0,0 @@
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.")
}

View file

@ -44,7 +44,7 @@ var svcCmd = &cobra.Command{
} }
type svcControl struct { type svcControl struct {
ctx context.Context //nolint:containedctx // service lifecycle ctx, cancelled by Stop ctx context.Context
cancel context.CancelFunc cancel context.CancelFunc
done chan struct{} done chan struct{}
} }
@ -53,13 +53,8 @@ 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() {
err := runNavidrome(p.ctx) 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
} }
@ -79,15 +74,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"] = "SIGKILL" options["SuccessExitStatus"] = "1 2 8 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,
@ -101,8 +96,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
@ -135,21 +130,19 @@ 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 != "" {
var absPath string conf.Server.ConfigFile, err = filepath.Abs(cfgFile)
absPath, err = filepath.Abs(cfgFile)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
conf.Update(func(c *conf.Options) { c.ConfigFile = absPath }) println(" config file: " + conf.Server.ConfigFile)
println(" config file: " + absPath)
} }
err = svcInstance().Install() err = svcInstance().Install()
if err != nil { if err != nil {

View file

@ -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().FindByUsername(ctx, userID) existingUser, err := tx.User(ctx).FindByUsername(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().GetAll(ctx, model.QueryOptions{Filters: squirrel.Eq{"id": libraryIds}}) user.Libraries, err = tx.Library(ctx).GetAll(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().GetAll(ctx) user.Libraries, err = tx.Library(ctx).GetAll()
if err != nil { if err != nil {
return err return err
} }
} }
err = tx.User().Put(ctx, &user) err = tx.User(ctx).Put(&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().SetUserLibraries(ctx, user.ID, updatedIds) err = tx.User(ctx).SetUserLibraries(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().CountAll(ctx) count, err := tx.User(ctx).CountAll()
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().Delete(ctx, user.ID) return tx.User(ctx).Delete(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().GetAll(ctx, model.QueryOptions{Filters: squirrel.Eq{"id": libraryIds}}) libraries, err := tx.Library(ctx).GetAll(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().GetAll(ctx) libraries, err := tx.Library(ctx).GetAll()
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().Put(ctx, user) err := tx.User(ctx).Put(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().SetUserLibraries(ctx, user.ID, updatedIds) err := tx.User(ctx).SetUserLibraries(user.ID, updatedIds)
if err != nil { if err != nil {
return err return err
} }
@ -393,11 +393,13 @@ func runUserList(ctx context.Context) {
ds, ctx := getAdminContext(ctx) ds, ctx := getAdminContext(ctx)
userList, err := ds.User().ReadAll(ctx) users, err := ds.User(ctx).ReadAll()
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{
@ -469,10 +471,7 @@ func runUserList(ctx context.Context) {
users[idx].Libraries = paths users[idx].Libraries = paths
} }
j, err := json.Marshal(users) j, _ := json.Marshal(users)
if err != nil {
log.Fatal(ctx, "Failed to encode users", err)
}
fmt.Printf("%s\n", j) fmt.Printf("%s\n", j)
} }
} }

View file

@ -4,12 +4,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io"
"os"
"strings"
"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"
@ -18,33 +13,6 @@ 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.
func newTabWriter(out io.Writer) *tabwriter.Writer {
return tabwriter.NewWriter(out, 0, 4, 2, ' ', 0)
}
func getAdminContext(ctx context.Context) (model.DataStore, context.Context) { func getAdminContext(ctx context.Context) (model.DataStore, context.Context) {
sqlDB := db.Db() sqlDB := db.Db()
ds := persistence.New(sqlDB) ds := persistence.New(sqlDB)
@ -57,14 +25,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().FindByUsername(ctx, id) user, err := ds.User(ctx).FindByUsername(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().Get(ctx, id) user, err = ds.User(ctx).Get(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)
} }

View file

@ -21,7 +21,6 @@ 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"
@ -31,7 +30,6 @@ 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"
@ -67,22 +65,25 @@ func CreateNativeAPIRouter(ctx context.Context) *nativeapi.Router {
sqlDB := db.Db() sqlDB := db.Db()
dataStore := persistence.New(sqlDB) dataStore := persistence.New(sqlDB)
share := core.NewShare(dataStore) share := core.NewShare(dataStore)
uploader := artwork.NewUploader(dataStore) imageUploadService := core.NewImageUploadService()
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader) playlistsPlaylists := playlists.NewPlaylists(dataStore, imageUploadService)
insights := metrics.GetInstance(dataStore) insights := metrics.GetInstance(dataStore)
fileCache := artwork.GetImageCache()
fFmpeg := ffmpeg.New()
broker := events.GetBroker() broker := events.GetBroker()
metricsMetrics := metrics.GetPrometheusInstance(dataStore) metricsMetrics := metrics.GetPrometheusInstance(dataStore)
modelScanner := scanner.GetInstance(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics)
watcher := scanner.GetWatcher(dataStore, modelScanner)
manager := plugins.GetManager(dataStore, broker, metricsMetrics) manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager)
matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher)
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, fFmpeg, provider)
cacheWarmer := artwork.NewCacheWarmer(artworkArtwork, fileCache)
modelScanner := scanner.New(ctx, dataStore, cacheWarmer, broker, playlistsPlaylists, metricsMetrics)
watcher := scanner.GetWatcher(dataStore, modelScanner)
library := core.NewLibrary(dataStore, modelScanner, watcher, broker, manager) library := core.NewLibrary(dataStore, modelScanner, watcher, broker, manager)
user := core.NewUser(dataStore, manager) user := core.NewUser(dataStore, manager)
maintenance := core.NewMaintenance(dataStore) maintenance := core.NewMaintenance(dataStore)
agentsAgents := agents.GetAgents(dataStore, manager) router := nativeapi.New(dataStore, share, playlistsPlaylists, insights, library, user, maintenance, manager, imageUploadService)
matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(ctx, dataStore, agentsAgents, matcherMatcher, broker)
quickConnect := quickconnect.GetInstance()
router := nativeapi.New(dataStore, share, playlistsPlaylists, insights, library, user, maintenance, manager, uploader, provider, quickConnect)
return router return router
} }
@ -90,27 +91,27 @@ func CreateSubsonicAPIRouter(ctx context.Context) *subsonic.Router {
sqlDB := db.Db() sqlDB := db.Db()
dataStore := persistence.New(sqlDB) dataStore := persistence.New(sqlDB)
fileCache := artwork.GetImageCache() fileCache := artwork.GetImageCache()
imageStore := artwork.GetImageStore()
fFmpeg := ffmpeg.New() fFmpeg := ffmpeg.New()
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, imageStore, fFmpeg)
transcodingCache := stream.GetTranscodingCache()
mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache)
transcodeDecider := stream.NewTranscodeDecider(dataStore, fFmpeg)
share := core.NewShare(dataStore)
archiver := core.NewArchiver(mediaStreamer, transcodeDecider, dataStore, share, artworkArtwork)
players := core.NewPlayers(dataStore)
broker := events.GetBroker() broker := events.GetBroker()
metricsMetrics := metrics.GetPrometheusInstance(dataStore) metricsMetrics := metrics.GetPrometheusInstance(dataStore)
manager := plugins.GetManager(dataStore, broker, metricsMetrics) manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager) agentsAgents := agents.GetAgents(dataStore, manager)
matcherMatcher := matcher.New(dataStore) matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(ctx, dataStore, agentsAgents, matcherMatcher, broker) provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher)
uploader := artwork.NewUploader(dataStore) artworkArtwork := artwork.NewArtwork(dataStore, fileCache, fFmpeg, provider)
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader) transcodingCache := stream.GetTranscodingCache()
modelScanner := scanner.GetInstance(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics) mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache)
share := core.NewShare(dataStore)
archiver := core.NewArchiver(mediaStreamer, dataStore, share)
players := core.NewPlayers(dataStore)
cacheWarmer := artwork.NewCacheWarmer(artworkArtwork, fileCache)
imageUploadService := core.NewImageUploadService()
playlistsPlaylists := playlists.NewPlaylists(dataStore, imageUploadService)
modelScanner := scanner.New(ctx, dataStore, cacheWarmer, 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
@ -120,33 +121,24 @@ func CreateJellyfinAPIRouter(ctx context.Context) *jellyfin.Router {
sqlDB := db.Db() sqlDB := db.Db()
dataStore := persistence.New(sqlDB) dataStore := persistence.New(sqlDB)
fileCache := artwork.GetImageCache() fileCache := artwork.GetImageCache()
imageStore := artwork.GetImageStore()
fFmpeg := ffmpeg.New() fFmpeg := ffmpeg.New()
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, imageStore, fFmpeg) broker := events.GetBroker()
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager)
matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher)
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, fFmpeg, provider)
transcodingCache := stream.GetTranscodingCache() transcodingCache := stream.GetTranscodingCache()
mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache) mediaStreamer := stream.NewMediaStreamer(dataStore, fFmpeg, transcodingCache)
transcodeDecider := stream.NewTranscodeDecider(dataStore, fFmpeg) transcodeDecider := stream.NewTranscodeDecider(dataStore, fFmpeg)
players := core.NewPlayers(dataStore) players := core.NewPlayers(dataStore)
broker := events.GetBroker()
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
manager := plugins.GetManager(dataStore, broker, metricsMetrics)
playTracker := scrobbler.GetPlayTracker(dataStore, broker, manager) playTracker := scrobbler.GetPlayTracker(dataStore, broker, manager)
uploader := artwork.NewUploader(dataStore) imageUploadService := core.NewImageUploadService()
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader) playlistsPlaylists := playlists.NewPlaylists(dataStore, imageUploadService)
agentsAgents := agents.GetAgents(dataStore, manager)
matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(ctx, dataStore, agentsAgents, matcherMatcher, broker)
sonicSonic := sonic.New(dataStore, manager, matcherMatcher) sonicSonic := sonic.New(dataStore, manager, matcherMatcher)
lyricsLyrics := lyrics.NewLyrics(dataStore, manager) lyricsLyrics := lyrics.NewLyrics(dataStore, manager)
quickConnect := quickconnect.GetInstance() router := jellyfin.New(dataStore, artworkArtwork, mediaStreamer, transcodeDecider, players, playTracker, playlistsPlaylists, provider, sonicSonic, lyricsLyrics)
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
} }
@ -154,15 +146,19 @@ func CreatePublicRouter() *public.Router {
sqlDB := db.Db() sqlDB := db.Db()
dataStore := persistence.New(sqlDB) dataStore := persistence.New(sqlDB)
fileCache := artwork.GetImageCache() fileCache := artwork.GetImageCache()
imageStore := artwork.GetImageStore()
fFmpeg := ffmpeg.New() fFmpeg := ffmpeg.New()
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, imageStore, fFmpeg) broker := events.GetBroker()
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager)
matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher)
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, fFmpeg, provider)
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, transcodeDecider, dataStore, share, artworkArtwork) archiver := core.NewArchiver(mediaStreamer, dataStore, share)
router := public.New(dataStore, artworkArtwork, mediaStreamer, transcodeDecider, share, archiver) router := public.New(dataStore, artworkArtwork, mediaStreamer, share, archiver)
return router return router
} }
@ -180,13 +176,6 @@ 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)
@ -204,22 +193,38 @@ func CreatePrometheus() metrics.Metrics {
func CreateScanner(ctx context.Context) model.Scanner { func CreateScanner(ctx context.Context) model.Scanner {
sqlDB := db.Db() sqlDB := db.Db()
dataStore := persistence.New(sqlDB) dataStore := persistence.New(sqlDB)
fileCache := artwork.GetImageCache()
fFmpeg := ffmpeg.New()
broker := events.GetBroker() broker := events.GetBroker()
uploader := artwork.NewUploader(dataStore)
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader)
metricsMetrics := metrics.GetPrometheusInstance(dataStore) metricsMetrics := metrics.GetPrometheusInstance(dataStore)
modelScanner := scanner.GetInstance(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics) manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager)
matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher)
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, fFmpeg, provider)
cacheWarmer := artwork.NewCacheWarmer(artworkArtwork, fileCache)
imageUploadService := core.NewImageUploadService()
playlistsPlaylists := playlists.NewPlaylists(dataStore, imageUploadService)
modelScanner := scanner.New(ctx, dataStore, cacheWarmer, broker, playlistsPlaylists, metricsMetrics)
return modelScanner return modelScanner
} }
func CreateScanWatcher(ctx context.Context) scanner.Watcher { func CreateScanWatcher(ctx context.Context) scanner.Watcher {
sqlDB := db.Db() sqlDB := db.Db()
dataStore := persistence.New(sqlDB) dataStore := persistence.New(sqlDB)
fileCache := artwork.GetImageCache()
fFmpeg := ffmpeg.New()
broker := events.GetBroker() broker := events.GetBroker()
uploader := artwork.NewUploader(dataStore)
playlistsPlaylists := playlists.NewPlaylists(dataStore, uploader)
metricsMetrics := metrics.GetPrometheusInstance(dataStore) metricsMetrics := metrics.GetPrometheusInstance(dataStore)
modelScanner := scanner.GetInstance(ctx, dataStore, broker, playlistsPlaylists, metricsMetrics) manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager)
matcherMatcher := matcher.New(dataStore)
provider := external.NewProvider(dataStore, agentsAgents, matcherMatcher)
artworkArtwork := artwork.NewArtwork(dataStore, fileCache, fFmpeg, provider)
cacheWarmer := artwork.NewCacheWarmer(artworkArtwork, fileCache)
imageUploadService := core.NewImageUploadService()
playlistsPlaylists := playlists.NewPlaylists(dataStore, imageUploadService)
modelScanner := scanner.New(ctx, dataStore, cacheWarmer, broker, playlistsPlaylists, metricsMetrics)
watcher := scanner.GetWatcher(dataStore, modelScanner) watcher := scanner.GetWatcher(dataStore, modelScanner)
return watcher return watcher
} }
@ -231,32 +236,6 @@ func GetPlaybackServer() playback.PlaybackServer {
return playbackServer return playbackServer
} }
func CreateArtworkWorker() *artwork.Worker {
sqlDB := db.Db()
dataStore := persistence.New(sqlDB)
imageStore := artwork.GetImageStore()
broker := events.GetBroker()
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager)
fFmpeg := ffmpeg.New()
fileCache := artwork.GetImageCache()
worker := artwork.NewWorker(dataStore, imageStore, agentsAgents, fFmpeg, broker, fileCache)
return worker
}
func CreateArtworkResolver(trace *artwork.ChainTrace, live bool) *artwork.TracingResolver {
sqlDB := db.Db()
dataStore := persistence.New(sqlDB)
broker := events.GetBroker()
metricsMetrics := metrics.GetPrometheusInstance(dataStore)
manager := plugins.GetManager(dataStore, broker, metricsMetrics)
agentsAgents := agents.GetAgents(dataStore, manager)
fFmpeg := ffmpeg.New()
tracingResolver := artwork.NewTracingResolver(dataStore, agentsAgents, fFmpeg, trace, live)
return tracingResolver
}
func getPluginManager() *plugins.Manager { func getPluginManager() *plugins.Manager {
sqlDB := db.Db() sqlDB := db.Db()
dataStore := persistence.New(sqlDB) dataStore := persistence.New(sqlDB)
@ -268,7 +247,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, 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))) 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)))
func GetPluginManager(ctx context.Context) *plugins.Manager { func GetPluginManager(ctx context.Context) *plugins.Manager {
manager := getPluginManager() manager := getPluginManager()

View file

@ -14,7 +14,6 @@ import (
"github.com/navidrome/navidrome/core/lyrics" "github.com/navidrome/navidrome/core/lyrics"
"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/scrobbler" "github.com/navidrome/navidrome/core/scrobbler"
"github.com/navidrome/navidrome/core/sonic" "github.com/navidrome/navidrome/core/sonic"
"github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/db"
@ -23,7 +22,6 @@ 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"
@ -37,15 +35,13 @@ 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.GetInstance, scanner.New,
scanner.GetWatcher, scanner.GetWatcher,
metrics.GetPrometheusInstance, metrics.GetPrometheusInstance,
db.Db, db.Db,
@ -60,7 +56,6 @@ var allProviders = wire.NewSet(
wire.Bind(new(core.PluginUnloader), new(*plugins.Manager)), wire.Bind(new(core.PluginUnloader), new(*plugins.Manager)),
wire.Bind(new(plugins.PluginMetricsRecorder), new(metrics.Metrics)), wire.Bind(new(plugins.PluginMetricsRecorder), new(metrics.Metrics)),
wire.Bind(new(core.Watcher), new(scanner.Watcher)), wire.Bind(new(core.Watcher), new(scanner.Watcher)),
wire.Bind(new(playlists.ImageUploadService), new(artwork.Uploader)),
) )
func CreateDataStore() model.DataStore { func CreateDataStore() model.DataStore {
@ -93,12 +88,6 @@ 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,
@ -117,12 +106,6 @@ 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,
@ -153,19 +136,6 @@ func GetPlaybackServer() playback.PlaybackServer {
)) ))
} }
func CreateArtworkWorker() *artwork.Worker {
panic(wire.Build(
allProviders,
))
}
func CreateArtworkResolver(trace *artwork.ChainTrace, live bool) *artwork.TracingResolver {
panic(wire.Build(
allProviders,
artwork.NewTracingResolver,
))
}
func getPluginManager() *plugins.Manager { func getPluginManager() *plugins.Manager {
panic(wire.Build( panic(wire.Build(
allProviders, allProviders,

View file

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

View file

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

View file

@ -1,48 +0,0 @@
package configtest_test
import (
"github.com/navidrome/navidrome/conf"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("RestoreAfterEachSpec", func() {
// Either spec can run first: the second one sees the first one's change if it leaks.
It("starts with the original value (A)", func() {
Expect(conf.Server().UIWelcomeMessage).To(BeEmpty())
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "A" })
})
It("starts with the original value (B)", func() {
Expect(conf.Server().UIWelcomeMessage).To(BeEmpty())
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "B" })
})
// Either container can run first: the second one sees the first one's change if it leaks.
for _, name := range []string{"first", "second"} {
Describe("in the "+name+" Ordered container", Ordered, func() {
It("starts with the original value", func() {
Expect(conf.Server().UIWelcomeMessage).To(BeEmpty())
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = name })
})
It("keeps the change for the rest of the container", func() {
Expect(conf.Server().UIWelcomeMessage).To(Equal(name))
})
})
}
Describe("in an Ordered container", Ordered, func() {
BeforeAll(func() {
conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "ordered" })
})
It("sees the BeforeAll change in the first spec", func() {
Expect(conf.Server().UIWelcomeMessage).To(Equal("ordered"))
})
It("still sees the BeforeAll change in later specs", func() {
Expect(conf.Server().UIWelcomeMessage).To(Equal("ordered"))
})
})
})

View file

@ -2,19 +2,14 @@ package conf
import ( import (
"cmp" "cmp"
"encoding" "encoding/json"
"errors"
"fmt" "fmt"
"math"
"net/url" "net/url"
"os" "os"
"path/filepath" "path/filepath"
"reflect"
"regexp"
"runtime" "runtime"
"slices" "slices"
"strings" "strings"
"sync"
"time" "time"
"github.com/bmatcuk/doublestar/v4" "github.com/bmatcuk/doublestar/v4"
@ -26,12 +21,11 @@ import (
"github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/scheduler" "github.com/navidrome/navidrome/scheduler"
"github.com/navidrome/navidrome/utils/run" "github.com/navidrome/navidrome/utils/run"
"github.com/navidrome/navidrome/utils/slice"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
type Options struct { type configOptions struct {
ConfigFile string `conf:"-"` ConfigFile string
Address string Address string
Port int Port int
UnixSocketPerm string UnixSocketPerm string
@ -73,7 +67,6 @@ type Options struct {
Matcher matcherOptions `json:",omitzero"` Matcher matcherOptions `json:",omitzero"`
RecentlyAddedByModTime bool RecentlyAddedByModTime bool
PreferSortTags bool PreferSortTags bool
EnableNaturalSorting bool
IgnoredArticles string IgnoredArticles string
IndexGroups string IndexGroups string
FFmpegPath string FFmpegPath string
@ -92,7 +85,6 @@ type Options struct {
EnableUserEditing bool EnableUserEditing bool
EnableArtworkUpload bool EnableArtworkUpload bool
MaxImageUploadSize string MaxImageUploadSize string
MaxImageSize string
EnableSharing bool EnableSharing bool
ShareURL string ShareURL string
DefaultShareExpiration time.Duration DefaultShareExpiration time.Duration
@ -102,7 +94,6 @@ type Options struct {
DefaultUIVolume int DefaultUIVolume int
UISearchDebounceMs int UISearchDebounceMs int
UICoverArtSize int UICoverArtSize int
UIAppendRemixers bool // Whether to show remixers after the track artists in the UI
EnableReplayGain bool EnableReplayGain bool
EnableCoverAnimation bool EnableCoverAnimation bool
EnableNowPlaying bool EnableNowPlaying bool
@ -144,13 +135,10 @@ type Options struct {
DevUIShowConfig bool DevUIShowConfig bool
DevNewEventStream bool DevNewEventStream bool
DevOffsetOptimize int DevOffsetOptimize int
DevMaxPlaylistTracksPerRequest int
DevArtworkMaxRequests int DevArtworkMaxRequests int
DevArtworkThrottleBacklogLimit int DevArtworkThrottleBacklogLimit int
DevArtworkThrottleBacklogTimeout time.Duration DevArtworkThrottleBacklogTimeout time.Duration
DevArtworkThrottleBuffered bool DevArtworkThrottleBuffered bool
DevArtworkWorkerConcurrency int
DevArtworkExternalMaxRPS int
DevArtistInfoTimeToLive time.Duration DevArtistInfoTimeToLive time.Duration
DevAlbumInfoTimeToLive time.Duration DevAlbumInfoTimeToLive time.Duration
DevExternalScanner bool DevExternalScanner bool
@ -163,8 +151,6 @@ type Options struct {
DevExternalArtistFetchMultiplier float64 DevExternalArtistFetchMultiplier float64
DevPreserveUnicodeInExternalCalls bool DevPreserveUnicodeInExternalCalls bool
DevEnableMediaFileProbe bool DevEnableMediaFileProbe bool
DevMatchEstimatedContentLength bool
DevAPIv1 bool
} }
type scannerOptions struct { type scannerOptions struct {
@ -179,7 +165,6 @@ 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"
} }
@ -210,14 +195,13 @@ type TagConf struct {
type lastfmOptions struct { type lastfmOptions struct {
Enabled bool Enabled bool
ApiKey string ApiKey string //nolint:gosec
Secret string Secret string //nolint:gosec
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 // Computed from Language, split by comma
} }
type deezerOptions struct { type deezerOptions struct {
@ -225,7 +209,7 @@ type deezerOptions struct {
Language string Language string
// Computed values // Computed values
Languages []string `conf:"-"` // Computed from Language, split by comma Languages []string // Computed from Language, split by comma
} }
type listenBrainzOptions struct { type listenBrainzOptions struct {
@ -241,8 +225,6 @@ 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.
@ -256,7 +238,7 @@ type httpHeaderOptions struct {
type prometheusOptions struct { type prometheusOptions struct {
Enabled bool Enabled bool
MetricsPath string MetricsPath string
Password string Password string //nolint:gosec
} }
type AudioDeviceDefinition []string type AudioDeviceDefinition []string
@ -323,13 +305,26 @@ var currentGOOS = func() string {
return runtime.GOOS return runtime.GOOS
} }
// TLSEnabled reports whether the server serves HTTPS. Both halves are required, var (
// so callers cannot infer it from the certificate alone. Server = &configOptions{}
func (c Options) TLSEnabled() bool { hooks []func()
return c.TLSCert != "" && c.TLSKey != "" )
}
var 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)
@ -340,26 +335,19 @@ func LoadFromFile(confFile string) {
Load(true) Load(true)
} }
func durationNonNegativeOrDefault(val *time.Duration, original time.Duration) {
if val.Nanoseconds() < 0 {
log.Warn("Duration is a negative value. Using default value", "value", *val, "default", original)
*val = original
}
}
func Load(noConfigDump bool) { func Load(noConfigDump bool) {
parseIniFileConfiguration() parseIniFileConfiguration()
remapEnvVarKeysFromConfig() remapEnvVarKeysFromConfig()
// Map deprecated options to their new names for backwards compatibility // Map deprecated options to their new names for backwards compatibility
for _, o := range deprecatedOptions { mapDeprecatedOption("ReverseProxyWhitelist", "ExtAuth.TrustedSources")
if o.replacement != "" { mapDeprecatedOption("ReverseProxyUserHeader", "ExtAuth.UserHeader")
mapDeprecatedOption(o.name, o.replacement) mapDeprecatedOption("HTTPSecurityHeaders.CustomFrameOptionsValue", "HTTPHeaders.FrameOptions")
} mapDeprecatedOption("CoverJpegQuality", "CoverArtQuality")
} mapDeprecatedOption("SimilarSongsMatchThreshold", "Matcher.FuzzyThreshold")
mapDeprecatedOption("EnableTranscodingCancellation", "Transcoding.EnableCancellation")
s := clone(current.Load()) err := viper.Unmarshal(&Server, viper.DecodeHook(
err := viper.Unmarshal(s, viper.DecodeHook(
mapstructure.ComposeDecodeHookFunc( mapstructure.ComposeDecodeHookFunc(
mapstructure.TextUnmarshallerHookFunc(), mapstructure.TextUnmarshallerHookFunc(),
mapstructure.StringToTimeDurationHookFunc(), mapstructure.StringToTimeDurationHookFunc(),
@ -371,35 +359,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 := s.validateEnforceNonRootUser(); err != nil { if err := validateEnforceNonRootUser(); err != nil {
logFatal(err) logFatal(err)
} }
if s.CacheFolder.String() == "" { if Server.CacheFolder.String() == "" {
s.CacheFolder = NewDir(filepath.Join(s.DataFolder.String(), "cache")) Server.CacheFolder = NewDir(filepath.Join(Server.DataFolder.String(), "cache"))
} }
if s.Plugins.Enabled { if Server.Plugins.Enabled {
if s.Plugins.Folder.String() == "" { if Server.Plugins.Folder.String() == "" {
s.Plugins.Folder = NewDirWithPerm(filepath.Join(s.DataFolder.String(), "plugins"), 0700) Server.Plugins.Folder = NewDirWithPerm(filepath.Join(Server.DataFolder.String(), "plugins"), 0700)
} else { } else {
s.Plugins.Folder = NewDirWithPerm(s.Plugins.Folder.String(), 0700) Server.Plugins.Folder = NewDirWithPerm(Server.Plugins.Folder.String(), 0700)
} }
} }
s.ConfigFile = viper.GetViper().ConfigFileUsed() Server.ConfigFile = viper.GetViper().ConfigFileUsed()
if s.DbPath == "" { if Server.DbPath == "" {
s.DbPath = filepath.Join(s.DataFolder.String(), consts.DefaultDbPath) Server.DbPath = filepath.Join(Server.DataFolder.String(), consts.DefaultDbPath)
} }
out := os.Stderr out := os.Stderr
if s.LogFile != "" { if Server.LogFile != "" {
if mkErr := os.MkdirAll(filepath.Dir(s.LogFile), os.ModePerm); mkErr != nil { if mkErr := os.MkdirAll(filepath.Dir(Server.LogFile), os.ModePerm); mkErr != nil {
logFatal("Error creating log file directory: " + mkErr.Error()) logFatal(fmt.Sprintf("Error creating log file directory: %s", mkErr.Error()))
} }
out, err = os.OpenFile(s.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) out, err = os.OpenFile(Server.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil { if err != nil {
logFatal(fmt.Sprintf("Error opening log file %s: %s", s.LogFile, err.Error())) logFatal(fmt.Sprintf("Error opening log file %s: %s", Server.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") != "" {
@ -410,64 +398,40 @@ func Load(noConfigDump bool) {
log.EnableJournalFormat() log.EnableJournalFormat()
} }
log.SetLevelString(s.LogLevel) log.SetLevelString(Server.LogLevel)
log.SetLogLevels(s.DevLogLevels) log.SetLogLevels(Server.DevLogLevels)
log.SetLogSourceLine(s.DevLogSourceLine) log.SetLogSourceLine(Server.DevLogSourceLine)
log.SetRedacting(s.EnableLogRedacting) log.SetRedacting(Server.EnableLogRedacting)
durationNonNegativeOrDefault(&s.SessionTimeout, consts.DefaultSessionTimeout)
durationNonNegativeOrDefault(&s.SmartPlaylistRefreshDelay, consts.DefaultSmartRefresh)
durationNonNegativeOrDefault(&s.DefaultShareExpiration, consts.DefaultShareExpiration)
durationNonNegativeOrDefault(&s.UIPlaybackReportInterval, consts.DefaultUIPlaybackReportInterval)
durationNonNegativeOrDefault(&s.AuthWindowLength, consts.DefaultAuthWindowLength)
durationNonNegativeOrDefault(&s.Scanner.WatcherWait, consts.DefaultWatcherWait)
durationNonNegativeOrDefault(&s.DevActivityPanelUpdateRate, consts.DefaultActivityPanelUpdateRate)
durationNonNegativeOrDefault(&s.DevArtworkThrottleBacklogTimeout, consts.RequestThrottleBacklogTimeout)
durationNonNegativeOrDefault(&s.DevArtistInfoTimeToLive, consts.ArtistInfoTimeToLive)
durationNonNegativeOrDefault(&s.DevAlbumInfoTimeToLive, consts.AlbumInfoTimeToLive)
durationNonNegativeOrDefault(&s.DevInsightsInitialDelay, consts.InsightsInitialDelay)
durationNonNegativeOrDefault(&s.DevPluginCompilationTimeout, consts.DefaultPluginCompilationTimeout)
durationNonNegativeOrDefault(&s.LastFM.MinScrobbleDuration, consts.DefaultMinScrobbleDuration)
// Log deprecated, removed and unknown options
for _, o := range deprecatedOptions {
logDeprecatedOptions(o.name, o.replacement)
}
logRemovedOptions(removedOptions...)
logUnknownOptions()
err = run.Sequentially( err = run.Sequentially(
s.validateScanSchedule, validateScanSchedule,
s.validateBackupSchedule, validateBackupSchedule,
s.validatePlaylistsPath, validatePlaylistsPath,
s.validatePurgeMissingOption, validatePurgeMissingOption,
validateByteSize("MaxImageUploadSize", s.MaxImageUploadSize), validateMaxImageUploadSize,
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)
} }
s.Search.Backend = normalizeSearchBackend(s.Search.Backend) Server.Search.Backend = normalizeSearchBackend(Server.Search.Backend)
if s.BaseURL != "" { if Server.BaseURL != "" {
u, err := url.Parse(s.BaseURL) u, err := url.Parse(Server.BaseURL)
if err != nil { if err != nil {
logFatal("Invalid BaseURL:", err) logFatal("Invalid BaseURL:", err)
} }
s.BasePath = u.Path Server.BasePath = u.Path
u.Path = "" u.Path = ""
u.RawQuery = "" u.RawQuery = ""
s.BaseHost = u.Host Server.BaseHost = u.Host
s.BaseScheme = u.Scheme Server.BaseScheme = u.Scheme
} }
// Log configuration source // Log configuration source
if s.ConfigFile != "" { if Server.ConfigFile != "" {
log.Info("Loaded configuration", "file", s.ConfigFile) log.Info("Loaded configuration", "file", Server.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 {
@ -476,75 +440,58 @@ 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", s) prettyConf := pretty.Sprintf("Configuration: %# v", Server)
if s.EnableLogRedacting { if Server.EnableLogRedacting {
prettyConf = log.Redact(prettyConf) prettyConf = log.Redact(prettyConf)
} }
_, _ = fmt.Fprintln(out, prettyConf) _, _ = fmt.Fprintln(out, prettyConf)
} }
if !s.EnableExternalServices { if !Server.EnableExternalServices {
s.disableExternalServices() disableExternalServices()
} }
// Make sure we don't have empty PIDs // Make sure we don't have empty PIDs
s.PID.Album = cmp.Or(s.PID.Album, consts.DefaultAlbumPID) Server.PID.Album = cmp.Or(Server.PID.Album, consts.DefaultAlbumPID)
s.PID.Track = cmp.Or(s.PID.Track, consts.DefaultTrackPID) Server.PID.Track = cmp.Or(Server.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)
s.LastFM.Languages = parseLanguages(s.LastFM.Language) Server.LastFM.Languages = parseLanguages(Server.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)
s.Deezer.Languages = parseLanguages(s.Deezer.Language) Server.Deezer.Languages = parseLanguages(Server.Deezer.Language)
// Deprecated options
logDeprecatedOptions("Scanner.GenreSeparators", "")
logDeprecatedOptions("Scanner.GroupAlbumReleases", "")
logDeprecatedOptions("DevEnableBufferedScrobble", "") // Deprecated: Buffered scrobbling is now always enabled and this option is ignored
logDeprecatedOptions("SearchFullString", "Search.FullString")
logDeprecatedOptions("ReverseProxyWhitelist", "ExtAuth.TrustedSources")
logDeprecatedOptions("ReverseProxyUserHeader", "ExtAuth.UserHeader")
logDeprecatedOptions("HTTPSecurityHeaders.CustomFrameOptionsValue", "HTTPHeaders.FrameOptions")
logDeprecatedOptions("CoverJpegQuality", "CoverArtQuality")
logDeprecatedOptions("SimilarSongsMatchThreshold", "Matcher.FuzzyThreshold")
logDeprecatedOptions("EnableTranscodingCancellation", "Transcoding.EnableCancellation")
// Removed options
logRemovedOptions("Spotify.ID", "Spotify.Secret")
// Validate other options // Validate other options
if s.UICoverArtSize < 200 || s.UICoverArtSize > 1200 { if Server.UICoverArtSize < 200 || Server.UICoverArtSize > 1200 {
newValue := max(200, min(1200, s.UICoverArtSize)) newValue := max(200, min(1200, Server.UICoverArtSize))
log.Warn("UICoverArtSize must be between 200 and 1200, clamping", "value", s.UICoverArtSize, "newValue", newValue) log.Warn("UICoverArtSize must be between 200 and 1200, clamping", "value", Server.UICoverArtSize, "newValue", newValue)
s.UICoverArtSize = newValue Server.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.
imgSize, _ := humanize.ParseBytes(s.MaxImageSize)
uploadSize, _ := humanize.ParseBytes(s.MaxImageUploadSize)
if imgSize < uploadSize {
log.Warn("MaxImageSize must be at least MaxImageUploadSize, raising", "value", s.MaxImageSize, "newValue", s.MaxImageUploadSize)
s.MaxImageSize = s.MaxImageUploadSize
}
current.Store(s)
// Call init hooks // Call init hooks
for _, hook := range hooks { for _, hook := range hooks {
hook() hook()
} }
} }
// deprecatedOptions still work, but will be removed in a future release. An empty
// replacement means the option is now ignored.
var deprecatedOptions = []struct{ name, replacement string }{
{"Scanner.GenreSeparators", ""},
{"Scanner.GroupAlbumReleases", ""},
{"DevEnableBufferedScrobble", ""},
{"SearchFullString", "Search.FullString"},
{"ReverseProxyWhitelist", "ExtAuth.TrustedSources"},
{"ReverseProxyUserHeader", "ExtAuth.UserHeader"},
{"HTTPSecurityHeaders.CustomFrameOptionsValue", "HTTPHeaders.FrameOptions"},
{"CoverJpegQuality", "CoverArtQuality"},
{"SimilarSongsMatchThreshold", "Matcher.FuzzyThreshold"},
{"EnableTranscodingCancellation", "Transcoding.EnableCancellation"},
}
var removedOptions = []string{"Spotify.ID", "Spotify.Secret"}
func logDeprecatedOptions(oldName, newName string) { func logDeprecatedOptions(oldName, newName string) {
envVar := envVarName(oldName) envVar := "ND_" + strings.ToUpper(strings.ReplaceAll(oldName, ".", "_"))
newEnvVar := envVarName(newName) newEnvVar := "ND_" + strings.ToUpper(strings.ReplaceAll(newName, ".", "_"))
logWarning := func(oldName, newName string) { logWarning := func(oldName, newName string) {
if newName != "" { if newName != "" {
log.Warn(fmt.Sprintf("Option '%s' is deprecated and will be ignored in a future release. Please use the new '%s'", oldName, newName)) log.Warn(fmt.Sprintf("Option '%s' is deprecated and will be ignored in a future release. Please use the new '%s'", oldName, newName))
@ -564,7 +511,7 @@ func logDeprecatedOptions(oldName, newName string) {
// not available anymore // not available anymore
func logRemovedOptions(options ...string) { func logRemovedOptions(options ...string) {
for _, option := range options { for _, option := range options {
envVar := envVarName(option) envVar := "ND_" + strings.ToUpper(strings.ReplaceAll(option, ".", "_"))
logWarning := func(option string) { logWarning := func(option string) {
log.Warn(fmt.Sprintf("Option '%s' is not available anymore and will be ignored. Please remove it from your config", option)) log.Warn(fmt.Sprintf("Option '%s' is not available anymore and will be ignored. Please remove it from your config", option))
} }
@ -585,193 +532,35 @@ func remapEnvVarKeysFromConfig() {
continue continue
} }
stripped := strings.TrimPrefix(key, "nd_") stripped := strings.TrimPrefix(key, "nd_")
canonicalKey := ndKeyToCanonical(key) canonicalKey := strings.ReplaceAll(stripped, "_", ".")
displayNDKey := "ND_" + strings.ToUpper(stripped) displayNDKey := "ND_" + strings.ToUpper(stripped)
canonicalName := canonicalOptionName(canonicalKey) displayCanonical := toPascalCase(canonicalKey)
if viper.InConfig(canonicalKey) { if viper.InConfig(canonicalKey) {
logFatal(fmt.Sprintf( logFatal(fmt.Sprintf(
"Config file contains both '%s' and '%s'. Remove the ND_-prefixed version. "+ "Config file contains both '%s' and '%s'. Remove the ND_-prefixed version. "+
"The 'ND_' prefix is only needed for environment variables, not config file keys.", "The 'ND_' prefix is only needed for environment variables, not config file keys.",
displayNDKey, cmp.Or(canonicalName, toPascalCase(canonicalKey)), displayNDKey, displayCanonical,
)) ))
return return
} }
viper.Set(canonicalKey, viper.Get(key)) viper.Set(canonicalKey, viper.Get(key))
// Unknown keys get no advice here, logUnknownOptions reports them instead
if canonicalName != "" {
_, _ = fmt.Fprintf(os.Stderr, "WARNING: Config key '%s' uses environment variable naming. Use '%s' instead. "+ _, _ = fmt.Fprintf(os.Stderr, "WARNING: Config key '%s' uses environment variable naming. Use '%s' instead. "+
"The 'ND_' prefix is only needed for environment variables.\n", "The 'ND_' prefix is only needed for environment variables.\n",
displayNDKey, canonicalName, displayNDKey, displayCanonical,
) )
} }
} }
}
// mapDeprecatedOption is used to provide backwards compatibility for deprecated options. It should be called after // mapDeprecatedOption is used to provide backwards compatibility for deprecated options. It should be called after
// the config has been read by viper, but before unmarshalling it into the Config struct. // the config has been read by viper, but before unmarshalling it into the Config struct.
func mapDeprecatedOption(legacyName, newName string) { func mapDeprecatedOption(legacyName, newName string) {
// viper.Set outranks the config file, so an explicit replacement must win over the legacy value if viper.IsSet(legacyName) {
if viper.IsSet(legacyName) && !explicitlySet(newName) {
viper.Set(newName, viper.Get(legacyName)) viper.Set(newName, viper.Get(legacyName))
} }
} }
// explicitlySet reports whether the user provided the option, ignoring defaults,
// which viper.IsSet counts as set. The ND_ spelling is also accepted in the config
// file, and remapEnvVarKeysFromConfig has already moved it out of InConfig's reach.
func explicitlySet(name string) bool {
envVar := envVarName(name)
return viper.InConfig(name) || os.Getenv(envVar) != "" || viper.InConfig(strings.ToLower(envVar))
}
func envVarName(option string) string {
if option == "" {
return ""
}
return "ND_" + strings.ToUpper(strings.ReplaceAll(option, ".", "_"))
}
func logUnknownOptions() {
for _, key := range unknownConfigKeys() {
msg := fmt.Sprintf("Option '%s' is not recognized and will be ignored", key)
if matches := suggestOptions(key); len(matches) > 0 {
msg += fmt.Sprintf(". Did you mean '%s'?", strings.Join(matches, "' or '"))
}
log.Warn(msg)
}
}
// suggestOptions returns the known options sharing the last segment with key,
// catching options written outside their section.
func suggestOptions(key string) []string {
key = strings.ToLower(key)
leaf := leafKey(key)
canonical, _ := configKeys()
var matches []string
for known, name := range canonical {
// Removed options are known only so they get their own warning, never suggest them
if known != key && leafKey(known) == leaf && !slices.Contains(removedOptions, name) {
matches = append(matches, name)
}
}
slices.Sort(matches)
return matches
}
func leafKey(key string) string {
return key[strings.LastIndex(key, ".")+1:]
}
// unknownConfigKeys returns config file keys that don't match any known option, so
// typos and options written outside their section don't fail silently.
func unknownConfigKeys() []string {
// INI files keep the original [default] section alongside the merged one
skipDefault := strings.EqualFold(filepath.Ext(viper.ConfigFileUsed()), ".ini")
var unknown []string
for _, key := range viper.AllKeys() {
if !viper.InConfig(key) || canonicalOptionName(key) != "" {
continue
}
if skipDefault && strings.HasPrefix(key, "default.") {
continue
}
// Only ND_-prefixed keys that remapEnvVarKeysFromConfig could resolve are valid
if strings.HasPrefix(key, "nd_") && canonicalOptionName(ndKeyToCanonical(key)) != "" {
continue
}
unknown = append(unknown, key)
}
slices.Sort(unknown)
return asWrittenInConfigFile(unknown)
}
func ndKeyToCanonical(key string) string {
return strings.ReplaceAll(strings.TrimPrefix(key, "nd_"), "_", ".")
}
// canonicalOptionName returns the documented spelling of a known option key, or ""
// if it matches no option. Subkeys of free-form maps have no fixed spelling.
func canonicalOptionName(key string) string {
keys, prefixes := configKeys()
if name, ok := keys[key]; ok {
return name
}
if slices.ContainsFunc(prefixes, func(p string) bool { return strings.HasPrefix(key, p) }) {
return toPascalCase(key)
}
return ""
}
// asWrittenInConfigFile restores the casing the keys have in the config file, as
// viper lowercases every key it loads.
func asWrittenInConfigFile(keys []string) []string {
if len(keys) == 0 {
return nil
}
data, err := os.ReadFile(viper.ConfigFileUsed())
if err != nil {
return keys
}
casing := map[string]string{}
for _, match := range configFileKeyRx.FindAllStringSubmatch(string(data), -1) {
for segment := range strings.SplitSeq(match[1], ".") {
lower := strings.ToLower(segment)
casing[lower] = cmp.Or(casing[lower], segment)
}
}
return slice.Map(keys, func(key string) string {
segments := strings.Split(key, ".")
for i, s := range segments {
segments[i] = cmp.Or(casing[s], s)
}
return strings.Join(segments, ".")
})
}
// configFileKeyRx matches keys and section headers in all supported config formats.
var configFileKeyRx = regexp.MustCompile(`(?m)^\s*\[?\s*"?([\w.]+)"?\s*[]=:]`)
// configKeys maps every accepted option name, lowercased, to its canonical spelling,
// plus the prefixes of free-form map options (Tags, DevLogLevels).
var configKeys = sync.OnceValues(func() (map[string]string, []string) {
keys := map[string]string{}
var prefixes []string
var collect func(t reflect.Type, prefix string)
collect = func(t reflect.Type, prefix string) {
for field := range t.Fields() {
// `conf:"-"` marks values computed during Load, not settable in the config
if !field.IsExported() || field.Tag.Get("conf") == "-" {
continue
}
name := prefix + field.Name
if field.Type.Kind() == reflect.Struct && !reflect.PointerTo(field.Type).Implements(textUnmarshalerType) {
collect(field.Type, name+".")
continue
}
lower := strings.ToLower(name)
keys[lower] = name
if field.Type.Kind() == reflect.Map {
prefixes = append(prefixes, lower+".")
}
}
}
collect(reflect.TypeFor[Options](), "")
for _, o := range deprecatedOptions {
keys[strings.ToLower(o.name)] = o.name
}
for _, o := range removedOptions {
keys[strings.ToLower(o)] = o
}
return keys, prefixes
})
var textUnmarshalerType = reflect.TypeFor[encoding.TextUnmarshaler]()
// parseIniFileConfiguration is used to parse the config file when it is in INI format. For INI files, it // parseIniFileConfiguration is used to parse the config file when it is in INI format. For INI files, it
// would require a nested structure, so instead we unmarshal it to a map and then merge the nested [default] // would require a nested structure, so instead we unmarshal it to a map and then merge the nested [default]
// section into the root level. // section into the root level.
@ -794,21 +583,21 @@ func parseIniFileConfiguration() {
} }
} }
func (s *Options) disableExternalServices() { func disableExternalServices() {
log.Info("All external integrations are DISABLED!") log.Info("All external integrations are DISABLED!")
s.EnableInsightsCollector = false Server.EnableInsightsCollector = false
s.EnableM3UExternalAlbumArt = false Server.EnableM3UExternalAlbumArt = false
s.LastFM.Enabled = false Server.LastFM.Enabled = false
s.Deezer.Enabled = false Server.Deezer.Enabled = false
s.ListenBrainz.Enabled = false Server.ListenBrainz.Enabled = false
s.Agents = "" Server.Agents = ""
if s.UILoginBackgroundURL == consts.DefaultUILoginBackgroundURL { if Server.UILoginBackgroundURL == consts.DefaultUILoginBackgroundURL {
s.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURLOffline Server.UILoginBackgroundURL = consts.DefaultUILoginBackgroundURLOffline
} }
} }
func (s *Options) validatePlaylistsPath() error { func validatePlaylistsPath() error {
for path := range strings.SplitSeq(s.PlaylistsPath, string(filepath.ListSeparator)) { for path := range strings.SplitSeq(Server.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)
@ -833,62 +622,53 @@ func parseLanguages(lang string) []string {
return languages return languages
} }
func (s *Options) validatePurgeMissingOption() error { func validatePurgeMissingOption() error {
allowedValues := []string{consts.PurgeMissingNever, consts.PurgeMissingAlways, consts.PurgeMissingFull} allowedValues := []string{consts.PurgeMissingNever, consts.PurgeMissingAlways, consts.PurgeMissingFull}
valid := slices.Contains(allowedValues, s.Scanner.PurgeMissing) valid := slices.Contains(allowedValues, Server.Scanner.PurgeMissing)
if !valid { if !valid {
err := fmt.Errorf("invalid Scanner.PurgeMissing value: '%s'. Must be one of: %v", s.Scanner.PurgeMissing, allowedValues) err := fmt.Errorf("invalid Scanner.PurgeMissing value: '%s'. Must be one of: %v", Server.Scanner.PurgeMissing, allowedValues)
s.Scanner.PurgeMissing = consts.PurgeMissingNever Server.Scanner.PurgeMissing = consts.PurgeMissingNever
return err return err
} }
return nil return nil
} }
func validateByteSize(name, value string) func() error { func validateMaxImageUploadSize() error {
return func() error { if _, err := humanize.ParseBytes(Server.MaxImageUploadSize); err != nil {
size, err := humanize.ParseBytes(value) return fmt.Errorf("invalid MaxImageUploadSize %q: use values like '10MB', '1GB', or raw bytes like '10485760': %w", Server.MaxImageUploadSize, err)
if err != nil {
return fmt.Errorf("invalid %s %q: use values like '10MB', '1GB', or raw bytes like '10485760': %w", name, value, err)
}
if size == 0 {
return fmt.Errorf("invalid %s %q: must be greater than zero", name, value)
}
if size > math.MaxInt64 {
return fmt.Errorf("invalid %s %q: value is too large", name, value)
} }
return nil return nil
} }
}
func (s *Options) validateEnforceNonRootUser() error { func validateEnforceNonRootUser() error {
if !s.EnforceNonRootUser || currentGOOS() == "windows" { if !Server.EnforceNonRootUser || currentGOOS() == "windows" {
return nil return nil
} }
if getEUID() == 0 { if getEUID() == 0 {
return errors.New("EnforceNonRootUser is enabled but Navidrome is running as root") return fmt.Errorf("EnforceNonRootUser is enabled but Navidrome is running as root")
} }
return nil return nil
} }
func (s *Options) validateScanSchedule() error { func validateScanSchedule() error {
if s.Scanner.Schedule == "0" || s.Scanner.Schedule == "" { if Server.Scanner.Schedule == "0" || Server.Scanner.Schedule == "" {
s.Scanner.Schedule = "" Server.Scanner.Schedule = ""
return nil return nil
} }
var err error var err error
s.Scanner.Schedule, err = validateSchedule(s.Scanner.Schedule, "Scanner.Schedule") Server.Scanner.Schedule, err = validateSchedule(Server.Scanner.Schedule, "Scanner.Schedule")
return err return err
} }
func (s *Options) validateBackupSchedule() error { func validateBackupSchedule() error {
if s.Backup.Path.String() == "" || s.Backup.Schedule == "" || s.Backup.Count == 0 { if Server.Backup.Path.String() == "" || Server.Backup.Schedule == "" || Server.Backup.Count == 0 {
s.Backup.Schedule = "" Server.Backup.Schedule = ""
return nil return nil
} }
var err error var err error
s.Backup.Schedule, err = validateSchedule(s.Backup.Schedule, "Backup.Schedule") Server.Backup.Schedule, err = validateSchedule(Server.Backup.Schedule, "Backup.Schedule")
return err return err
} }
@ -987,7 +767,7 @@ func setViperDefaults() {
viper.SetDefault("autoimportplaylists", true) viper.SetDefault("autoimportplaylists", true)
viper.SetDefault("defaultplaylistpublicvisibility", false) viper.SetDefault("defaultplaylistpublicvisibility", false)
viper.SetDefault("playlistspath", "") viper.SetDefault("playlistspath", "")
viper.SetDefault("smartPlaylistRefreshDelay", consts.DefaultSmartRefresh) viper.SetDefault("smartPlaylistRefreshDelay", 5*time.Second)
viper.SetDefault("enabledownloads", true) viper.SetDefault("enabledownloads", true)
viper.SetDefault("enableexternalservices", true) viper.SetDefault("enableexternalservices", true)
viper.SetDefault("enablem3uexternalalbumart", false) viper.SetDefault("enablem3uexternalalbumart", false)
@ -1000,7 +780,6 @@ func setViperDefaults() {
viper.SetDefault("matcher.fuzzythreshold", 85) viper.SetDefault("matcher.fuzzythreshold", 85)
viper.SetDefault("recentlyaddedbymodtime", false) viper.SetDefault("recentlyaddedbymodtime", false)
viper.SetDefault("prefersorttags", false) viper.SetDefault("prefersorttags", false)
viper.SetDefault("enablenaturalsorting", false)
viper.SetDefault("ignoredarticles", "The El La Los Las Le Les Os As O A") viper.SetDefault("ignoredarticles", "The El La Los Las Le Les Os As O A")
viper.SetDefault("indexgroups", "A B C D E F G H I J K L M N O P Q R S T U V W X-Z(XYZ) [Unknown]([)") viper.SetDefault("indexgroups", "A B C D E F G H I J K L M N O P Q R S T U V W X-Z(XYZ) [Unknown]([)")
viper.SetDefault("ffmpegpath", "") viper.SetDefault("ffmpegpath", "")
@ -1022,24 +801,22 @@ 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)
viper.SetDefault("uiplaybackreportinterval", consts.DefaultUIPlaybackReportInterval) viper.SetDefault("uiplaybackreportinterval", consts.DefaultUIPlaybackReportInterval)
viper.SetDefault("enableartworkupload", true) viper.SetDefault("enableartworkupload", true)
viper.SetDefault("maximageuploadsize", consts.DefaultMaxImageUploadSize) viper.SetDefault("maximageuploadsize", consts.DefaultMaxImageUploadSize)
viper.SetDefault("maximagesize", consts.DefaultMaxImageSize)
viper.SetDefault("enablesharing", true) viper.SetDefault("enablesharing", true)
viper.SetDefault("shareurl", "") viper.SetDefault("shareurl", "")
viper.SetDefault("defaultshareexpiration", consts.DefaultShareExpiration) viper.SetDefault("defaultshareexpiration", 8760*time.Hour)
viper.SetDefault("defaultdownloadableshare", false) viper.SetDefault("defaultdownloadableshare", false)
viper.SetDefault("gatrackingid", "") viper.SetDefault("gatrackingid", "")
viper.SetDefault("enableinsightscollector", true) viper.SetDefault("enableinsightscollector", true)
viper.SetDefault("enablescheduleddbanalyze", true) viper.SetDefault("enablescheduleddbanalyze", true)
viper.SetDefault("enablelogredacting", true) viper.SetDefault("enablelogredacting", true)
viper.SetDefault("authrequestlimit", 5) viper.SetDefault("authrequestlimit", 5)
viper.SetDefault("authwindowlength", consts.DefaultAuthWindowLength) viper.SetDefault("authwindowlength", 20*time.Second)
viper.SetDefault("passwordencryptionkey", "") viper.SetDefault("passwordencryptionkey", "")
viper.SetDefault("extauth.userheader", "Remote-User") viper.SetDefault("extauth.userheader", "Remote-User")
viper.SetDefault("extauth.trustedsources", "") viper.SetDefault("extauth.trustedsources", "")
@ -1062,7 +839,6 @@ 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)
@ -1080,7 +856,6 @@ 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)
@ -1089,8 +864,6 @@ 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", "")
@ -1119,9 +892,7 @@ 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))
@ -1129,12 +900,6 @@ func setViperDefaults() {
viper.SetDefault("devartworkthrottlebackloglimit", consts.RequestThrottleBacklogLimit) viper.SetDefault("devartworkthrottlebackloglimit", consts.RequestThrottleBacklogLimit)
viper.SetDefault("devartworkthrottlebacklogtimeout", consts.RequestThrottleBacklogTimeout) viper.SetDefault("devartworkthrottlebacklogtimeout", consts.RequestThrottleBacklogTimeout)
viper.SetDefault("devartworkthrottlebuffered", true) viper.SetDefault("devartworkthrottlebuffered", true)
// Half the CPU count (min 2), so local resolution scales with the host but stays under the
// SQLite pool (MaxOpenConns) — leaving connections for the scanner, scrobbles and the UI.
viper.SetDefault("devartworkworkerconcurrency", max(2, runtime.NumCPU()/2))
// External RPS gates outbound calls to third-party services (per service); it is bounded by
// their tolerance, not the host, so it stays a small constant regardless of CPU count.
viper.SetDefault("devartworkexternalmaxrps", 2)
viper.SetDefault("devartistinfotimetolive", consts.ArtistInfoTimeToLive) viper.SetDefault("devartistinfotimetolive", consts.ArtistInfoTimeToLive)
viper.SetDefault("devalbuminfotimetolive", consts.AlbumInfoTimeToLive) viper.SetDefault("devalbuminfotimetolive", consts.AlbumInfoTimeToLive)
viper.SetDefault("devexternalscanner", true) viper.SetDefault("devexternalscanner", true)
@ -1147,7 +912,6 @@ func setViperDefaults() {
viper.SetDefault("devexternalartistfetchmultiplier", 1.5) viper.SetDefault("devexternalartistfetchmultiplier", 1.5)
viper.SetDefault("devpreserveunicodeinexternalcalls", false) viper.SetDefault("devpreserveunicodeinexternalcalls", false)
viper.SetDefault("devenablemediafileprobe", true) viper.SetDefault("devenablemediafileprobe", true)
viper.SetDefault("devmatchestimatedcontentlength", true)
} }
func init() { func init() {

View file

@ -1,18 +1,12 @@
package conf_test package conf_test
import ( import (
"bytes"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"testing" "testing"
"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/log"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/spf13/viper" "github.com/spf13/viper"
@ -23,8 +17,6 @@ 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
@ -34,7 +26,10 @@ var _ = Describe("Configuration", func() {
viper.SetDefault("loglevel", "error") viper.SetDefault("loglevel", "error")
conf.ResetConf() conf.ResetConf()
DeferCleanup(conf.PanicOnLogFatal()) // Panic instead of exiting on fatal errors to allow testing error conditions
DeferCleanup(conf.SetLogFatal(func(args ...any) {
panic(fmt.Sprint(args...))
}))
}) })
Describe("ParseLanguages", func() { Describe("ParseLanguages", func() {
@ -66,13 +61,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 +104,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()).ToNot(Succeed()) Expect(fn()).To(HaveOccurred())
}) })
It("rejects a URL without a host", func() { It("rejects a URL without a host", func() {
@ -157,9 +152,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,124 +174,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"))
})
})
Describe("unknownConfigKeys", func() {
BeforeEach(func() {
viper.Reset()
conf.SetViperDefaults()
viper.SetDefault("datafolder", GinkgoT().TempDir())
viper.SetDefault("loglevel", "error")
conf.ResetConf()
})
It("reports misplaced and misspelled options, as spelled in the config file", func() {
conf.InitConfig(filepath.Join("testdata", "cfg_unknown_keys.toml"), false)
conf.Load(true)
Expect(conf.UnknownConfigKeys()).To(ConsistOf(
"ArtistSplitExceptions", "EnableDownlods", "Whatever.Foo",
))
})
DescribeTable("recovers the original casing in all supported formats",
func(file string) {
conf.InitConfig(filepath.Join("testdata", file), false)
conf.Load(true)
Expect(conf.UnknownConfigKeys()).To(ConsistOf("NotAnOption"))
},
Entry("TOML", "cfg_unknown_casing.toml"),
Entry("YAML", "cfg_unknown_casing.yaml"),
Entry("JSON", "cfg_unknown_casing.json"),
Entry("INI", "cfg_unknown_casing.ini"),
)
It("does not report valid, deprecated or free-form keys", func() {
conf.InitConfig(filepath.Join("testdata", "cfg.toml"), false)
conf.Load(true)
Expect(conf.UnknownConfigKeys()).To(BeEmpty())
})
It("does not report the [default] section of INI files", func() {
conf.InitConfig(filepath.Join("testdata", "cfg.ini"), false)
conf.Load(true)
Expect(conf.UnknownConfigKeys()).To(BeEmpty())
})
DescribeTable("SuggestOptions",
func(key string, expected []string) {
Expect(conf.SuggestOptions(key)).To(Equal(expected))
},
Entry("suggests the section of a misplaced option", "artistsplitexceptions",
[]string{"Scanner.ArtistSplitExceptions"}),
Entry("suggests the section of a misplaced nested option", "backup.fuzzythreshold",
[]string{"Matcher.FuzzyThreshold"}),
Entry("suggests every section defining the option", "schedule",
[]string{"Backup.Schedule", "Scanner.Schedule"}),
Entry("suggests nothing for a typo", "enabledownlods", nil),
)
It("does not report ND_-prefixed keys, as they are remapped", func() {
conf.InitConfig(filepath.Join("testdata", "cfg_nd_keys.toml"), false)
conf.Load(true)
Expect(conf.UnknownConfigKeys()).To(BeEmpty())
})
It("reports ND_-prefixed keys that remap to no known option", func() {
conf.InitConfig(filepath.Join("testdata", "cfg_nd_bogus.toml"), false)
conf.Load(true)
Expect(conf.UnknownConfigKeys()).To(ConsistOf("ND_TOTALLY_BOGUS_OPTION"))
Expect(conf.Server().Scanner.Schedule).To(Equal("@every 1h"))
})
It("migrates every deprecated option that has a replacement", func() {
conf.InitConfig(filepath.Join("testdata", "cfg_deprecated_search.toml"), false)
conf.Load(true)
Expect(conf.Server().Search.FullString).To(BeTrue())
Expect(conf.UnknownConfigKeys()).To(BeEmpty())
})
It("warns about each unrecognized option at startup", func() {
var logBuf bytes.Buffer
log.SetOutput(&logBuf)
DeferCleanup(func() { log.SetOutput(GinkgoWriter) })
conf.InitConfig(filepath.Join("testdata", "cfg_warning_output.toml"), false)
conf.Load(true)
Expect(logBuf.String()).To(ContainSubstring(
"Option 'ArtistSplitExceptions' is not recognized and will be ignored. " +
"Did you mean 'Scanner.ArtistSplitExceptions'?"))
Expect(logBuf.String()).To(ContainSubstring(
"Option 'EnableDownlods' is not recognized and will be ignored"))
Expect(logBuf.String()).ToNot(ContainSubstring("ArtistJoiner"))
})
Context("with runtime-computed and removed options in the config", func() {
BeforeEach(func() {
conf.InitConfig(filepath.Join("testdata", "cfg_runtime_fields.toml"), false)
conf.Load(true)
})
It("reports values computed during Load, which the config cannot set", func() {
Expect(conf.UnknownConfigKeys()).To(ContainElements("ConfigFile", "LastFM.Languages"))
})
It("never suggests a removed option", func() {
Expect(conf.SuggestOptions("id")).To(BeEmpty())
})
It("keeps an explicit replacement over the deprecated value", func() {
Expect(conf.Server().Search.FullString).To(BeFalse())
})
}) })
}) })
@ -329,21 +207,6 @@ 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")
@ -354,10 +217,19 @@ var _ = Describe("Configuration", func() {
}) })
Describe("ValidateByteSize", func() { Describe("ValidateMaxImageUploadSize", func() {
BeforeEach(func() {
viper.Reset()
conf.SetViperDefaults()
viper.SetDefault("datafolder", GinkgoT().TempDir())
viper.SetDefault("loglevel", "error")
conf.ResetConf()
})
DescribeTable("accepts valid size values", DescribeTable("accepts valid size values",
func(input string) { func(input string) {
Expect(conf.ValidateByteSize("MaxImageSize", input)()).To(Succeed()) conf.Server.MaxImageUploadSize = input
Expect(conf.ValidateMaxImageUploadSize()).To(Succeed())
}, },
Entry("megabytes", "10MB"), Entry("megabytes", "10MB"),
Entry("gigabytes", "1GB"), Entry("gigabytes", "1GB"),
@ -368,90 +240,19 @@ var _ = Describe("Configuration", func() {
DescribeTable("rejects invalid size values", DescribeTable("rejects invalid size values",
func(input string) { func(input string) {
Expect(conf.ValidateByteSize("MaxImageSize", input)()).To(MatchError(ContainSubstring("invalid MaxImageSize"))) conf.Server.MaxImageUploadSize = input
Expect(conf.ValidateMaxImageUploadSize()).To(MatchError(ContainSubstring("invalid MaxImageUploadSize")))
}, },
Entry("garbage string", "not-a-size"), Entry("garbage string", "not-a-size"),
Entry("negative-looking", "-10MB"), Entry("negative-looking", "-10MB"),
Entry("zero", "0"),
Entry("zero with unit", "0MB"),
Entry("overflows int64", "9223372036854775808"),
) )
}) })
Describe("MaxImageSize floor", func() {
BeforeEach(func() {
viper.Reset()
conf.SetViperDefaults()
viper.SetDefault("datafolder", GinkgoT().TempDir())
viper.SetDefault("loglevel", "error")
conf.ResetConf()
})
It("is raised to MaxImageUploadSize when configured lower", func() {
viper.SetDefault("maximagesize", "5MB")
viper.SetDefault("maximageuploadsize", "50MB")
conf.Load(true)
Expect(conf.Server().MaxImageSize).To(Equal("50MB"))
})
It("keeps a larger MaxImageSize unchanged", func() {
viper.SetDefault("maximagesize", "30MB")
conf.Load(true)
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"))
})
})
Describe("EnforceNonRootUser", func() { Describe("EnforceNonRootUser", 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() {
@ -460,7 +261,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() {
@ -486,7 +287,7 @@ var _ = Describe("Configuration", func() {
conf.Load(true) conf.Load(true)
Expect(conf.Server().EnforceNonRootUser).To(BeTrue()) Expect(conf.Server.EnforceNonRootUser).To(BeTrue())
}) })
}) })
@ -500,88 +301,20 @@ 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"),
Entry("INI format", "ini"), Entry("INI format", "ini"),
Entry("JSON format", "json"), Entry("JSON format", "json"),
) )
It("should use default values for negative duration fields", func() {
filename := filepath.Join("testdata", "invalid_duration.toml")
conf.InitConfig(filename, false)
conf.Load(true)
server := conf.Server()
Expect(server.SessionTimeout).To(Equal(consts.DefaultSessionTimeout))
Expect(server.SmartPlaylistRefreshDelay).To(Equal(consts.DefaultSmartRefresh))
Expect(server.DefaultShareExpiration).To(Equal(consts.DefaultShareExpiration))
Expect(server.UIPlaybackReportInterval).To(Equal(consts.DefaultUIPlaybackReportInterval))
Expect(server.AuthWindowLength).To(Equal(consts.DefaultAuthWindowLength))
Expect(server.Scanner.WatcherWait).To(Equal(consts.DefaultWatcherWait))
Expect(server.DevActivityPanelUpdateRate).To(Equal(consts.DefaultActivityPanelUpdateRate))
Expect(server.DevArtworkThrottleBacklogTimeout).To(Equal(consts.RequestThrottleBacklogTimeout))
Expect(server.DevArtistInfoTimeToLive).To(Equal(consts.ArtistInfoTimeToLive))
Expect(server.DevAlbumInfoTimeToLive).To(Equal(consts.AlbumInfoTimeToLive))
Expect(server.DevInsightsInitialDelay).To(Equal(consts.InsightsInitialDelay))
Expect(server.DevPluginCompilationTimeout).To(Equal(consts.DefaultPluginCompilationTimeout))
})
It("should use parsed values for duration fields", func() {
conf.InitConfig(filepath.Join("testdata", "valid_duration.toml"), false)
conf.Load(true)
configured := 1 * time.Second
server := conf.Server()
Expect(server.SessionTimeout).To(Equal(configured))
Expect(server.SmartPlaylistRefreshDelay).To(Equal(configured))
Expect(server.DefaultShareExpiration).To(Equal(configured))
Expect(server.UIPlaybackReportInterval).To(Equal(configured))
Expect(server.AuthWindowLength).To(Equal(configured))
Expect(server.Scanner.WatcherWait).To(Equal(configured))
Expect(server.DevActivityPanelUpdateRate).To(Equal(configured))
Expect(server.DevArtworkThrottleBacklogTimeout).To(Equal(configured))
Expect(server.DevArtistInfoTimeToLive).To(Equal(configured))
Expect(server.DevAlbumInfoTimeToLive).To(Equal(configured))
Expect(server.DevInsightsInitialDelay).To(Equal(configured))
Expect(server.DevPluginCompilationTimeout).To(Equal(configured))
})
})
var _ = Describe("TLSEnabled", func() {
It("is false when neither the certificate nor the key is set", func() {
Expect(conf.Server().TLSEnabled()).To(BeFalse())
})
It("is true when both the certificate and the key are set", func() {
conf.Update(func(c *conf.Options) {
c.TLSCert = "cert.pem"
c.TLSKey = "key.pem"
})
Expect(conf.Server().TLSEnabled()).To(BeTrue())
})
It("is false when only the certificate is set", func() {
conf.Update(func(c *conf.Options) { c.TLSCert = "cert.pem" })
Expect(conf.Server().TLSEnabled()).To(BeFalse())
})
It("is false when only the key is set", func() {
conf.Update(func(c *conf.Options) { c.TLSKey = "key.pem" })
Expect(conf.Server().TLSEnabled()).To(BeFalse())
})
}) })

View file

@ -82,14 +82,20 @@ var _ = Describe("Dir", func() {
}) })
It("calls logFatal on error", func() { It("calls logFatal on error", func() {
DeferCleanup(conf.PanicOnLogFatal()) var fatalMsg []any
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(PanicWith(ContainSubstring("creating directory"))) Expect(func() { d.MustPath() }).To(Panic())
Expect(fatalMsg).ToNot(BeEmpty())
}) })
}) })

View file

@ -1,9 +1,7 @@
package conf package conf
import "fmt"
func ResetConf() { func ResetConf() {
current.Store(&Options{}) Server = &configOptions{}
} }
var SetViperDefaults = setViperDefaults var SetViperDefaults = setViperDefaults
@ -16,7 +14,7 @@ var NormalizeSearchBackend = normalizeSearchBackend
var ToPascalCase = toPascalCase var ToPascalCase = toPascalCase
var ValidateByteSize = validateByteSize var ValidateMaxImageUploadSize = validateMaxImageUploadSize
func SetRuntimeInfoForTest(goos string, euid int) func() { func SetRuntimeInfoForTest(goos string, euid int) func() {
oldGOOS := currentGOOS oldGOOS := currentGOOS
@ -34,14 +32,3 @@ func SetLogFatal(f func(...any)) func() {
logFatal = f logFatal = f
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 SuggestOptions = suggestOptions

View file

@ -1,87 +0,0 @@
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)
}
}

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