Compare commits

..
30 Commits
Author SHA1 Message Date
bvandeusenandClaude Opus 5.5 e5f11647ee test(web): the bell test reads the new-music body
release / web (push) Successful in 1m31s
release / go (push) Successful in 2m6s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m42s
release / android (push) Successful in 5m25s
release / Build signed APK (push) Successful in 6m19s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 36s
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 23:35:43 -05:00
bvandeusenandClaude Opus 5.5 561c1d5eae feat: new-music notices come from the scanner; request notices and the original specs go
release / web (push) Failing after 1m29s
release / go (push) Successful in 1m55s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m22s
release / android (push) Successful in 4m57s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 4m23s
Request notifications (approved, declined, completed, pending) are removed
along with the request flow that produced them. A new_music kind takes the
"new music arrived" slot: when a scan or a watcher batch finishes, the
scanner claims every album not yet announced (albums.announced_at) and tells
every user about the ones that are new: an album with a track on disk and
no track older than itself. The first import into an empty library, and an
album formed only by retagging tracks already held, announce nothing. One
notice per scan, carrying up to 50 albums and the total; it is never
coalesced, so a notice already emailed can't quietly absorb later arrivals.
It feeds the daily summary email, grouped by artist. Defaults: inbox and
email on, phone off.

Migration 0103 deletes request-kind notification rows and prefs, swaps the
kind CHECKs to new_music, and adds albums.announced_at with every album
held marked announced, so the first scan after it announces nothing old.

Web and Android: labels, the Android "Requests" settings section becomes
"New music", the shade channel your_requests becomes new_music (the old one
is deleted at startup), and "/" opens Home in the app. TrackLabel moves to
the notifications package. docs/smart-music-{server,client}-spec.md are
deleted per the operator; an Android comment loses the word "exchanges".

Grimoire #7666, #7671.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 23:29:13 -05:00
bvandeusenandClaude Opus 5.5 9d267ba8dd feat(android): the app drops requests, Discover and auto-approve
release / go (push) Successful in 1m52s
release / web (push) Successful in 1m17s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m12s
release / android (push) Successful in 4m46s
release / Build signed APK (push) Successful in 5m50s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 23s
release / Verify release artifacts (tag releases only) (push) Skipped
The server no longer takes requests or suggests music, so the app's
screens for them go:
- My requests (Settings), Discover (the app bar menu) and Admin >
  Requests, with their routes, view models, repositories, API
  interfaces and models;
- the auto-approve toggle on Admin > Users;
- the Requests card and its count on the Admin landing.

The offline queue loses its request_create, request_cancel and
suggestion_snooze_toggle kinds. A phone that still holds rows of those
kinds drops them on the next drain, through the replayer's existing
unknown-kind path, so nothing is retried against the removed endpoints.
The toggle-collapse tests that used snoozes now use likes and settings.

Notification links to /requests and /admin/requests open nothing. The
request notification kinds and their settings section stay until the
server decides what replaces them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 22:09:08 -05:00
bvandeusenandClaude Opus 5.5 0eae7a247a test(similarity): only library artists are stored
release / android (push) Successful in 4m34s
release / web (push) Successful in 1m21s
release / go (push) Successful in 1m52s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m6s
release / Build signed APK (push) Successful in 5m13s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 37s
release / Verify release artifacts (tag releases only) (push) Skipped
The similarity worker stops keeping the similar artists the library does
not hold, now that Discover is gone. The test keeps its check that the
in-library match lands scored against the seed's best, and drops the
assertions on the unmatched table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 21:03:10 -05:00
bvandeusenandClaude Opus 5.5 797fb1f4b4 fix(web): take the patched SvelteKit and adapter-static
release / go (push) Successful in 1m44s
release / web (push) Successful in 1m18s
release / govulncheck (push) Successful in 20s
release / integration (push) Failing after 4m12s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 3m59s
release / Build signed APK (push) Canceled after 2m33s
npm audit now flags @sveltejs/kit 3.0.1 (high: GHSA-mw6w-2fmv-pvw3,
GHSA-m9j8-jcmv-hp69 and others) and @sveltejs/adapter-static 4.0.0
(moderate: GHSA-jf9x-2fg2-hx4w). The lockfile moves to kit 3.4.0 and
adapter-static 4.0.1, inside the ranges package.json already allows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 20:57:29 -05:00
bvandeusenandClaude Opus 5.5 55c7497ca7 feat: Minstrel stops acquiring music and drops Discover
release / go (push) Successful in 1m54s
release / web (push) Failing after 5s
release / integration (push) Failing after 3m44s
release / govulncheck (push) Successful in 20s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 19s
release / android (push) Canceled after 2m37s
Minstrel is now a viewer of the library it is pointed at. Finding,
downloading and filing music moves out of it.

Removed from the server:
- the request flow (requests, approval, auto-approve) and the wanted list,
  follows, release profiles and release blocks;
- searching indexers, the download clients, the importer, the album
  lifecycle and missing-file re-acquisition;
- the catalogue's discography, search and art (the MusicBrainz release and
  track-list cache stays, for the duplicate resolver);
- Discover: its suggestions of artists not in the library, snoozes, the
  candidate-artist tag enrichment and its tuning scope;
- writes to acquisition tables from moving the library folder and from
  merging duplicates, the want-list join on Suspect sources, the sealing of
  acquisition credentials, and the release-group lookup only
  re-acquisition used.

Settling a wrong-slot duplicate no longer sets the release aside: the
copies go and their slots show as missing until a good copy is in the
library.

Removed from the web: Admin > Acquisition and Requests, /requests,
/discover, Follow on the artist page, the auto-approve toggle, and the
Collection's wanted-list tabs. The Collection is now the library's health:
an overview, Reports, Duplicates, Suspect sources and Missing files. The
README and docs no longer describe getting music.

The tables stay for now; a later migration drops them. The request
notification kinds and the Android screens are still to go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 20:51:14 -05:00
bvandeusenandClaude Opus 5.5 dabe1e052d feat: genre mixes pick specific genres that don't share songs (#6933)
release / go (push) Successful in 2m0s
release / web (push) Successful in 1m33s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 5m11s
release / android (push) Successful in 4m14s
release / Build signed APK (push) Successful in 4m38s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 29s
release / Verify release artifacts (tag releases only) (push) Skipped
The shelf had four mixes built largely from the same lo-fi beats: about
1,250 tracks carry Hip Hop, Lo-Fi, Instrumental, Downtempo and four more
tags at once, and the near-duplicate guard compared artists, not songs, so
each tag passed as its own channel.

Genre selection now works on songs:
- ListGenreMixCandidates returns each genre's track ids instead of its
  artist ids.
- A broad genre, one whose songs mostly also carry clearly narrower
  candidates (Rock over Pop Punk and Ska Punk), is considered after the
  specific genres of its tier.
- A genre is kept only when at least half its songs are not already in a
  kept genre.
- Each mix leaves out songs tagged with a genre kept before it
  (ListGenreMixTracks exclude_genres), so a song is in one mix at most.

The tiers, the minimum shelf and the minimum mix length are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 14:55:19 -05:00
bvandeusenandClaude Opus 5.5 14debe2ea9 feat: genre mixes lean toward what the listener likes (#6921)
release / web (push) Successful in 1m40s
release / go (push) Successful in 2m5s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 5m2s
release / android (push) Successful in 4m40s
release / Build signed APK (push) Successful in 5m7s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 32s
release / Verify release artifacts (tag releases only) (push) Skipped
Within a genre both halves of the mix were a uniform daily draw: a song
played forty times was no likelier than one played once, and the unheard
40% ignored who the artist was. ListGenreMixTracks now draws each half by a
date-seeded weighted lottery (Efraimidis-Spirakis: smallest -ln(u)/weight
wins), so the mix still changes daily and holds within a day.

- Familiar: 1 + ln(1 + plays) + 1 if liked, times the share of plays that
  weren't skips.
- Unheard: 1 + ln(1 + the artist's plays + 2 x its liked tracks)
  + 2 x the artist's best similarity to the user's own artists, times the
  artist's non-skip share. An unknown artist weighs 1, so new artists still
  come up.

Which genres are offered, the exclusions and the familiar/unheard blend
are unchanged. DB tests check the lean averaged over ten days, and that a
stranger's tracks stay in the pool.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 14:21:04 -05:00
bvandeusenandClaude Opus 5.5 adbb3a3cd8 fix(android): the launch profile refresh waits for the stored login
release / govulncheck (push) Successful in 18s
release / Build signed APK (push) Successful in 4m37s
release / web (push) Successful in 1m25s
release / go (push) Successful in 1m50s
release / integration (push) Successful in 4m36s
release / android (push) Successful in 3m59s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 15s
release / Verify release artifacts (tag releases only) (push) Skipped
AuthController refreshes /api/me when the app starts, to pick up account
flags such as debug mode. That ran before the session cookie had loaded
from the Keystore, read the user as signed out, and skipped. It now waits
for the load (bounded by the hydration deadline). The diagnostics
uploader's drain waits the same way, so a launch-time trigger isn't
skipped. BootReceiver already waited.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 11:55:59 -05:00
bvandeusenandClaude Opus 5.5 e73950458f test(android): the slow-hydration test's row carries the mock server URL
release / web (push) Successful in 1m34s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m57s
release / go (push) Successful in 1m58s
release / android (push) Successful in 4m30s
release / Build signed APK (push) Successful in 4m56s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 16s
release / Verify release artifacts (tag releases only) (push) Skipped
On a real background dispatcher the store's row collector lands after
construction and reset the base URL to the default, so the request went to
localhost:8080 instead of the mock server. The row now holds the server URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 10:30:42 -05:00
bvandeusenandClaude Opus 5.5 454d71d079 fix(android): the app stops signing itself out at launch (#6911)
release / web (push) Successful in 1m24s
release / go (push) Successful in 1m52s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 4m43s
release / android (push) Failing after 3m25s
release / Build signed APK (push) Successful in 4m41s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
At launch the stored session cookie loads from the Keystore off the main
thread. A request sent before that finished went out without it, typically
the library sync that fires as soon as the server answers. The server then
answered 401, and the interceptor cleared the store on any 401, which also
stopped the load from restoring the cookie and wrote null over the stored
one. The user had to sign in on every launch. A session lost mid-use also
left them on Home with every request failing, because the app only routes
to sign-in when it starts.

- The interceptor waits for the stored cookie to load before attaching it,
  bounded by the existing hydration deadline.
- A 401 signs out only when the request carried the current cookie
  (compare-and-clear). A request sent without one, or with a cookie a newer
  sign-in has replaced, leaves the login alone.
- When the server refuses the session mid-use, the app opens the sign-in
  screen. A sign-out from Settings does not trigger this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 10:22:59 -05:00
bvandeusenandClaude Opus 5.5 8251fef604 test: seedGenre gives each artist one artist row and one album
release / web (push) Successful in 1m25s
release / go (push) Successful in 1m49s
release / govulncheck (push) Successful in 22s
release / android (push) Successful in 4m22s
release / Build + push container image (push) Successful in 1m12s
release / Verify release artifacts (tag releases only) (push) Skipped
release / integration (push) Successful in 4m52s
release / Build signed APK (push) Successful in 4m46s
release / Attach APK to the Release (tag releases only) (push) Skipped
seedTrack mints a new artist per call when there is no mbid, so the genre
fixtures held one artist per track and the candidate query's artist_ids
counted 30 where the test meant 6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 22:39:29 -05:00
bvandeusenandClaude Opus 5.5 dbaa8b7d57 feat: genre mixes — a daily playlist per genre you listen to, on a "Your genres" Home row (#6904)
release / Build signed APK (push) Successful in 4m34s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
release / web (push) Successful in 1m24s
release / govulncheck (push) Successful in 25s
release / go (push) Successful in 1m47s
release / integration (push) Failing after 4m38s
release / android (push) Successful in 4m3s
A new system playlist kind, genre_mix: up to 10 "{Genre} mix" playlists per
user, rebuilt daily with the other system mixes.

Which genres: library genres with at least 25 playable tracks across 3
artists, ranked in tiers — taste-profile genres first (matched
case-insensitively, so ID3 "Post-Punk" and folksonomy "post-punk" are one),
then genres the user has played or liked, then the rest of the library, which
only tops a short shelf up to 4. A genre whose artist set is a near
duplicate of one already picked (Jaccard >= 0.5) is skipped, so "Lo-Fi" and
"Lo-Fi Hip Hop" don't both appear but "Alternative Rock" survives "Rock". A
genre that can't fill 15 tracks gives way to the next.

Each mix is 50 tracks: 3 in 5 the user already knows (played through or
liked), the rest unheard in that genre, interleaved, with the usual
per-album/per-artist caps. Tracks skipped twice and more often than played
are left out. The order changes daily and holds within a day. Picks are
stamped taste / taste_unheard, and genre_mix plays count toward rotation and
the recommendation metrics.

Migration 0102 adds genre_mix to the playlists variant constraints.

Web and Android each get a "Your genres" row in name order, hidden until a
mix exists. Kinds with several playlists per user now play by playlist id
wherever the client used to test seed_artist_id (web card, detail page
self-heal), keyed on the server's refreshable flag; on Android genre_mix
joins songs_like_artist as not refreshable. The web detail page's
"mix was rebuilt" reload now finds a Songs-like or genre mix by name instead
of calling the by-kind shuffle, which those kinds don't have.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 22:30:41 -05:00
bvandeusenandClaude Opus 5.5 477f453100 feat(android): settings read as a menu — every group on one Section plate, every setting one SettingRow (#6768)
release / web (push) Successful in 1m19s
release / govulncheck (push) Successful in 18s
release / android (push) Successful in 4m16s
release / Build signed APK (push) Successful in 4m38s
release / go (push) Successful in 1m48s
release / integration (push) Successful in 4m29s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped
Settings and Notification settings were hand-rolled ElevatedCards, each with
its own padding, title style and row layout, and several rows carried
two- and three-line explanations. They are now built from one vocabulary in
theme/Section.kt: Section (the plate), SettingRow (title, one short line, an
optional icon, the control at the end), SwitchRow and ChoiceRow (the whole
row toggles or opens the choices), RowValue, RowSpinner, RowChevron, Muted.

The plate is Minstrel's own raised surface with its radius tokens, so the
app keeps its look. Sign out, sync and clear cache are rows, not loose
buttons; the theme, leveling, loudness target and storage caps are choice
rows; the About card (also the update sheet on Home) shows the version as a
value and the update as a row with its one button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:31:25 -05:00
bvandeusenandClaude Opus 5.5 598abeb8cf fix: a fresh app install syncs the whole library, not the last 30 days of changes (#6778)
release / govulncheck (push) Successful in 14s
release / web (push) Successful in 1m20s
release / go (push) Successful in 1m44s
release / android (push) Successful in 4m54s
release / Build signed APK (push) Successful in 5m10s
release / integration (push) Successful in 5m19s
release / Build + push container image (push) Successful in 15s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
The change feed dropped every row older than 30 days, and an app syncing
from cursor 0 builds its library from the feed, so a fresh install, cleared
data or a 410 reset got only what had changed lately.

The compactor now keeps each entity's latest change however old. It drops a
row once a newer one for the same entity exists, and a delete once it is 30
days old, raising a stored mark (library_changes_trimmed) past it; an app
whose cursor is below the mark is sent back to 0, as before. Migration 0101
adds the index the compactor needs, seeds the mark where the old compactor
left off, and gives every artist, album and track whose latest row is not an
upsert a fresh one, so the rows the old compactor dropped come back. The
backup carries the mark with the feed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:07:42 -05:00
bvandeusenandClaude Opus 5.5 ad48d8c8c9 fix: the route-registration test passes Mount its restart hook
release / govulncheck (push) Successful in 16s
release / web (push) Successful in 1m25s
release / android (push) Successful in 4m57s
release / Build signed APK (push) Successful in 5m9s
release / go (push) Successful in 1m43s
release / integration (push) Successful in 5m21s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 22s
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:25:39 -05:00
bvandeusenandClaude Opus 5.5 68e1e47534 fix: a new server takes a backup after its first scan, and restarts to load the restored settings (#6786)
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / govulncheck (push) Successful in 16s
release / go (push) Failing after 49s
release / web (push) Successful in 1m9s
release / integration (push) Failing after 4m14s
release / android (push) Canceled after 4m38s
release / Build signed APK (push) Canceled after 4m38s
A one-off end-to-end run of the :dev image (scratch Postgres, generated
FLAC files, no outbound network) found that the web restore, done the way
docs/hosting.md describes, was refused with not_empty: a new server's
startup scan fills the library before anyone signs up, and Restore counted
tracks as occupied. The command-line restore passed the same run.

- Restore now asks only that the instance has no accounts. The library the
  first scan found is replaced by the backup's (every foreign key into
  artists/albums/tracks cascades or sets null), and the restore locks the
  library tables so a running scan waits rather than adding to them.
- Settings are read once at boot by about ten services, the library folders
  among them, so after a web restore the server ran on its defaults until
  restarted. The restore endpoint now answers, then asks the process to
  restart in place (syscall.Exec of the same binary, arguments and
  environment), which needs no container restart policy. The startup scan
  of the restarted server replaces the scan the endpoint used to start.
- The restore form says Minstrel is restarting; the docs say a scanned new
  server still takes a backup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:21:00 -05:00
bvandeusenandClaude Opus 5.5 a521326686 fix: the restore form's file picker isn't required, so the form submits once a file is chosen
release / govulncheck (push) Successful in 17s
release / web (push) Successful in 1m24s
release / go (push) Successful in 1m40s
release / android (push) Successful in 5m12s
release / integration (push) Successful in 5m24s
release / Build signed APK (push) Successful in 5m35s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 23s
release / Verify release artifacts (tag releases only) (push) Skipped
The Restore button already waits for a file. A required file input also kept
jsdom from submitting after a test picked one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 16:16:27 -05:00
bvandeusenandClaude Opus 5.5 29042e4eb2 feat: a new Minstrel restores a backup, from the web app or the command line, then rescans (#6775)
release / govulncheck (push) Successful in 29s
release / web (push) Failing after 1m21s
release / go (push) Successful in 1m39s
release / integration (push) Successful in 5m26s
release / android (push) Successful in 5m27s
release / Build signed APK (push) Successful in 5m44s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
A new server (no accounts, no library) offers "Restore a backup" beside
"Create account". The file goes up as the request body to
POST /api/auth/restore with the setup token from the log in X-Setup-Token,
since the backup's admins become this server's. It loads in one transaction,
then a library scan starts and finds each file at its path. The same load runs
offline as `minstrel restore FILE`, which migrates the schema first.

That path alone gets a 1 GiB, 15-minute body allowance instead of 4 MiB and
30s, and skips the JSON-only check for cookie writes: a stale cookie from the
old server would otherwise refuse the upload, and the custom header already
rules out a cross-site form.

The library sync answers 410 cursor_ahead to a cursor past the last one the
server has handed out, read from the change sequence, so an app synced with
the old server after the backup was made starts over instead of skipping the
ids the restored server reuses. Restore now leaves each sequence as having
issued the restored maximum, so that reading holds; a compacted log still
counts its handed-out cursors.

backup.Read keeps the underlying error in its chain, so an oversized upload
answers 413 rather than "not a backup". The hosting docs say how to put the
music back first and what is entered again afterwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 16:10:06 -05:00
bvandeusenandClaude Opus 5.5 5090c89d20 fix: the backup panel test reads the music sizes as formatBytes prints them
release / govulncheck (push) Successful in 14s
release / web (push) Successful in 1m23s
release / go (push) Successful in 1m40s
release / android (push) Successful in 5m4s
release / Build signed APK (push) Successful in 5m15s
release / integration (push) Successful in 5m25s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 22s
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:35:58 -05:00
bvandeusenandClaude Opus 5.5 967763f6ce feat: the backup can include the music, sending each library file once to music/ and again only when it changes (#6774)
release / govulncheck (push) Successful in 15s
release / web (push) Failing after 1m17s
release / go (push) Successful in 1m33s
release / integration (push) Successful in 5m16s
release / Build signed APK (push) Successful in 6m13s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
release / android (push) Successful in 5m56s
With "Include the music" on, each night's run sends the library files the
destination doesn't hold yet, after the database file has landed, for up to
six hours; a large library spans several nights the first time. Files keep
their path under the library folders' common root, beside database/ in the
same folder or bucket.

backup_music_files records each file's size and mtime as sent, so a night
sends only new and changed files, and a rescan that touches a track but finds
the same file sends nothing. A changed file goes to its old name; Minstrel
never deletes there. An object the bucket refuses (a locked overwrite) is
kept with its answer and goes again once the file changes or the settings are
saved; three refusals in a row stop the night's music, since that is a key
that may not write under music/. A folder copy is written under a .part name
and renamed, keeping the file's time.

The panel shows how much of the library is in, the refused files, and each
run's music count and note. The verdict still turns on the database file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:26:20 -05:00
bvandeusenandClaude Opus 5.5 ff5ee755f2 fix: the backup test result says its count through plural(), and the panel tests read the size and folder field as shown
release / govulncheck (push) Successful in 17s
release / web (push) Successful in 1m30s
release / go (push) Successful in 1m46s
release / android (push) Successful in 5m23s
release / integration (push) Successful in 5m32s
release / Build signed APK (push) Successful in 5m33s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 24s
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:04:32 -05:00
bvandeusenandClaude Opus 5.5 f7222732e3 fix: the route test passes the backup service, and the backup panel narrows its status inside each column
release / govulncheck (push) Successful in 19s
release / web (push) Failing after 1m32s
release / go (push) Successful in 1m47s
release / android (push) Successful in 5m16s
release / integration (push) Successful in 5m31s
release / Build signed APK (push) Successful in 5m24s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 14:56:26 -05:00
bvandeusenandClaude Opus 5.5 9d324ab2d0 feat: Minstrel backs itself up nightly to a folder or an S3 bucket, off until an admin switches it on (#6773)
release / integration (push) Failing after 3m29s
release / web (push) Failing after 15s
release / govulncheck (push) Successful in 16s
release / go (push) Failing after 41s
release / android (push) Successful in 4m7s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 5m34s
Admin › Backups shows a verdict first (off, not set up, waiting, backed up,
overdue, failing since when), Back up now, Test destination and the latest
runs, with the settings beside them.

- backup.Service: one run at a time, bounded at 30 minutes; the schedule
  ticks every 5 minutes, catches up a slot missed while the server was down,
  and retries a failure after an hour and then after as long as it has been
  failing. Runs are recorded in backup_runs, pruned after 90 days; a run cut
  off by a shutdown is marked failed at the next start.
- A folder destination writes database/minstrel-<UTC stamp>.tar and refuses
  a folder that isn't there. An S3 destination stages the file, hashes it,
  and uploads it under database/ through a throttled reader (4 MiB/s by
  default, 0 for no limit).
- Test destination checks the form as typed and only lists.
- The bucket secret is sealed like every stored credential; backup_settings
  and backup_runs are left out of the backup itself.
- The panel polls only while a run is going, capped at the run limit plus
  five minutes.

The music switch named in the task is left to #6774, so no control ships
that does nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 14:50:55 -05:00
bvandeusenandClaude Opus 5.5 faf19ef67b test: the file-name test's later backup is later in UTC too
release / govulncheck (push) Successful in 22s
release / web (push) Successful in 1m33s
release / go (push) Successful in 1m49s
release / android (push) Successful in 4m59s
release / integration (push) Successful in 5m27s
release / Build signed APK (push) Successful in 5m1s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 14:01:31 -05:00
bvandeusenandClaude Opus 5.5 e11011e977 fix: the backup package checks or explicitly drops every error the linter flags
release / govulncheck (push) Successful in 24s
release / go (push) Failing after 1m42s
release / web (push) Successful in 1m25s
release / android (push) Successful in 4m52s
release / Build signed APK (push) Successful in 5m1s
release / integration (push) Canceled after 5m17s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
Closing a refused S3 response and a test file, and the fake bucket's
writes, now say they ignore the error on purpose; handler parameters the
tests don't use are named _.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 13:56:22 -05:00
bvandeusenandClaude Opus 5.5 b6ae205862 feat: Minstrel can put and list objects in a path-style S3 bucket, signed with SigV4 and no SDK (#6771)
release / govulncheck (push) Successful in 14s
release / android (push) Successful in 4m37s
release / Build signed APK (push) Successful in 4m47s
release / integration (push) Failing after 5m3s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
release / go (push) Failing after 1m7s
release / web (push) Successful in 1m14s
Bucket.Put stores a body under a key, signed over its SHA-256; Bucket.List
pages through ListObjectsV2. A backup only adds and lists, so an
append-only key is enough. Keys are encoded once, exactly as signed, so
music paths with spaces, plus signs and accents reach the bucket intact.
A refusal names S3's code in words ("the secret key is wrong").

The signer is pinned to AWS's published GET Object, PUT Object and
ListObjects examples.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 13:51:02 -05:00
bvandeusenandClaude Opus 5.5 8be69b752a feat: a backup is one uncompressed tar of per-table JSON Lines that stays the same bytes day to day (#6769)
The file is minstrel-<UTC stamp>.tar: manifest.json first, then
tables/<table>.jsonl, rows one per line in primary-key order. The run's
time lives only in the manifest and member headers are fixed, so a
deduplicating off-site copy stores unchanged tables once.

WriteFile writes to a hidden .part file, syncs it and renames it, so a
watched folder never shows half a backup. Read refuses anything that
isn't a whole backup: another format, a newer format version, a cut-off
file, or a member holding fewer rows than the manifest says.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 13:51:02 -05:00
bvandeusenandClaude Opus 5.5 a67897a6cd feat: Minstrel can read its irreplaceable data out as JSON Lines and load it back into an empty instance (#6770)
release / web (push) Successful in 1m17s
release / android (push) Successful in 4m41s
release / Build signed APK (push) Successful in 4m52s
release / govulncheck (push) Successful in 15s
release / go (push) Successful in 1m29s
release / integration (push) Successful in 5m3s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped
internal/backup names every table a backup holds, in parent-first order,
and every table it leaves out with the reason: what the server computes
from the music files, provider caches it fetches again, sign-ins and
one-time links, and logs of past runs. The library's identity rows travel
because every like, play and playlist entry hangs off a track id, and the
sync change feed travels because the apps' first sync reads it.

Sealed credentials are left out of the file, and so are the markers that
say tag and art enrichment are done, so a restored server asks for the
credentials again and redoes that work rather than believing it has it.

Snapshot reads one REPEATABLE READ, read-only transaction, each table in
primary-key order, keys sorted. Restore refuses an instance with accounts
or tracks and a backup from a newer schema, replaces seeded settings,
inserts by column intersection in batches, skips generated columns, and
carries serial sequences on past the restored ids.

Guards: every schema table is backed up or excluded; every backed-up
table comes after what it references and references nothing excluded;
every omitted column exists; a restore gives back the backup byte for byte.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 13:43:16 -05:00
bvandeusenandClaude Opus 5.5 a8a2d20307 feat: stored credentials are sealed at rest, so a copy of the database alone reveals none of them (#6767)
release / govulncheck (push) Successful in 28s
release / web (push) Successful in 1m18s
release / go (push) Successful in 1m35s
release / android (push) Successful in 4m45s
release / Build signed APK (push) Successful in 4m57s
release / integration (push) Successful in 5m3s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 1m14s
release / Verify release artifacts (tag releases only) (push) Skipped
Minstrel keeps credentials it has to read back: indexer, Prowlarr and
download-client keys and passwords, the AcoustID key, cover-art and tag
provider keys, the SMTP password, and each user's ListenBrainz token and
Subsonic password. They were stored in the clear; they are now sealed with
AES-256-GCM under a per-column HKDF key derived from the stream secret, each
value bound to its row.

- internal/secret: Seal/Open/Reveal, and Columns, the one list of sealed
  columns (a backup will leave them out). Install takes the master key at
  startup; SealStored seals any value still in the clear, so an existing
  database is brought over in place on the first boot.
- Every write seals and every read opens: acquire (one read path, getService
  / usableServices), acoustid settings, SMTP, ListenBrainz, Subsonic auth and
  password generation, cover-art and tag provider settings.
- A value that does not open (the stream secret changed) is logged and reads
  as unset, to be entered again in Settings. docs/security.md says so.
- Tests: secret unit tests (wrong owner/purpose/key, malformed, no key), a
  SealStored integration test over all eight columns plus a schema check that
  each listed column exists, and the existing tests now assert sealed storage.
  dbtest installs a test key for integration tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 13:23:19 -05:00
449 changed files with 10464 additions and 44564 deletions
+7 -14
View File
@@ -4,7 +4,7 @@
<p align="center">A self-hosted music server that picks what to play next.</p>
Minstrel serves your music library to the web, to its own Android app, and to any Subsonic client. Shuffle, radio, likes and play history are worked out on the server, so every device gets the same mixes and the same history. It can also find, download and file the albums you want, through a search service and a download client you run yourself. It is for anyone who keeps their own music collection and wants it to sound like more than a random shuffle.
Minstrel serves your music library to the web, to its own Android app, and to any Subsonic client. Shuffle, radio, likes and play history are worked out on the server, so every device gets the same mixes and the same history. It is for anyone who keeps their own music collection and wants it to sound like more than a random shuffle.
<a href="docs/screenshots/home.png"><img src="docs/screenshots/home.png" width="820" alt="Minstrel home — your library at a glance"></a>
@@ -49,7 +49,7 @@ Open `http://<host>:4533/register` and create the first account with that setup
1. **Let the first scan finish.** Minstrel scans the library on startup. Watch it, or scan again, on the **Admin** page (`/admin`). Later scans only pick up what changed.
2. **Install the Android app.** In **Settings** (`/settings`), the *Install the Android app* card downloads the app this server ships. It updates itself from your server after that.
3. **Invite the household.** In **Admin › Users** (`/admin/users`), make an invite token or turn on open registration. Each person gets their own likes, history and recommendations.
4. **Optional: connect services.** Add a search service and a download client in **Admin › Acquisition** (`/admin/acquisition`). Each person adds their own ListenBrainz token in **Settings › Connections**.
4. **Optional: connect ListenBrainz.** Each person adds their own ListenBrainz token in **Settings › Connections**.
<a href="docs/screenshots/library-scan.png"><img src="docs/screenshots/library-scan.png" width="820" alt="The Admin page, where the library scan runs and reports progress"></a>
@@ -64,11 +64,11 @@ The quick start sets everything that's required. These are the settings people m
| `MINSTREL_BRANDING_APP_NAME` | The name shown in the header, the browser tab and link previews. |
| `MINSTREL_LOG_LEVEL` | `debug`, `info`, `warn` or `error`. |
Search services, download clients, ListenBrainz, email and recommendation tuning are set in the web UI and take effect without a restart. The full file-based surface is in [`config.example.yaml`](./config.example.yaml); to use it, mount your copy at `/etc/smartmusic/config.yaml`.
ListenBrainz, email, metadata sources and recommendation tuning are set in the web UI and take effect without a restart. The full file-based surface is in [`config.example.yaml`](./config.example.yaml); to use it, mount your copy at `/etc/smartmusic/config.yaml`.
## Setup pitfalls
- **The library mount has to be writable by uid 1000.** Minstrel files the albums it downloads into the library, and it deletes a file when an admin asks it to. It never moves, renames or retags files that were already there. Mount the library `:ro` to forbid writes: those actions then refuse and say why.
- **The library mount has to be writable by uid 1000.** Minstrel deletes a file when an admin asks it to, and when the duplicate resolver removes a copy. It never moves, renames or retags your files. Mount the library `:ro` to forbid writes: those actions then refuse and say why.
- **`MINSTREL_LIBRARY_SCAN_PATHS` names the path inside the container** (`/music`), not the folder on your host.
- **On the internet, put it behind HTTPS.** Plain `http://` is fine on a network you trust. For a public server, bind the port to `127.0.0.1` and put a reverse proxy in front: see [docs/hosting.md](docs/hosting.md).
@@ -103,11 +103,6 @@ Every image carries a signed Android app, all with the same key, so a phone can
- Duplicates, missing files and suspect copies are found and listed under **Collection** for an admin to fix.
- Missing album art and MusicBrainz ids are filled in automatically.
**Getting music**
- A wanted list: requests from the household, artists you follow, and albums whose files went missing.
- Minstrel searches the indexers you configure, hands the best release to your download client, checks what arrives against MusicBrainz, tags it, and files it. A better copy replaces a poor one.
- Off until you add a search service and a download client.
**Clients and accounts**
- A full web app, built into the server.
- A native Android app that ships inside the server image, keeps playing what it has cached when the server is out of reach, and updates itself from your server.
@@ -116,13 +111,11 @@ Every image carries a signed Android app, all with the same key, so a phone can
## Scope and responsible use
Minstrel indexes the files you point it at and streams them to your own clients. It ships no indexers, no trackers, no torrent, Usenet or NZB engine of its own, and no DRM circumvention.
Minstrel indexes the files you point it at and streams them to your own clients. It does not find or download music, and it does no DRM circumvention.
Getting music is optional and does nothing until you configure it. It searches only the search service (Prowlarr or a Torznab indexer) and the download client (qBittorrent) you add yourself.
What you put in your library is your responsibility. Copyright law applies to your collection as it does to any other software that plays a file; please respect it, and the terms of any service you connect.
What you put in your library, and the sources you configure, are your responsibility. Copyright law applies to your collection as it does to any other software that plays a file; please respect it, and the terms of any service you connect.
Minstrel is not affiliated with or endorsed by ListenBrainz, MusicBrainz, Prowlarr, qBittorrent or Subsonic.
Minstrel is not affiliated with or endorsed by ListenBrainz, MusicBrainz or Subsonic.
## Development
@@ -24,6 +24,7 @@ import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.fabledsword.minstrel.auth.AuthStore
import com.fabledsword.minstrel.auth.ui.AuthGateViewModel
@@ -33,6 +34,7 @@ import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.nav.DetailSeedCache
import com.fabledsword.minstrel.nav.LocalDetailSeedCache
import com.fabledsword.minstrel.nav.Login
import com.fabledsword.minstrel.nav.MinstrelNavGraph
import com.fabledsword.minstrel.nav.Notifications
import com.fabledsword.minstrel.nav.NowPlaying
@@ -177,6 +179,7 @@ private fun App(
navController.navigate(route) { launchSingleTop = true }
onOpenedRoute()
}
SignInWhenSessionRejected(gate, navController)
MinstrelNavGraph(
navController = navController,
startDestination = resolved,
@@ -187,6 +190,24 @@ private fun App(
}
}
/**
* When the server ends the session while the app is in use, opens the
* sign-in screen rather than leaving the user on screens whose every
* request fails.
*/
@Composable
private fun SignInWhenSessionRejected(gate: AuthGateViewModel, navController: NavHostController) {
val sessionRejected by gate.sessionRejected.collectAsStateWithLifecycle()
LaunchedEffect(sessionRejected, navController) {
if (!sessionRejected) return@LaunchedEffect
navController.navigate(Login) {
popUpTo(0) { inclusive = true }
launchSingleTop = true
}
gate.consumeSessionRejected()
}
}
@Composable
private fun BootSplash() {
Surface(
@@ -11,9 +11,9 @@ import javax.inject.Inject
import javax.inject.Singleton
/**
* Read-through accessor for the admin quarantine queue. No Room cache —
* same rationale as AdminRequests. Three resolution actions all delete
* the row from the queue once the server accepts them.
* Read-through accessor for the admin quarantine queue. No Room cache:
* it is an admin's live work list, read fresh each time. Three resolution
* actions all delete the row from the queue once the server accepts them.
*/
@Singleton
class AdminQuarantineRepository @Inject constructor(
@@ -1,50 +0,0 @@
package com.fabledsword.minstrel.admin.data
import com.fabledsword.minstrel.api.endpoints.AdminRequestsApi
import com.fabledsword.minstrel.models.RequestRef
import com.fabledsword.minstrel.models.RequestStatus
import com.fabledsword.minstrel.models.wire.RequestWire
import retrofit2.Retrofit
import retrofit2.create
import javax.inject.Inject
import javax.inject.Singleton
/**
* Read-through accessor for the admin cross-user requests queue.
*
* No Room caching — admin actions are infrequent and don't benefit
* from offline scrollback. `approve` and `reject` fire direct REST
* (no mutation queue) because admin confirmation is point-and-shoot;
* if the request fails the UI surfaces the error and rolls back.
*/
@Singleton
class AdminRequestsRepository @Inject constructor(
retrofit: Retrofit,
) {
private val api: AdminRequestsApi = retrofit.create()
suspend fun list(): List<RequestRef> = api.list().map { it.toDomain() }
suspend fun approve(id: String) = api.approve(id)
suspend fun reject(id: String) = api.reject(id)
}
private fun RequestWire.toDomain(): RequestRef = RequestRef(
id = id,
userId = userId,
username = username,
status = RequestStatus.fromWire(status),
kind = kind,
artistName = artistName,
albumTitle = albumTitle,
trackTitle = trackTitle,
requestedAt = requestedAt,
decidedAt = decidedAt,
notes = notes,
importedAlbumCount = importedAlbumCount,
importedTrackCount = importedTrackCount,
matchedTrackId = matchedTrackId,
matchedAlbumId = matchedAlbumId,
matchedArtistId = matchedArtistId,
)
@@ -3,7 +3,6 @@ package com.fabledsword.minstrel.admin.data
import com.fabledsword.minstrel.api.endpoints.AdminUsersApi
import com.fabledsword.minstrel.api.endpoints.ResetPasswordBody
import com.fabledsword.minstrel.api.endpoints.SetAdminBody
import com.fabledsword.minstrel.api.endpoints.SetAutoApproveBody
import com.fabledsword.minstrel.models.AdminUserRef
import com.fabledsword.minstrel.models.wire.AdminUserWire
import retrofit2.Retrofit
@@ -27,9 +26,6 @@ class AdminUsersRepository @Inject constructor(
suspend fun setAdmin(id: String, isAdmin: Boolean) =
api.setAdmin(id, SetAdminBody(isAdmin))
suspend fun setAutoApprove(id: String, autoApprove: Boolean) =
api.setAutoApprove(id, SetAutoApproveBody(autoApprove))
suspend fun resetPassword(id: String, newPassword: String) =
api.resetPassword(id, ResetPasswordBody(newPassword))
@@ -41,6 +37,5 @@ private fun AdminUserWire.toDomain(): AdminUserRef = AdminUserRef(
username = username,
displayName = displayName,
isAdmin = isAdmin,
autoApproveRequests = autoApproveRequests,
createdAt = createdAt,
)
@@ -26,19 +26,16 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavHostController
import com.composables.icons.lucide.Inbox
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Music
import com.composables.icons.lucide.TriangleAlert
import com.composables.icons.lucide.Users
import com.fabledsword.minstrel.admin.data.AdminQuarantineRepository
import com.fabledsword.minstrel.admin.data.AdminRequestsRepository
import com.fabledsword.minstrel.admin.data.AdminTagSourcesRepository
import com.fabledsword.minstrel.admin.data.AdminUsersRepository
import com.fabledsword.minstrel.api.ErrorCopy
import com.fabledsword.minstrel.nav.Admin
import com.fabledsword.minstrel.nav.AdminQuarantine
import com.fabledsword.minstrel.nav.AdminRequests
import com.fabledsword.minstrel.nav.AdminTagSources
import com.fabledsword.minstrel.nav.AdminUsers
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
@@ -58,7 +55,7 @@ import javax.inject.Inject
// ─── State ───────────────────────────────────────────────────────────
data class AdminCounts(val requests: Int, val quarantine: Int, val users: Int, val tagSources: Int)
data class AdminCounts(val quarantine: Int, val users: Int, val tagSources: Int)
sealed interface AdminLandingUiState {
data object Loading : AdminLandingUiState
@@ -70,7 +67,6 @@ sealed interface AdminLandingUiState {
@HiltViewModel
class AdminLandingViewModel @Inject constructor(
private val requestsRepo: AdminRequestsRepository,
private val quarantineRepo: AdminQuarantineRepository,
private val usersRepo: AdminUsersRepository,
private val tagSourcesRepo: AdminTagSourcesRepository,
@@ -87,11 +83,10 @@ class AdminLandingViewModel @Inject constructor(
internal.value = AdminLandingUiState.Loading
try {
val counts = coroutineScope {
val req = async { requestsRepo.list().size }
val qua = async { quarantineRepo.list().size }
val usr = async { usersRepo.list().size }
val tag = async { tagSourcesRepo.list().count { it.enabled } }
AdminCounts(req.await(), qua.await(), usr.await(), tag.await())
AdminCounts(qua.await(), usr.await(), tag.await())
}
internal.value = AdminLandingUiState.Success(counts)
} catch (
@@ -150,15 +145,6 @@ private fun SectionList(counts: AdminCounts, navController: NavHostController) {
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
item {
SectionCard(
icon = Lucide.Inbox,
title = "Requests",
subtitle = "Approve or reject requests for new music",
count = counts.requests,
onClick = { navController.navigate(AdminRequests) },
)
}
item {
SectionCard(
icon = Lucide.TriangleAlert,
@@ -1,163 +0,0 @@
package com.fabledsword.minstrel.admin.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AssistChip
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import com.fabledsword.minstrel.models.RequestRef
import com.fabledsword.minstrel.nav.AdminRequests
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AdminRequestsScreen(
navController: NavHostController,
viewModel: AdminRequestsViewModel = hiltViewModel(),
) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
Scaffold(
contentWindowInsets = ShellContentWindowInsets,
modifier = Modifier.fillMaxSize(),
topBar = {
MinstrelTopAppBar(
title = "Admin · Requests",
navController = navController,
currentRouteName = AdminRequests::class.qualifiedName,
onBack = { navController.popBackStack() },
)
},
) { inner ->
PullToRefreshScaffold(
onRefresh = { viewModel.refresh().join() },
modifier = Modifier.fillMaxSize().padding(inner),
) {
when (val s = state) {
AdminRequestsUiState.Loading -> LoadingCentered()
AdminRequestsUiState.Empty -> EmptyState(
title = "No requests waiting",
body = "When users ask for new music, their pending " +
"requests show up here for approval.",
)
is AdminRequestsUiState.Error -> ErrorRetry(
title = "Couldn't load requests",
message = s.message,
onRetry = { viewModel.refresh() },
)
is AdminRequestsUiState.Success -> RequestList(
rows = s.rows,
onApprove = viewModel::approve,
onReject = viewModel::reject,
)
}
}
}
}
@Composable
private fun RequestList(
rows: List<RequestRef>,
onApprove: (String) -> Unit,
onReject: (String) -> Unit,
) {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(items = rows, key = { it.id }) { req ->
AdminRequestRow(
req = req,
requester = req.username.ifEmpty {
req.userId.take(USER_ID_PREFIX_LEN).ifEmpty { "unknown" }
},
onApprove = { onApprove(req.id) },
onReject = { onReject(req.id) },
)
HorizontalDivider()
}
}
}
@Composable
private fun AdminRequestRow(
req: RequestRef,
requester: String,
onApprove: () -> Unit,
onReject: () -> Unit,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
text = req.displayName,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = "Requested by $requester",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
AssistChip(
onClick = {},
enabled = false,
label = { Text(req.kind, style = MaterialTheme.typography.labelSmall) },
)
AssistChip(
onClick = {},
enabled = false,
label = { Text(req.status.wire, style = MaterialTheme.typography.labelSmall) },
)
}
if (req.artistName.isNotEmpty() && req.artistName != req.displayName) {
Text(
text = "Artist: ${req.artistName}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
) {
OutlinedButton(onClick = onReject) { Text("Reject") }
Button(onClick = onApprove) { Text("Approve") }
}
}
}
// UUID prefix length used as a friendlier-than-raw-UUID fallback when a
// row comes back without the requester's username.
private const val USER_ID_PREFIX_LEN = 8
@@ -1,105 +0,0 @@
package com.fabledsword.minstrel.admin.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fabledsword.minstrel.admin.data.AdminRequestsRepository
import com.fabledsword.minstrel.api.ErrorCopy
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.recoveries
import com.fabledsword.minstrel.events.EventsStream
import com.fabledsword.minstrel.models.RequestRef
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import javax.inject.Inject
private val RELEVANT_EVENT_KINDS = setOf("request.status_changed")
sealed interface AdminRequestsUiState {
data object Loading : AdminRequestsUiState
data object Empty : AdminRequestsUiState
data class Success(val rows: List<RequestRef>) : AdminRequestsUiState
data class Error(val message: String) : AdminRequestsUiState
}
@HiltViewModel
class AdminRequestsViewModel @Inject constructor(
private val repository: AdminRequestsRepository,
private val eventsStream: EventsStream,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow<AdminRequestsUiState>(AdminRequestsUiState.Loading)
val uiState: StateFlow<AdminRequestsUiState> = internal.asStateFlow()
init {
refresh()
viewModelScope.launch {
eventsStream.events
.filter { it.kind in RELEVANT_EVENT_KINDS }
.collect { refresh() }
}
// Screen-level auto-recovery: reload a failed list
// when server health returns instead of waiting for a manual pull.
viewModelScope.launch {
networkStatus.recoveries().collect {
if (internal.value is AdminRequestsUiState.Error) refresh()
}
}
}
fun refresh(): Job = viewModelScope.launch {
internal.value = AdminRequestsUiState.Loading
try {
val rows = repository.list()
internal.value = if (rows.isEmpty()) {
AdminRequestsUiState.Empty
} else {
AdminRequestsUiState.Success(rows = rows)
}
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = AdminRequestsUiState.Error(
ErrorCopy.fromThrowable(e),
)
}
}
fun approve(id: String) = decide(id) { repository.approve(it) }
fun reject(id: String) = decide(id) { repository.reject(it) }
/**
* Optimistically removes the decided row from the visible list and
* fires the REST call. On failure, refetches so the UI matches the
* server's view rather than leaving a phantom hole.
*/
private fun decide(id: String, action: suspend (String) -> Unit) {
val before = internal.value
if (before is AdminRequestsUiState.Success) {
val filtered = before.rows.filterNot { it.id == id }
internal.value = if (filtered.isEmpty()) {
AdminRequestsUiState.Empty
} else {
AdminRequestsUiState.Success(rows = filtered)
}
}
viewModelScope.launch {
try {
action(id)
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
// Refetch reconciles whatever the server now says about
// this request; the error is intentionally swallowed
// because the refresh result IS the user-facing signal.
refresh()
}
}
}
}
@@ -81,7 +81,6 @@ fun AdminUsersScreen(
invitesViewModel.refresh()
},
onSetAdmin = viewModel::setAdmin,
onSetAutoApprove = viewModel::setAutoApprove,
onAskResetPassword = { resetPasswordFor = it },
onAskDelete = { deleteCandidate = it },
onAskGenerateInvite = { showGenerateInvite = true },
@@ -121,7 +120,6 @@ private fun AdminUsersScaffold(
invitesState: AdminInvitesUiState,
onRefresh: suspend () -> Unit,
onSetAdmin: (String, Boolean) -> Unit,
onSetAutoApprove: (String, Boolean) -> Unit,
onAskResetPassword: (AdminUserRef) -> Unit,
onAskDelete: (AdminUserRef) -> Unit,
onAskGenerateInvite: () -> Unit,
@@ -148,7 +146,6 @@ private fun AdminUsersScaffold(
usersSection(
state = usersState,
onSetAdmin = onSetAdmin,
onSetAutoApprove = onSetAutoApprove,
onAskResetPassword = onAskResetPassword,
onAskDelete = onAskDelete,
)
@@ -195,7 +192,6 @@ private fun SectionHeader(label: String, trailing: (@Composable () -> Unit)? = n
private fun androidx.compose.foundation.lazy.LazyListScope.usersSection(
state: AdminUsersUiState,
onSetAdmin: (String, Boolean) -> Unit,
onSetAutoApprove: (String, Boolean) -> Unit,
onAskResetPassword: (AdminUserRef) -> Unit,
onAskDelete: (AdminUserRef) -> Unit,
) {
@@ -207,7 +203,6 @@ private fun androidx.compose.foundation.lazy.LazyListScope.usersSection(
UserRow(
user = user,
onSetAdmin = { onSetAdmin(user.id, it) },
onSetAutoApprove = { onSetAutoApprove(user.id, it) },
onResetPassword = { onAskResetPassword(user) },
onDelete = { onAskDelete(user) },
)
@@ -397,7 +392,6 @@ private fun PendingDialogs(
private fun UserRow(
user: AdminUserRef,
onSetAdmin: (Boolean) -> Unit,
onSetAutoApprove: (Boolean) -> Unit,
onResetPassword: () -> Unit,
onDelete: () -> Unit,
) {
@@ -420,11 +414,6 @@ private fun UserRow(
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
ToggleRow(label = "Admin", checked = user.isAdmin, onChange = onSetAdmin)
ToggleRow(
label = "Auto-approve requests",
checked = user.autoApproveRequests,
onChange = onSetAutoApprove,
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.End),
@@ -62,11 +62,6 @@ class AdminUsersViewModel @Inject constructor(
repository.setAdmin(it, isAdmin)
}
fun setAutoApprove(id: String, autoApprove: Boolean) =
patch(id, { it.copy(autoApproveRequests = autoApprove) }) {
repository.setAutoApprove(it, autoApprove)
}
fun resetPassword(id: String, newPassword: String) {
viewModelScope.launch {
runCatching { repository.resetPassword(id, newPassword) }
@@ -8,9 +8,9 @@ import javax.inject.Singleton
/**
* Attaches the session cookie from [AuthStore] to Minstrel-server
* requests, captures Set-Cookie from successful responses (login
* flow), and clears the store on 401 so downstream code can react
* to logout.
* requests (waiting for the stored one to load at launch), captures
* Set-Cookie from successful responses (login flow), and signs out when
* the server refuses the cookie a request carried.
*
* Scoped to the [BaseUrlInterceptor.PLACEHOLDER_HOST] sentinel host
* the same way BaseUrlInterceptor is. The shared OkHttpClient also
@@ -32,7 +32,7 @@ class AuthCookieInterceptor @Inject constructor(
// session. Pass through untouched.
return chain.proceed(original)
}
val cookie = authStore.sessionCookie.value
val cookie = authStore.sessionCookieForRequest()
val request = original.newBuilder().apply {
if (!cookie.isNullOrEmpty()) header("Cookie", cookie)
}.build()
@@ -40,7 +40,11 @@ class AuthCookieInterceptor @Inject constructor(
val response = chain.proceed(request)
if (response.code == HTTP_UNAUTHORIZED) {
authStore.setSessionCookie(null)
// Only a refusal of the cookie this request carried ends the
// session. A request sent without one says nothing about the
// stored login, and a refusal of an older cookie must not
// discard one a sign-in has stored since.
if (!cookie.isNullOrEmpty()) authStore.dropRejectedSessionCookie(cookie)
} else if (response.isSuccessful) {
// Capture the first Set-Cookie pair on login; subsequent
// responses that include Set-Cookie keep the store fresh.
@@ -24,7 +24,7 @@ import javax.inject.Singleton
* rewritten. Absolute external URLs — artwork from
* artwork.musicbrainz.org / coverartarchive.org, for example — must
* reach their authored host unchanged: rewritten to the Minstrel host
* they 404, and Discover suggestions show no covers.
* they 404, and the art never shows.
*
* No-op when the stored base URL is unparseable (falls through to
* whatever Retrofit had) — that case shows up as a transport-level
@@ -1,24 +0,0 @@
package com.fabledsword.minstrel.api.endpoints
import com.fabledsword.minstrel.models.wire.RequestWire
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
/**
* Retrofit interface for `/api/admin/requests`.
*
* Server returns the same `requestView` shape as the user-side
* `/api/requests`, so RequestWire is reused. Different listing scope —
* admin sees all users' requests, not just the caller's.
*/
interface AdminRequestsApi {
@GET("api/admin/requests")
suspend fun list(): List<RequestWire>
@POST("api/admin/requests/{id}/approve")
suspend fun approve(@Path("id") id: String)
@POST("api/admin/requests/{id}/reject")
suspend fun reject(@Path("id") id: String)
}
@@ -9,14 +9,7 @@ import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.Path
/**
* Retrofit interface for `/api/admin/users`.
*
* Note: the PUT-auto-approve body field is `auto_approve`, NOT
* `auto_approve_requests` — the request shape differs from the
* response field name. Verified against `internal/api/admin_users.go
* adminAutoApproveReq` (May 2026).
*/
/** Retrofit interface for `/api/admin/users`. */
interface AdminUsersApi {
@GET("api/admin/users")
suspend fun list(): AdminUsersListWire
@@ -24,9 +17,6 @@ interface AdminUsersApi {
@PUT("api/admin/users/{id}/admin")
suspend fun setAdmin(@Path("id") id: String, @Body body: SetAdminBody)
@PUT("api/admin/users/{id}/auto-approve")
suspend fun setAutoApprove(@Path("id") id: String, @Body body: SetAutoApproveBody)
@POST("api/admin/users/{id}/reset-password")
suspend fun resetPassword(@Path("id") id: String, @Body body: ResetPasswordBody)
@@ -39,10 +29,5 @@ data class SetAdminBody(
@kotlinx.serialization.SerialName("is_admin") val isAdmin: Boolean,
)
@Serializable
data class SetAutoApproveBody(
@kotlinx.serialization.SerialName("auto_approve") val autoApprove: Boolean,
)
@Serializable
data class ResetPasswordBody(val password: String)
@@ -1,62 +0,0 @@
package com.fabledsword.minstrel.api.endpoints
import com.fabledsword.minstrel.models.wire.ArtistSuggestionWire
import com.fabledsword.minstrel.models.wire.CreateRequestBody
import com.fabledsword.minstrel.models.wire.CatalogueSearchResultWire
import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody
import com.fabledsword.minstrel.models.wire.SuggestionSnoozeWire
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
import retrofit2.http.Query
/**
* Retrofit interface for Discover / catalogue search / request creation.
*
* `/api/catalogue/search` asks MusicBrainz, which allows one request a
* second, so the Discover screen searches when the query is submitted,
* not on every keystroke.
*
* Cancel + my-requests-list endpoints live on RequestsApi, not here.
*/
interface DiscoverApi {
@GET("api/discover/suggestions")
suspend fun listSuggestions(): List<ArtistSuggestionWire>
@GET("api/catalogue/search")
suspend fun search(
@Query("q") query: String,
@Query("kind") kind: String,
): List<CatalogueSearchResultWire>
@POST("api/requests")
suspend fun createRequest(@Body body: CreateRequestBody)
/**
* Parks a suggestion — "not right now", NOT a dislike. Time-boxed
* server-side (90 days) and never fed into the taste profile.
*
* [body] must carry the artist's name: candidates are out-of-library, so
* the server has no local row to resolve a display name from and returns
* 400 without it.
*/
@POST("api/discover/suggestions/{mbid}/snooze")
suspend fun snoozeSuggestion(
@Path("mbid") mbid: String,
@Body body: SnoozeSuggestionBody,
)
/** Brings a parked suggestion back. 404 when it wasn't snoozed. */
@DELETE("api/discover/suggestions/{mbid}/snooze")
suspend fun unsnoozeSuggestion(@Path("mbid") mbid: String)
/**
* Currently-parked suggestions. Server filters expired rows, so every
* row returned is still snoozed. This is the only route back to an
* un-snooze once the card has left the deck.
*/
@GET("api/discover/snoozes")
suspend fun listSnoozes(): List<SuggestionSnoozeWire>
}
@@ -1,24 +0,0 @@
package com.fabledsword.minstrel.api.endpoints
import com.fabledsword.minstrel.models.wire.RequestWire
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.Path
/**
* Retrofit interface for the user-side `/api/requests`.
*
* Server scopes results to the caller — admins see only their own
* requests through this endpoint. The cross-user admin view lives on
* a separate `/api/admin/requests` route.
*
* The DELETE endpoint returns the cancelled row (not 204) so the UI
* can patch local state without a refetch.
*/
interface RequestsApi {
@GET("api/requests")
suspend fun listMine(): List<RequestWire>
@DELETE("api/requests/{id}")
suspend fun cancel(@Path("id") id: String): RequestWire
}
@@ -89,8 +89,11 @@ class AuthController @Inject constructor(
* + persisted userJson. Carries account-level flags (debug mode)
* that aren't in the login response. Best-effort: a network failure
* leaves the cached identity untouched. No-op when signed out.
* Waits for the stored login to load first: at launch this runs before
* it has, and would otherwise read the user as signed out and skip.
*/
suspend fun refreshProfile() {
authStore.awaitSessionHydrated()
if (!isSignedIn) return
val p = runCatching { meApi.getProfile() }.getOrNull() ?: return
val user = UserRef(
@@ -12,6 +12,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeoutOrNull
@@ -148,6 +149,49 @@ class AuthStore @Inject constructor(
scope.launch { cookieLock.withLock { storeCookie(value) } }
}
/**
* The cookie to attach to an outgoing request. Blocks the calling
* (OkHttp) thread until the stored cookie has loaded, up to
* [HYDRATION_DEADLINE_MS], so a request made in the first moment after
* launch carries the login instead of going out without it. Once
* hydration has finished this is a plain read.
*/
fun sessionCookieForRequest(): String? {
if (!cookieHydration.isCompleted) {
runBlocking { withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } }
}
return sessionCookieState.value
}
/**
* True once the server has refused the current session (see
* [dropRejectedSessionCookie]) and the UI has not yet sent the user to
* sign in. Held rather than fired, so a refusal that lands while the app
* is in the background is still acted on when it comes back. A sign-out
* the user asked for does not set it.
*/
private val sessionRejectedState = MutableStateFlow(false)
val sessionRejected: StateFlow<Boolean> = sessionRejectedState.asStateFlow()
/** The UI has opened the sign-in screen for a refused session. */
fun consumeSessionRejected() {
sessionRejectedState.value = false
}
/**
* Signs out because the server answered 401 to a request that carried
* [rejected]. Does nothing when the store has since moved on to another
* cookie (a sign-in landed meanwhile), so a refusal of an old session
* never discards a new one. What is persisted is read inside the lock,
* so a sign-in racing this call is the value that ends up stored.
*/
fun dropRejectedSessionCookie(rejected: String) {
if (!sessionCookieState.compareAndSet(rejected, null)) return
cookieTouched = true
scope.launch { cookieLock.withLock { storeCookie(sessionCookieState.value) } }
sessionRejectedState.value = true
}
private suspend fun hydrateSessionCookie() = cookieLock.withLock {
val legacy = runCatching { dao.get()?.sessionCookie }.getOrNull()
if (cookieTouched) return@withLock
@@ -38,6 +38,15 @@ class AuthGateViewModel @Inject constructor(
private val internal = MutableStateFlow<Any?>(null)
val startDestination: StateFlow<Any?> = internal.asStateFlow()
/**
* True when the server has ended the session while the app was in use;
* the root NavHost answers by opening the sign-in screen, then calls
* [consumeSessionRejected].
*/
val sessionRejected: StateFlow<Boolean> = authStore.sessionRejected
fun consumeSessionRejected() = authStore.consumeSessionRejected()
init {
viewModelScope.launch {
authStore.awaitSessionHydrated()
@@ -9,7 +9,7 @@ import kotlinx.datetime.Instant
* Cache row for one artist.
*
* Column names follow Kotlin idiom (camelCase) — the schema is purely
* internal to the app; the sync controller exchanges snake_case JSON
* internal to the app; the sync controller trades snake_case JSON
* with the server and our mappers translate at the boundary.
*/
@Entity(tableName = "cached_artists")
@@ -19,16 +19,15 @@ private const val QUEUED_MESSAGE = "Saved — will sync when online"
/**
* Stable mutation kinds the queue knows how to replay. Strings are
* persisted in `cached_mutations.kind` so renaming a variant breaks
* the on-disk queue — only ever add new kinds, never rename.
* the on-disk queue — never rename one. A kind can be removed: the
* replayer drops rows of a kind it doesn't know.
*/
object MutationKind {
const val LIKE_TOGGLE: String = "like_toggle"
const val REQUEST_CREATE: String = "request_create"
const val QUARANTINE_UNFLAG: String = "quarantine_unflag"
const val PLAYLIST_APPEND: String = "playlist_append"
const val QUARANTINE_FLAG: String = "quarantine_flag"
const val PLAY_OFFLINE: String = "play_offline"
const val REQUEST_CANCEL: String = "request_cancel"
const val PLAYBACK_ERROR_REPORT: String = "playback_error_report"
// Durable close-by-id for a play whose server row is already open
@@ -37,12 +36,6 @@ object MutationKind {
// background would duplicate the open row and leave it orphaned.
const val PLAY_ENDED: String = "play_ended"
// Suggestion snooze. ONE toggle kind rather than separate
// snooze/unsnooze kinds, mirroring LIKE_TOGGLE, so a snooze followed by
// an undo collapses to the latest intent instead of replaying as two
// opposed calls whose order decides the outcome.
const val SUGGESTION_SNOOZE_TOGGLE: String = "suggestion_snooze_toggle"
// Loudness-normalization preference. The payload is the whole
// preference, a target state like the toggles above, so queued changes
// collapse to the last one and an older one can never be replayed last.
@@ -73,23 +66,6 @@ data class LikeTogglePayload(
val desiredState: Boolean,
)
/**
* Persisted payload for `MutationKind.REQUEST_CREATE` (a Discover
* request that landed during a connectivity hiccup). Optional
* fields stay null when not applicable; the replayer rebuilds the
* `CreateRequestBody` from these.
*/
@Serializable
data class RequestCreatePayload(
val kind: String,
val artistMbid: String,
val artistName: String,
val albumMbid: String? = null,
val albumTitle: String? = null,
val trackMbid: String? = null,
val trackTitle: String? = null,
)
/**
* Write side of the offline mutation queue; [MutationReplayer] drains it.
*
@@ -137,11 +113,6 @@ class MutationQueue @Inject constructor(
),
)
suspend fun enqueueRequestCreate(payload: RequestCreatePayload): Long = insertUserDriven(
MutationKind.REQUEST_CREATE,
json.encodeToString(RequestCreatePayload.serializer(), payload),
)
suspend fun enqueueQuarantineUnflag(trackId: String): Long = insertUserDriven(
MutationKind.QUARANTINE_UNFLAG,
json.encodeToString(
@@ -173,25 +144,6 @@ class MutationQueue @Inject constructor(
),
)
/**
* Queues a suggestion snooze (or its undo) for replay. [desiredSnoozed]
* is the TARGET state, so repeated taps collapse to one replay.
*
* [name] is carried even for an un-snooze, where the server ignores it,
* so a single payload shape serves both directions.
*/
suspend fun enqueueSuggestionSnoozeToggle(
mbid: String,
name: String,
desiredSnoozed: Boolean,
): Long = insertUserDriven(
MutationKind.SUGGESTION_SNOOZE_TOGGLE,
json.encodeToString(
SuggestionSnoozeTogglePayload.serializer(),
SuggestionSnoozeTogglePayload(mbid, name, desiredSnoozed),
),
)
/** Queues the user's whole normalization preference for replay. */
suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long = insertUserDriven(
MutationKind.NORMALIZATION_SET,
@@ -217,14 +169,6 @@ class MutationQueue @Inject constructor(
json.encodeToString(NotificationSettingPayload.serializer(), payload),
)
suspend fun enqueueRequestCancel(requestId: String): Long = insertUserDriven(
MutationKind.REQUEST_CANCEL,
json.encodeToString(
RequestCancelPayload.serializer(),
RequestCancelPayload(requestId),
),
)
suspend fun enqueuePlayOffline(payload: PlayOfflinePayload): Long = dao.insert(
CachedMutationEntity(
kind = MutationKind.PLAY_OFFLINE,
@@ -257,21 +201,6 @@ class MutationQueue @Inject constructor(
}
}
/**
* Persisted payload for `MutationKind.SUGGESTION_SNOOZE_TOGGLE`.
* `desiredSnoozed` is the *target* state, matching [LikeTogglePayload], so
* the replayer can collapse repeated toggles for one candidate down to the
* last intent. Both directions are idempotent server-side: re-snoozing
* extends the window, and un-snoozing something already back is a 404 the
* replayer treats as permanent (nothing left to do).
*/
@Serializable
data class SuggestionSnoozeTogglePayload(
val mbid: String,
val name: String,
val desiredSnoozed: Boolean,
)
/**
* Persisted payload for `MutationKind.QUARANTINE_UNFLAG` — the
* `DELETE /api/quarantine/{trackId}` call lost during a connectivity
@@ -337,15 +266,6 @@ data class PlayEndedPayload(
val durationPlayedMs: Long,
)
/**
* Persisted payload for `MutationKind.REQUEST_CANCEL` — the
* `POST /api/requests/{id}/cancel` call lost during a connectivity
* hiccup. Server is idempotent on re-cancel (already-cancelled
* request stays cancelled).
*/
@Serializable
data class RequestCancelPayload(val requestId: String)
/**
* Persisted payload for `MutationKind.PLAYBACK_ERROR_REPORT` — the
* `POST /api/playback-errors` call lost during a connectivity hiccup.
@@ -3,7 +3,6 @@
package com.fabledsword.minstrel.cache.mutations
import com.fabledsword.minstrel.api.endpoints.AppendTracksRequest
import com.fabledsword.minstrel.api.endpoints.DiscoverApi
import com.fabledsword.minstrel.api.endpoints.EventsApi
import com.fabledsword.minstrel.api.endpoints.FlagRequest
import com.fabledsword.minstrel.api.endpoints.LikesApi
@@ -15,19 +14,16 @@ import com.fabledsword.minstrel.api.endpoints.PlaybackErrorReportRequest
import com.fabledsword.minstrel.api.endpoints.PlaybackErrorsApi
import com.fabledsword.minstrel.api.endpoints.PlaylistsApi
import com.fabledsword.minstrel.api.endpoints.QuarantineApi
import com.fabledsword.minstrel.api.endpoints.RequestsApi
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.models.wire.PlayEndedRequest
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody
import com.fabledsword.minstrel.auth.AuthStore
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
import com.fabledsword.minstrel.di.ApplicationScope
import com.fabledsword.minstrel.likes.data.LikesRepository
import com.fabledsword.minstrel.settings.data.NormalizationPrefs
import com.fabledsword.minstrel.models.wire.CreateRequestBody
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
@@ -78,11 +74,9 @@ class MutationReplayer @Inject constructor(
retrofit: Retrofit,
) {
private val likesApi: LikesApi = retrofit.create()
private val discoverApi: DiscoverApi = retrofit.create()
private val quarantineApi: QuarantineApi = retrofit.create()
private val playlistsApi: PlaylistsApi = retrofit.create()
private val eventsApi: EventsApi = retrofit.create()
private val requestsApi: RequestsApi = retrofit.create()
private val playbackErrorsApi: PlaybackErrorsApi = retrofit.create()
private val meApi: MeApi = retrofit.create()
private val notificationsApi: NotificationsApi = retrofit.create()
@@ -122,11 +116,11 @@ class MutationReplayer @Inject constructor(
private suspend fun drain() {
val rows = dao.getAll()
// Collapse superseded toggles (likes, suggestion snoozes): only the
// latest desired state per entity is replayed; older toggles for the
// same entity are dropped unsent. Without this, partial-failure +
// Collapse superseded toggles (likes, settings): only the latest
// desired state per entity is replayed; older toggles for the same
// entity are dropped unsent. Without this, partial-failure +
// differential retry could replay an older toggle last and invert the
// final state — a snooze the user already undid would come back.
// final state — an unlike the user already made would be undone.
val superseded = supersededToggleIds(rows, json)
for (row in rows) {
if (row.id in superseded) {
@@ -164,15 +158,12 @@ class MutationReplayer @Inject constructor(
*/
private suspend fun dispatch(row: CachedMutationEntity): Outcome = when (row.kind) {
MutationKind.LIKE_TOGGLE -> dispatchLikeToggle(row.payload)
MutationKind.REQUEST_CREATE -> dispatchRequestCreate(row.payload)
MutationKind.QUARANTINE_UNFLAG -> dispatchQuarantineUnflag(row.payload)
MutationKind.PLAYLIST_APPEND -> dispatchPlaylistAppend(row.payload)
MutationKind.QUARANTINE_FLAG -> dispatchQuarantineFlag(row.payload)
MutationKind.PLAY_OFFLINE -> dispatchPlayOffline(row.payload)
MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload)
MutationKind.REQUEST_CANCEL -> dispatchRequestCancel(row.payload)
MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload)
MutationKind.SUGGESTION_SNOOZE_TOGGLE -> dispatchSuggestionSnoozeToggle(row.payload)
MutationKind.NORMALIZATION_SET -> dispatchNormalizationSet(row.payload)
MutationKind.NOTIFICATION_READ,
MutationKind.NOTIFICATIONS_READ_ALL,
@@ -206,22 +197,6 @@ class MutationReplayer @Inject constructor(
return Outcome.SENT
}
private suspend fun dispatchRequestCreate(payload: String): Outcome {
val decoded = json.decodeFromString(RequestCreatePayload.serializer(), payload)
discoverApi.createRequest(
CreateRequestBody(
kind = decoded.kind,
artistMbid = decoded.artistMbid,
artistName = decoded.artistName,
albumMbid = decoded.albumMbid,
albumTitle = decoded.albumTitle,
trackMbid = decoded.trackMbid,
trackTitle = decoded.trackTitle,
),
)
return Outcome.SENT
}
private suspend fun dispatchQuarantineUnflag(payload: String): Outcome {
val decoded = json.decodeFromString(QuarantineUnflagPayload.serializer(), payload)
quarantineApi.unflag(decoded.trackId)
@@ -275,30 +250,6 @@ class MutationReplayer @Inject constructor(
return Outcome.SENT
}
private suspend fun dispatchRequestCancel(payload: String): Outcome {
val decoded = json.decodeFromString(RequestCancelPayload.serializer(), payload)
requestsApi.cancel(decoded.requestId)
return Outcome.SENT
}
/**
* Replays a suggestion snooze in whichever direction the payload asks for.
*
* The un-snooze branch can legitimately 404 (the row already lapsed, or a
* previous attempt landed and the response was lost). [outcomeFor] classes
* 404 as permanent → DROP, which is right: the user's intended end state
* already holds, so there is nothing left to send.
*/
private suspend fun dispatchSuggestionSnoozeToggle(payload: String): Outcome {
val decoded = json.decodeFromString(SuggestionSnoozeTogglePayload.serializer(), payload)
if (decoded.desiredSnoozed) {
discoverApi.snoozeSuggestion(decoded.mbid, SnoozeSuggestionBody(name = decoded.name))
} else {
discoverApi.unsnoozeSuggestion(decoded.mbid)
}
return Outcome.SENT
}
/**
* Sends the queued normalization preference. The device already shows
* it, so the server's echo is not written back: a change made since the
@@ -354,7 +305,7 @@ class MutationReplayer @Inject constructor(
/**
* Row ids of desired-state toggles superseded by a later toggle for the same
* entity. Applies to every kind whose payload encodes a TARGET state rather
* than an action — like-toggles, suggestion snoozes and the
* than an action — like-toggles, notification settings and the
* normalization preference — because
* replaying a stale one last would invert the final state.
*
@@ -388,10 +339,6 @@ private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when (
json.decodeFromString(LikeTogglePayload.serializer(), row.payload)
}.getOrNull()?.let { "${row.kind}:${it.entityType}:${it.entityId}" }
MutationKind.SUGGESTION_SNOOZE_TOGGLE -> runCatching {
json.decodeFromString(SuggestionSnoozeTogglePayload.serializer(), row.payload)
}.getOrNull()?.let { "${row.kind}:${it.mbid}" }
MutationKind.NOTIFICATION_SETTING_SET -> runCatching {
json.decodeFromString(NotificationSettingPayload.serializer(), row.payload)
}.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" }
@@ -70,6 +70,9 @@ class DiagnosticsUploader @Inject constructor(
/** Coalesces concurrent triggers via tryLock — a drain in flight wins. */
private suspend fun drainSafe() {
// A trigger at launch can fire before the stored login has loaded;
// wait for it, so a signed-in user is not read as signed out.
authStore.awaitSessionHydrated()
val clientId = authStore.clientId.value
// Signed out / no client id yet → nothing to do. Single guard keeps
// the return count within the detekt gate.
@@ -1,199 +0,0 @@
package com.fabledsword.minstrel.discover.data
import com.fabledsword.minstrel.api.endpoints.DiscoverApi
import com.fabledsword.minstrel.cache.mutations.MutationQueue
import com.fabledsword.minstrel.cache.mutations.RequestCreatePayload
import com.fabledsword.minstrel.models.ArtistSuggestionRef
import com.fabledsword.minstrel.models.RequestKind
import com.fabledsword.minstrel.models.CatalogueResultRef
import com.fabledsword.minstrel.models.SeedContributionRef
import com.fabledsword.minstrel.models.SuggestionSnoozeRef
import com.fabledsword.minstrel.models.wire.ArtistSuggestionWire
import com.fabledsword.minstrel.models.wire.CreateRequestBody
import com.fabledsword.minstrel.models.wire.CatalogueSearchResultWire
import com.fabledsword.minstrel.models.wire.SeedContributionWire
import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody
import com.fabledsword.minstrel.models.wire.SuggestionSnoozeWire
import retrofit2.HttpException
import retrofit2.Retrofit
import retrofit2.create
import javax.inject.Inject
import javax.inject.Singleton
/**
* Outcome of a `createRequest` call — discriminates "server accepted"
* from "network down, queued for later replay". The UI uses this to
* pick between "Requested" and "Queued" snackbars.
*/
enum class RequestOutcome { ACCEPTED, QUEUED }
/**
* Read-through Discover surface: catalogue search, suggestion feed, and
* the request-creation write path. Writes never go fire-and-forget, so
* `createRequest` falls back to the MutationQueue on transport failure.
*
* Reads are not cached locally — discovery results are inherently
* transient (60s server-side LRU), so a local cache would win little.
*/
@Singleton
class DiscoverRepository @Inject constructor(
private val mutationQueue: MutationQueue,
retrofit: Retrofit,
) {
private val api: DiscoverApi = retrofit.create()
suspend fun listSuggestions(): List<ArtistSuggestionRef> =
api.listSuggestions().map { it.toDomain() }
suspend fun listSnoozes(): List<SuggestionSnoozeRef> =
api.listSnoozes().map { it.toDomain() }
/**
* Parks a suggestion ("not right now"). Offline-first: on
* transport failure the target state is queued for the replayer rather
* than dropped.
*
* Always reports success to the caller. Unlike a request, a snooze has no
* meaningful failed state to show — the user asked for a card to go away,
* and it will, either now or when the queue drains.
*/
suspend fun snoozeSuggestion(mbid: String, name: String): Unit = toggleSnooze(
mbid = mbid,
name = name,
desiredSnoozed = true,
) { api.snoozeSuggestion(mbid, SnoozeSuggestionBody(name = name)) }
/** Brings a parked suggestion back. Same offline-first contract. */
suspend fun unsnoozeSuggestion(mbid: String, name: String): Unit = toggleSnooze(
mbid = mbid,
name = name,
desiredSnoozed = false,
) { api.unsnoozeSuggestion(mbid) }
private suspend fun toggleSnooze(
mbid: String,
name: String,
desiredSnoozed: Boolean,
call: suspend () -> Unit,
) {
try {
call()
} catch (e: HttpException) {
// A 4xx is the server's considered answer, not a lost call, so
// queueing it would be wrong twice over: the replay is guaranteed
// to fail again, and the enqueue would raise a "will sync when
// online" snackbar for something already settled. The common case
// is a 404 from un-snoozing a row that already lapsed — which is
// the end state the user wanted anyway.
if (!isPermanent(e.code())) {
mutationQueue.enqueueSuggestionSnoozeToggle(mbid, name, desiredSnoozed)
}
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
// Transport failure — intentional swallow, same offline-first
// rationale as createRequest above. The queue carries the desired
// STATE, so a later undo supersedes this rather than fighting it
// on replay.
mutationQueue.enqueueSuggestionSnoozeToggle(mbid, name, desiredSnoozed)
}
}
/**
* Mirrors MutationReplayer's classification so the enqueue decision here
* and the drop decision there can't disagree: 4xx is permanent except the
* two "retry me" statuses.
*/
private fun isPermanent(code: Int): Boolean =
code in HTTP_CLIENT_ERR_MIN..HTTP_CLIENT_ERR_MAX &&
code != HTTP_TIMEOUT && code != HTTP_TOO_MANY
suspend fun search(query: String, kind: RequestKind): List<CatalogueResultRef> =
api.search(query = query, kind = kind.wire).map { it.toDomain() }
/**
* Fires `POST /api/requests`; on transport failure enqueues a
* `RequestCreatePayload` for the Phase-12.2 replayer to drain.
* Returns [RequestOutcome.ACCEPTED] when the server responded
* 2xx, [RequestOutcome.QUEUED] when the call was buffered.
*/
suspend fun createRequest(
kind: RequestKind,
artistMbid: String,
artistName: String,
albumMbid: String? = null,
albumTitle: String? = null,
trackMbid: String? = null,
trackTitle: String? = null,
): RequestOutcome {
val payload = RequestCreatePayload(
kind = kind.wire,
artistMbid = artistMbid,
artistName = artistName,
albumMbid = albumMbid?.ifEmpty { null },
albumTitle = albumTitle?.ifEmpty { null },
trackMbid = trackMbid?.ifEmpty { null },
trackTitle = trackTitle?.ifEmpty { null },
)
return try {
api.createRequest(payload.toBody())
RequestOutcome.ACCEPTED
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
// Intentional swallow — see LikesRepository.toggleLike for
// the same offline-first rationale.
mutationQueue.enqueueRequestCreate(payload)
RequestOutcome.QUEUED
}
}
private companion object {
const val HTTP_CLIENT_ERR_MIN = 400
const val HTTP_CLIENT_ERR_MAX = 499
const val HTTP_TIMEOUT = 408
const val HTTP_TOO_MANY = 429
}
}
// ── Mappers (internal — wire types stay out of UI) ──
private fun CatalogueSearchResultWire.toDomain(): CatalogueResultRef = CatalogueResultRef(
mbid = mbid,
name = name,
secondaryText = secondaryText,
imageUrl = imageUrl,
artistMbid = artistMbid,
albumMbid = albumMbid,
inLibrary = inLibrary,
requested = requested,
)
private fun ArtistSuggestionWire.toDomain(): ArtistSuggestionRef = ArtistSuggestionRef(
mbid = mbid,
name = name,
imageUrl = imageUrl,
attribution = attribution.map { it.toDomain() },
matchedTags = matchedTags,
)
private fun SeedContributionWire.toDomain(): SeedContributionRef = SeedContributionRef(
name = name,
isLiked = isLiked,
)
private fun SuggestionSnoozeWire.toDomain(): SuggestionSnoozeRef = SuggestionSnoozeRef(
mbid = mbid,
name = name,
snoozedUntil = snoozedUntil,
)
private fun RequestCreatePayload.toBody(): CreateRequestBody = CreateRequestBody(
kind = kind,
artistMbid = artistMbid,
artistName = artistName,
albumMbid = albumMbid,
albumTitle = albumTitle,
trackMbid = trackMbid,
trackTitle = trackTitle,
)
@@ -1,353 +0,0 @@
package com.fabledsword.minstrel.discover.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Search as LucideSearch
import com.fabledsword.minstrel.discover.data.RequestOutcome
import com.fabledsword.minstrel.models.ArtistSuggestionRef
import com.fabledsword.minstrel.models.RequestKind
import com.fabledsword.minstrel.models.CatalogueResultRef
import com.fabledsword.minstrel.models.SuggestionSnoozeRef
import com.fabledsword.minstrel.nav.Discover
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import kotlinx.coroutines.launch
// ─── Screen ──────────────────────────────────────────────────────────
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DiscoverScreen(
navController: NavHostController,
viewModel: DiscoverViewModel = hiltViewModel(),
) {
val state by viewModel.state.collectAsStateWithLifecycle()
val snackbar = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
Scaffold(
contentWindowInsets = ShellContentWindowInsets,
modifier = Modifier.fillMaxSize(),
topBar = {
MinstrelTopAppBar(
title = "Discover",
navController = navController,
currentRouteName = Discover::class.qualifiedName,
onBack = { navController.popBackStack() },
)
},
snackbarHost = { SnackbarHost(snackbar) },
) { inner ->
DiscoverBody(
inner = inner,
state = state,
viewModel = viewModel,
snackbar = snackbar,
scope = scope,
)
}
}
@Composable
private fun DiscoverBody(
inner: androidx.compose.foundation.layout.PaddingValues,
state: DiscoverState,
viewModel: DiscoverViewModel,
snackbar: SnackbarHostState,
scope: kotlinx.coroutines.CoroutineScope,
) {
Column(modifier = Modifier.fillMaxSize().padding(inner)) {
SearchBar(
query = state.query,
onQueryChange = viewModel::setQuery,
onSubmit = viewModel::runSearch,
)
KindChips(kind = state.kind, onChange = viewModel::setKind)
PullToRefreshScaffold(
onRefresh = { viewModel.loadSuggestions().join() },
modifier = Modifier.fillMaxSize(),
) {
when (val r = state.results) {
ResultsState.Idle -> SuggestionsPane(
state = state.suggestions,
locallyRequestedMbids = state.locallyRequestedMbids,
snoozeUi = SnoozeUi(
locallySnoozedMbids = state.locallySnoozedMbids,
snoozes = state.snoozes,
// No snackbar on snooze: the row itself flips to "Not
// right now" with an Undo, so a snackbar would only
// repeat what the user can already see — and cover the
// next row while doing it.
onSnooze = { s -> scope.launch { viewModel.snoozeSuggestion(s) } },
onUnsnooze = { mbid, name ->
scope.launch { viewModel.unsnoozeSuggestion(mbid, name) }
},
),
onRequest = { s ->
scope.launch {
val outcome = viewModel.requestSuggestion(s)
snackbar.showSnackbar(snackbarFor(outcome, s.name))
}
},
onRetry = { viewModel.loadSuggestions() },
)
ResultsState.Loading -> LoadingCentered()
is ResultsState.Loaded -> ResultsList(
rows = r.items,
locallyRequestedMbids = state.locallyRequestedMbids,
onRequest = { row ->
scope.launch {
val outcome = viewModel.requestRow(row)
snackbar.showSnackbar(snackbarFor(outcome, row.name))
}
},
)
is ResultsState.Error -> ErrorRetry(
title = "Search failed",
message = r.message,
onRetry = viewModel::runSearch,
)
}
}
}
}
@Composable
private fun SearchBar(
query: String,
onQueryChange: (String) -> Unit,
onSubmit: () -> Unit,
) {
OutlinedTextField(
value = query,
onValueChange = onQueryChange,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
singleLine = true,
placeholder = { Text("Search MusicBrainz for new music") },
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(onSearch = { onSubmit() }),
trailingIcon = {
IconButton(onClick = onSubmit) {
Icon(Lucide.LucideSearch, contentDescription = "Search")
}
},
)
}
@Composable
private fun KindChips(kind: RequestKind, onChange: (RequestKind) -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
FilterChip(
selected = kind == RequestKind.ARTIST,
onClick = { onChange(RequestKind.ARTIST) },
label = { Text("Artists") },
)
FilterChip(
selected = kind == RequestKind.ALBUM,
onClick = { onChange(RequestKind.ALBUM) },
label = { Text("Albums") },
)
}
}
/**
* The snooze surface's data and callbacks, bundled rather than threaded
* through as separate parameters: the pane carries three actions, and the
* signatures stop being readable otherwise.
*/
private data class SnoozeUi(
val locallySnoozedMbids: Set<String>,
val snoozes: List<SuggestionSnoozeRef>,
val onSnooze: (ArtistSuggestionRef) -> Unit,
val onUnsnooze: (String, String) -> Unit,
)
@Composable
private fun SuggestionsPane(
state: SuggestionState,
locallyRequestedMbids: Set<String>,
snoozeUi: SnoozeUi,
onRequest: (ArtistSuggestionRef) -> Unit,
onRetry: () -> Unit,
) {
when (state) {
SuggestionState.Loading -> LoadingCentered()
is SuggestionState.Error -> ErrorRetry(
title = "Couldn't load suggestions",
message = state.message,
onRetry = onRetry,
)
is SuggestionState.Loaded -> SuggestionsList(
items = state.items.filter { it.mbid !in locallyRequestedMbids },
snoozeUi = snoozeUi,
onRequest = onRequest,
)
}
}
@Composable
private fun SuggestionsList(
items: List<ArtistSuggestionRef>,
snoozeUi: SnoozeUi,
onRequest: (ArtistSuggestionRef) -> Unit,
) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(bottom = 16.dp),
) {
item { SuggestionsHeader() }
if (items.isEmpty()) {
// An empty deck means one of two things — no listening signal yet,
// or "you parked them all" — and telling the second user to go
// listen to something would be wrong advice.
item {
CenteredMessage(
if (snoozeUi.snoozes.isEmpty()) {
"Listen to or like an artist to fill this in."
} else {
"Nothing new right now — the artists you've parked are below."
},
)
}
} else {
items(items = items, key = { it.mbid }) { s ->
SuggestionTile(
s = s,
snoozed = s.mbid in snoozeUi.locallySnoozedMbids,
onRequest = { onRequest(s) },
onSnooze = { snoozeUi.onSnooze(s) },
onUnsnooze = { snoozeUi.onUnsnooze(s.mbid, s.name) },
)
HorizontalDivider()
}
}
// Parked candidates live at the bottom of the same scroll, not behind a
// separate screen: it's a short list the user rarely needs, but it must
// be reachable — a snoozed candidate is gone from the deck above, so
// this is the only way back to it.
if (snoozeUi.snoozes.isNotEmpty()) {
item { SnoozedHeader() }
items(items = snoozeUi.snoozes, key = { "snoozed-${it.mbid}" }) { row ->
SnoozedTile(
row = row,
onUnsnooze = { snoozeUi.onUnsnooze(row.mbid, row.name) },
)
HorizontalDivider()
}
}
}
}
@Composable
private fun SnoozedHeader() {
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
HorizontalDivider(modifier = Modifier.padding(bottom = 12.dp))
Text(
text = "Not right now",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onBackground,
)
Text(
text = "These come back on their own. Nothing here counts against your taste profile.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun SuggestionsHeader() {
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {
Text(
text = "Suggested for you",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onBackground,
)
Text(
text = "Out-of-library artists drawn from what you've liked and played.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun ResultsList(
rows: List<CatalogueResultRef>,
locallyRequestedMbids: Set<String>,
onRequest: (CatalogueResultRef) -> Unit,
) {
if (rows.isEmpty()) {
CenteredMessage("Nothing to add for that search yet.")
return
}
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(items = rows, key = { it.mbid }) { row ->
ResultTile(
row = row,
locallyRequested = row.mbid in locallyRequestedMbids,
onRequest = { onRequest(row) },
)
HorizontalDivider()
}
}
}
@Composable
private fun CenteredMessage(text: String) {
Box(modifier = Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) {
Text(
text = text,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
private fun snackbarFor(outcome: RequestOutcome, name: String): String = when (outcome) {
RequestOutcome.ACCEPTED -> "Requested: $name"
RequestOutcome.QUEUED -> "Request queued: $name"
}
@@ -1,191 +0,0 @@
package com.fabledsword.minstrel.discover.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AssistChip
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.composables.icons.lucide.Clock
import com.composables.icons.lucide.Disc3
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.User
import com.fabledsword.minstrel.models.ArtistSuggestionRef
import com.fabledsword.minstrel.models.CatalogueResultRef
import com.fabledsword.minstrel.models.SuggestionSnoozeRef
import com.fabledsword.minstrel.shared.widgets.ServerImage
@Composable
internal fun SuggestionTile(
s: ArtistSuggestionRef,
snoozed: Boolean,
onRequest: () -> Unit,
onSnooze: () -> Unit,
onUnsnooze: () -> Unit,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Avatar(imageUrl = s.imageUrl, fallback = Lucide.User, circular = true)
Column(modifier = Modifier.weight(1f)) {
Text(
text = s.name,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
// Once parked, the "because you liked X" line is no longer the
// useful thing to say — confirming what just happened is.
val secondary =
if (snoozed) "Not right now — hidden for a while" else s.reasonText
if (secondary.isNotEmpty()) {
Text(
text = secondary,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
}
if (snoozed) {
TextButton(onClick = onUnsnooze) { Text("Undo") }
} else {
Button(onClick = onRequest) { Text("Request") }
IconButton(onClick = onSnooze) {
Icon(
imageVector = Lucide.Clock,
// The label states what happens and passes no judgement on the
// music: never "not for me".
contentDescription = "Not right now — hide ${s.name} for a while",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
/**
* One row of the parked list. This exists because a snoozed candidate is by
* definition absent from the deck above, so without it there is no route back
* to an un-snooze once the card has gone.
*/
@Composable
internal fun SnoozedTile(row: SuggestionSnoozeRef, onUnsnooze: () -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = row.name,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = "Back ${row.returnsIn()}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
TextButton(onClick = onUnsnooze) { Text("Bring back") }
}
}
@Composable
internal fun ResultTile(
row: CatalogueResultRef,
locallyRequested: Boolean,
onRequest: () -> Unit,
) {
val effectivelyRequested = row.requested || locallyRequested
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Avatar(imageUrl = row.imageUrl, fallback = Lucide.Disc3, circular = false)
Column(modifier = Modifier.weight(1f)) {
Text(
text = row.name,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (row.secondaryText.isNotEmpty()) {
Text(
text = row.secondaryText,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
when {
row.inLibrary -> AssistChip(onClick = {}, enabled = false, label = { Text("In library") })
effectivelyRequested ->
AssistChip(onClick = {}, enabled = false, label = { Text("Requested") })
else -> Button(onClick = onRequest) { Text("Request") }
}
}
}
@Composable
private fun Avatar(imageUrl: String, fallback: ImageVector, circular: Boolean) {
val clip = if (circular) CircleShape else RoundedCornerShape(6.dp)
Box(
modifier = Modifier
.size(56.dp)
.clip(clip)
.background(MaterialTheme.colorScheme.surfaceVariant),
contentAlignment = Alignment.Center,
) {
// The server hands back its own art endpoint (relative),
// which answers 404 when no source has an image: ServerImage resolves
// the path and shows the icon while loading and on a miss.
ServerImage(
url = imageUrl,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
) {
Icon(
imageVector = fallback,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@@ -1,206 +0,0 @@
package com.fabledsword.minstrel.discover.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fabledsword.minstrel.api.ErrorCopy
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.recoveries
import com.fabledsword.minstrel.discover.data.DiscoverRepository
import com.fabledsword.minstrel.discover.data.RequestOutcome
import com.fabledsword.minstrel.models.ArtistSuggestionRef
import com.fabledsword.minstrel.models.RequestKind
import com.fabledsword.minstrel.models.CatalogueResultRef
import com.fabledsword.minstrel.models.SuggestionSnoozeRef
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
// ─── State ───────────────────────────────────────────────────────────
data class DiscoverState(
val query: String = "",
val kind: RequestKind = RequestKind.ARTIST,
val suggestions: SuggestionState = SuggestionState.Loading,
val results: ResultsState = ResultsState.Idle,
val locallyRequestedMbids: Set<String> = emptySet(),
/**
* Parked candidates, for the manage list under the feed. Empty is the
* normal case and hides the section entirely.
*/
val snoozes: List<SuggestionSnoozeRef> = emptyList(),
/**
* Just-snoozed MBIDs. These keep their row visible showing an Undo rather
* than yanking it out from under the user's finger; the row is gone on the
* next load, and [snoozes] is the way back after that.
*/
val locallySnoozedMbids: Set<String> = emptySet(),
)
sealed interface SuggestionState {
data object Loading : SuggestionState
data class Loaded(val items: List<ArtistSuggestionRef>) : SuggestionState
data class Error(val message: String) : SuggestionState
}
sealed interface ResultsState {
/** No active search — the screen shows the suggestion feed. */
data object Idle : ResultsState
data object Loading : ResultsState
data class Loaded(val items: List<CatalogueResultRef>) : ResultsState
data class Error(val message: String) : ResultsState
}
// ─── ViewModel ───────────────────────────────────────────────────────
@HiltViewModel
class DiscoverViewModel @Inject constructor(
private val repository: DiscoverRepository,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow(DiscoverState())
val state: StateFlow<DiscoverState> = internal.asStateFlow()
init {
loadSuggestions()
// Screen-level auto-recovery: re-run whichever pane
// failed while the server was unreachable once health returns.
viewModelScope.launch {
networkStatus.recoveries().collect {
val s = internal.value
if (s.suggestions is SuggestionState.Error) loadSuggestions()
if (s.results is ResultsState.Error) runSearch()
}
}
}
fun setQuery(value: String) {
internal.update {
// Clearing the box returns to the suggestion feed.
val newResults = if (value.isBlank()) ResultsState.Idle else it.results
it.copy(query = value, results = newResults)
}
}
fun setKind(kind: RequestKind) {
internal.update { it.copy(kind = kind) }
if (internal.value.query.isNotBlank()) runSearch()
}
fun loadSuggestions(): Job = viewModelScope.launch {
internal.update { it.copy(suggestions = SuggestionState.Loading) }
try {
val items = repository.listSuggestions()
internal.update { it.copy(suggestions = SuggestionState.Loaded(items)) }
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.update {
it.copy(
suggestions = SuggestionState.Error(
ErrorCopy.fromThrowable(e),
),
)
}
}
// Refresh the parked list alongside the deck: a snooze made on another
// client should show up here, and one whose window lapsed should drop
// off. Sequenced after the deck load rather than raced with it so the
// two panes can't disagree about a candidate mid-refresh.
loadSnoozes()
}
/**
* Loads the parked list. Failure is deliberately silent: this is a
* secondary pane, and an error banner for it would sit above the suggestion
* feed the user actually came for. The list stays as-is and the next
* refresh retries.
*/
private suspend fun loadSnoozes() {
try {
val rows = repository.listSnoozes()
internal.update { it.copy(snoozes = rows) }
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
// Keep whatever we last showed rather than blanking the section.
}
}
/**
* Parks a suggestion. Flips the row locally first so the tap registers
* immediately; the repository handles the offline case, so there is no
* failure branch to revert here — unlike the web client, where the fetch
* either lands or doesn't.
*/
suspend fun snoozeSuggestion(s: ArtistSuggestionRef) {
internal.update { it.copy(locallySnoozedMbids = it.locallySnoozedMbids + s.mbid) }
repository.snoozeSuggestion(s.mbid, s.name)
loadSnoozes()
}
/** Brings a parked suggestion back, from either the card or the list. */
suspend fun unsnoozeSuggestion(mbid: String, name: String) {
internal.update { it.copy(locallySnoozedMbids = it.locallySnoozedMbids - mbid) }
repository.unsnoozeSuggestion(mbid, name)
loadSnoozes()
}
fun runSearch() {
val q = internal.value.query.trim()
if (q.isEmpty()) {
internal.update { it.copy(results = ResultsState.Idle) }
return
}
viewModelScope.launch {
internal.update { it.copy(results = ResultsState.Loading) }
try {
val rows = repository.search(q, internal.value.kind)
internal.update { it.copy(results = ResultsState.Loaded(rows)) }
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.update {
it.copy(results = ResultsState.Error(ErrorCopy.fromThrowable(e)))
}
}
}
}
/**
* Request a search-result row. Returns the outcome (ACCEPTED vs
* QUEUED) so the screen can pick the snackbar wording and update
* the local "requested" overlay.
*/
suspend fun requestRow(row: CatalogueResultRef): RequestOutcome {
val kind = internal.value.kind
val outcome = repository.createRequest(
kind = kind,
artistMbid = if (kind == RequestKind.ARTIST) row.mbid else row.artistMbid,
artistName = if (kind == RequestKind.ARTIST) row.name else row.secondaryText,
albumMbid = if (kind == RequestKind.ALBUM) row.mbid else null,
albumTitle = if (kind == RequestKind.ALBUM) row.name else null,
)
markRequested(row.mbid)
return outcome
}
suspend fun requestSuggestion(s: ArtistSuggestionRef): RequestOutcome {
val outcome = repository.createRequest(
kind = RequestKind.ARTIST,
artistMbid = s.mbid,
artistName = s.name,
)
markRequested(s.mbid)
return outcome
}
private fun markRequested(mbid: String) {
internal.update { it.copy(locallyRequestedMbids = it.locallyRequestedMbids + mbid) }
}
}
@@ -781,6 +781,13 @@ private fun HomeSuccessContent(
onPlayPool = onPlayPool,
onPlayPlaylist = onPlayPlaylist,
)
genreMixSection(
playlists = sections.playlists,
offline = offline,
onPlaylistClick = onPlaylistClick,
onPlayPool = onPlayPool,
onPlayPlaylist = onPlayPlaylist,
)
youMightLikeSection(
albums = sections.youMightLikeAlbums,
artists = sections.youMightLikeArtists,
@@ -833,6 +840,31 @@ private fun LazyListScope.songsLikeSection(
}
}
/**
* The "Your genres" row: one mix per genre the user listens to. Hidden
* when there is nothing to show, built or cached.
*/
private fun LazyListScope.genreMixSection(
playlists: List<PlaylistRef>,
offline: Boolean,
onPlaylistClick: (String) -> Unit,
onPlayPool: (OfflinePoolKind) -> Unit,
onPlayPlaylist: suspend (PlaylistRef) -> Unit,
) {
val rowItems = buildGenreMixRow(playlists, offline)
if (rowItems.isEmpty()) return
item {
PlaylistsRow(
title = "Your genres",
rowItems = rowItems,
offline = offline,
onPlaylistClick = onPlaylistClick,
onPlayPool = onPlayPool,
onPlayPlaylist = onPlayPlaylist,
)
}
}
private fun LazyListScope.recentlyAddedSection(
albums: List<HomeTile<AlbumRef>>,
onAlbumClick: (String) -> Unit,
@@ -1233,6 +1265,25 @@ internal fun buildSongsLikeRow(
}
}
/**
* Builds the "Your genres" row: every genre mix, in name order so the
* shelf reads like a stable channel list. No placeholders — a genre mix
* needs listening history or a genre-tagged library, so none built means
* nothing to show. Offline, fully-cached mixes come first and the rest are
* greyed. Mirrors the web Home's genreMixPlaylists.
*/
internal fun buildGenreMixRow(
owned: List<PlaylistRef>,
offline: Boolean,
): List<PlaylistRowItem> {
val mixes = owned
.filter { it.systemVariant == "genre_mix" }
.sortedBy { it.name.lowercase() }
if (!offline) return mixes.map { PlaylistRowItem.Real(it) }
val (available, greyed) = mixes.partition { !it.unavailableOffline }
return (available + greyed).map { PlaylistRowItem.Real(it) }
}
/**
* Curated real-playlist order (system primaries, then secondary, then user).
* Must mirror [buildOnlineRow]'s slot order — the offline row reuses this and
@@ -1,8 +1,7 @@
package com.fabledsword.minstrel.models
/**
* One admin-side user row. The
* admin-scoped variant exposes `autoApproveRequests` and the
* One admin-side user row. The admin-scoped variant carries the
* canonical `createdAt` that the user-scoped /me response omits.
*/
data class AdminUserRef(
@@ -10,6 +9,5 @@ data class AdminUserRef(
val username: String,
val displayName: String? = null,
val isAdmin: Boolean = false,
val autoApproveRequests: Boolean = false,
val createdAt: String = "",
)
@@ -1,157 +0,0 @@
package com.fabledsword.minstrel.models
import kotlinx.datetime.Instant
import kotlin.math.roundToInt
/**
* Kind of request being created. Wire form is the lowercase
* enum name; the helper [wire] keeps that mapping in one place.
*/
enum class RequestKind {
ARTIST, ALBUM, TRACK;
val wire: String get() = name.lowercase()
}
/**
* Catalogue search hit — `mbid` is the result's own MBID; `artistMbid`
* and `albumMbid` are filled when the row is an album/track and the
* UI needs the parent IDs to build the request.
*
* `inLibrary` and `requested` together cover the "already-handled"
* cases — UI greys the row + swaps the Request button for a pill.
*/
data class CatalogueResultRef(
val mbid: String,
val name: String,
val secondaryText: String = "",
val imageUrl: String = "",
val artistMbid: String = "",
val albumMbid: String = "",
val inLibrary: Boolean = false,
val requested: Boolean = false,
)
/**
* Per-seed attribution string for a suggestion — "you liked X" /
* "you played Y". `isLiked = true` discriminates the verb.
*/
data class SeedContributionRef(
val name: String,
val isLiked: Boolean,
)
/**
* Out-of-library artist suggestion from `GET /api/discover/suggestions`.
* `attributionText` names up to 3 seeds with an Oxford comma so the
* subtitle reads naturally.
*/
data class ArtistSuggestionRef(
val mbid: String,
val name: String,
val imageUrl: String = "",
val attribution: List<SeedContributionRef> = emptyList(),
/** Taste-profile tags this candidate matches, strongest first. */
val matchedTags: List<String> = emptyList(),
) {
val attributionText: String
get() {
if (attribution.isEmpty()) return ""
val phrases = attribution
.take(MAX_ATTRIBUTION_PHRASES)
.map { "${if (it.isLiked) "liked" else "played"} ${it.name}" }
return when (phrases.size) {
1 -> "Because you ${phrases[0]}."
2 -> "Because you ${phrases[0]} and ${phrases[1]}."
else -> "Because you ${phrases[0]}, ${phrases[1]}, and ${phrases[2]}."
}
}
/**
* The subtitle line for the card.
*
* Prefers the taste-tag reason over seed attribution when we have one,
* because it describes the MUSIC ("sounds like what you like") rather than
* the graph ("adjacent to something you played"). Falls back to
* attribution, which is the common case: tag coverage for out-of-library
* artists is partial by nature, so most candidates have no matched tags.
*
* Kept in lockstep with the web client's reasonText() in
* SuggestionFeed.svelte — same wording, same Oxford comma.
*/
val reasonText: String
get() {
val tags = matchedTags.take(MAX_ATTRIBUTION_PHRASES)
return when (tags.size) {
0 -> attributionText
1 -> "Matches your taste in ${tags[0]}."
2 -> "Matches your taste in ${tags[0]} and ${tags[1]}."
else -> "Matches your taste in ${tags[0]}, ${tags[1]}, and ${tags[2]}."
}
}
companion object {
private const val MAX_ATTRIBUTION_PHRASES = 3
}
}
/**
* A suggestion the user parked with "not right now".
*
* Deliberately NOT a dislike: it carries no verdict on the artist, expires on
* its own, and never reaches the taste profile. Anything that treats this as
* negative preference signal is a bug.
*
* [snoozedUntil] is the raw RFC3339 string from the wire. Only the server
* decides whether a snooze is still in effect — every row the client receives
* already is — so this is read purely to phrase "back in about 3 months".
*/
data class SuggestionSnoozeRef(
val mbid: String,
val name: String,
val snoozedUntil: String,
) {
/**
* Relative return phrase for the manage list. Relative rather than a
* calendar date because the exact day a 90-day snooze lapses is noise the
* user never asked for.
*
* [nowMs] is injectable so this is testable without freezing the clock.
* Returns "shortly" for an unparseable or already-past timestamp: the row
* is on screen, so the server still considers it snoozed, and guessing is
* better than rendering an empty line.
*/
fun returnsIn(nowMs: Long = System.currentTimeMillis()): String {
val remainingMs = runCatching { Instant.parse(snoozedUntil).toEpochMilliseconds() }
.getOrNull()?.minus(nowMs)
// Two ways to have nothing to state: an unparseable timestamp, or one
// already lapsed by our clock though the server still returned the row
// (the two disagree). Neither is "today", which would read as a real
// prediction.
if (remainingMs == null || remainingMs <= 0) return "shortly"
val days = (remainingMs.toDouble() / MILLIS_PER_DAY).roundToInt()
return when {
days < 1 -> "today"
days == 1 -> "tomorrow"
days < DAYS_BEFORE_MONTHS -> "in $days days"
else -> {
val months = (days.toDouble() / DAYS_PER_MONTH).roundToInt()
if (months == 1) "in about a month" else "in about $months months"
}
}
}
private companion object {
const val MILLIS_PER_DAY = 86_400_000.0
// Below this, days read more naturally than a rounded month count.
//
// Must be <= DAYS_PER_MONTH, or the singular "in about a month" is
// unreachable: a rounded month count of 1 needs 15..44 days, and any
// threshold above 30 sends all of those down the days branch instead.
// This was 45 and the singular branch was dead code — the unit test
// for it is what surfaced that.
const val DAYS_BEFORE_MONTHS = 30
const val DAYS_PER_MONTH = 30.0
}
}
@@ -26,10 +26,11 @@ data class PlaylistRef(
/**
* Whether the "Regenerate" affordance applies: every system playlist
* EXCEPT songs_like_artist (the server's songs-like family exposes no
* refresh trigger; rebuilds are scheduler-driven).
* EXCEPT the kinds with several playlists per user (songs_like_artist,
* genre_mix), which the server can't address by kind; those rebuild on
* the daily schedule and play by playlist id.
*/
val refreshable: Boolean get() = isSystem && systemVariant != "songs_like_artist"
val refreshable: Boolean get() = isSystem && systemVariant !in PER_PLAYLIST_SYSTEM_VARIANTS
/**
* Can't be relied on while offline — either it needs the live server to
@@ -39,6 +40,9 @@ data class PlaylistRef(
val unavailableOffline: Boolean get() = refreshable || !fullyCached
}
/** System kinds with several playlists per user, played by playlist id. */
private val PER_PLAYLIST_SYSTEM_VARIANTS = setOf("songs_like_artist", "genre_mix")
/**
* One row of a playlist's tracks.
*
@@ -1,64 +0,0 @@
package com.fabledsword.minstrel.models
/**
* Status of a request. Stored on the wire as a plain string;
* the typed enum keeps switch / when blocks exhaustive and lets the
* UI map directly to a status pill color without raw-string matches.
*/
enum class RequestStatus {
PENDING, APPROVED, REJECTED, COMPLETED, FAILED, UNKNOWN;
companion object {
fun fromWire(s: String): RequestStatus = when (s) {
"pending" -> PENDING
"approved" -> APPROVED
"rejected" -> REJECTED
"completed" -> COMPLETED
"failed" -> FAILED
else -> UNKNOWN
}
}
val wire: String get() = name.lowercase()
}
/**
* One request the user has submitted, shared between the user-side
* `/api/requests` view and the admin cross-user view since the wire
* shape is identical.
*
* `displayName` picks the right field based on kind:
* - album → albumTitle (fallback artistName)
* - track → trackTitle (fallback artistName)
* - artist → artistName
*
* `listenHrefId` returns the most-specific matched library ID once the
* request completes (track → album → artist) so the "Listen" CTA can
* navigate to the right detail screen. Returns null until the
* server's ingest job populates the matched_* fields.
*/
data class RequestRef(
val id: String,
val userId: String,
val username: String = "",
val status: RequestStatus,
val kind: String,
val artistName: String,
val albumTitle: String? = null,
val trackTitle: String? = null,
val requestedAt: String,
val decidedAt: String? = null,
val notes: String? = null,
val importedAlbumCount: Int = 0,
val importedTrackCount: Int = 0,
val matchedTrackId: String? = null,
val matchedAlbumId: String? = null,
val matchedArtistId: String? = null,
) {
val displayName: String
get() = when (kind) {
"album" -> albumTitle ?: artistName
"track" -> trackTitle ?: artistName
else -> artistName
}
}
@@ -6,8 +6,8 @@ import kotlinx.serialization.Serializable
/**
* One admin-side user row. Mirrors `adminUserView` from
* `internal/api/admin_users.go`. Distinct from the user-scoped /me
* profile shape because admin endpoints expose `auto_approve_requests`
* and the canonical `created_at`.
* profile shape because admin endpoints expose the canonical
* `created_at`.
*/
@Serializable
data class AdminUserWire(
@@ -15,7 +15,6 @@ data class AdminUserWire(
val username: String = "",
@SerialName("display_name") val displayName: String? = null,
@SerialName("is_admin") val isAdmin: Boolean = false,
@SerialName("auto_approve_requests") val autoApproveRequests: Boolean = false,
@SerialName("created_at") val createdAt: String = "",
)
@@ -1,100 +0,0 @@
package com.fabledsword.minstrel.models.wire
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* One row of `GET /api/catalogue/search` (the MusicBrainz search). Mirrors
* `web/src/lib/api/types.ts` CatalogueSearchResult. `imageUrl` is the
* server's own art endpoint, relative, so it goes through ServerImage.
*
* `inLibrary` and `requested` let the UI greyout rows the user can't
* act on (already imported / already awaiting review). All defaults
* empty so missing keys don't throw on decode.
*/
@Serializable
data class CatalogueSearchResultWire(
val mbid: String = "",
val name: String = "",
@SerialName("secondary_text") val secondaryText: String = "",
@SerialName("image_url") val imageUrl: String = "",
@SerialName("artist_mbid") val artistMbid: String = "",
@SerialName("album_mbid") val albumMbid: String = "",
@SerialName("in_library") val inLibrary: Boolean = false,
val requested: Boolean = false,
)
/**
* `GET /api/discover/suggestions` row — an out-of-library artist
* surfaced from ListenBrainz-derived seeds. `imageUrl` may be empty.
*/
@Serializable
data class ArtistSuggestionWire(
val mbid: String = "",
val name: String = "",
@SerialName("image_url") val imageUrl: String = "",
val attribution: List<SeedContributionWire> = emptyList(),
/**
* Tags this candidate shares with the user's taste profile, strongest
* first (max 3). Absent for most candidates — tag coverage for
* out-of-library artists is partial by nature — so the default
* empty list is the common case, not an error.
*/
@SerialName("matched_tags") val matchedTags: List<String> = emptyList(),
)
/**
* Per-seed attribution for an ArtistSuggestion — "because you liked X"
* / "because you played Y". `isLiked = true` means the seed came from
* the user's likes; false means a played-but-not-liked play.
*/
@Serializable
data class SeedContributionWire(
val name: String = "",
@SerialName("is_liked") val isLiked: Boolean = false,
)
/**
* One row of `GET /api/discover/snoozes` — a suggestion the user parked
* with "not right now". The server only returns rows that are still in
* effect, so the client never compares [snoozedUntil] against the clock to
* decide whether to show it; it reads it only to say when the artist comes
* back.
*/
@Serializable
data class SuggestionSnoozeWire(
val mbid: String = "",
val name: String = "",
@SerialName("snoozed_until") val snoozedUntil: String = "",
@SerialName("created_at") val createdAt: String = "",
)
/**
* Body for `POST /api/discover/suggestions/{mbid}/snooze`.
*
* [name] is required by the server, not decorative: suggestions are
* out-of-library, so there is no artists row to resolve a display name from
* and the snooze list would have nothing to render. Omitting it is a 400.
*
* No `days` field. The duration is the server's to own (90 days); pinning it
* client-side would freeze the default at whatever this build shipped.
*/
@Serializable
data class SnoozeSuggestionBody(
val name: String,
)
/**
* Body posted to `POST /api/requests`. Optional fields are emitted only
* when non-null server-side; matching that here keeps the wire identical.
*/
@Serializable
data class CreateRequestBody(
val kind: String,
@SerialName("artist_mbid") val artistMbid: String,
@SerialName("artist_name") val artistName: String,
@SerialName("album_mbid") val albumMbid: String? = null,
@SerialName("album_title") val albumTitle: String? = null,
@SerialName("track_mbid") val trackMbid: String? = null,
@SerialName("track_title") val trackTitle: String? = null,
)
@@ -1,37 +0,0 @@
package com.fabledsword.minstrel.models.wire
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* Wire shape of `requestView` from `internal/api/requests.go` — the
* row returned by both `GET /api/requests` (caller's own requests) and
* `GET /api/admin/requests` (cross-user admin view).
*
* Status values: `pending` / `approved` / `rejected` / `completed` /
* `failed`. Kind values: `artist` / `album` / `track`.
*
* `matched_*_id` are set after a completed request ingests into the
* local library; the user-side "Listen" affordance picks the most
* specific one (track → album → artist).
*/
@Serializable
data class RequestWire(
val id: String,
@SerialName("user_id") val userId: String = "",
// The requester's username. Only `GET /api/admin/requests` sends it.
val username: String = "",
val status: String = "pending",
val kind: String = "artist",
@SerialName("artist_name") val artistName: String = "",
@SerialName("album_title") val albumTitle: String? = null,
@SerialName("track_title") val trackTitle: String? = null,
@SerialName("requested_at") val requestedAt: String = "",
@SerialName("decided_at") val decidedAt: String? = null,
val notes: String? = null,
@SerialName("imported_album_count") val importedAlbumCount: Int = 0,
@SerialName("imported_track_count") val importedTrackCount: Int = 0,
@SerialName("matched_track_id") val matchedTrackId: String? = null,
@SerialName("matched_album_id") val matchedAlbumId: String? = null,
@SerialName("matched_artist_id") val matchedArtistId: String? = null,
)
@@ -15,12 +15,10 @@ import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.fabledsword.minstrel.admin.ui.AdminLandingScreen
import com.fabledsword.minstrel.admin.ui.AdminQuarantineScreen
import com.fabledsword.minstrel.admin.ui.AdminRequestsScreen
import com.fabledsword.minstrel.admin.ui.AdminTagSourcesScreen
import com.fabledsword.minstrel.admin.ui.AdminUsersScreen
import com.fabledsword.minstrel.auth.ui.LoginScreen
import com.fabledsword.minstrel.auth.ui.ServerUrlScreen
import com.fabledsword.minstrel.discover.ui.DiscoverScreen
import com.fabledsword.minstrel.home.ui.HomeScreen
import com.fabledsword.minstrel.library.ui.AlbumDetailScreen
import com.fabledsword.minstrel.library.ui.ArtistDetailScreen
@@ -31,7 +29,6 @@ import com.fabledsword.minstrel.player.ui.NowPlayingScreen
import com.fabledsword.minstrel.player.ui.QueueScreen
import com.fabledsword.minstrel.playlists.ui.PlaylistDetailScreen
import com.fabledsword.minstrel.playlists.ui.PlaylistsListScreen
import com.fabledsword.minstrel.requests.ui.RequestsScreen
import com.fabledsword.minstrel.search.ui.SearchScreen
import com.fabledsword.minstrel.settings.ui.SettingsScreen
import com.fabledsword.minstrel.shared.widgets.ShellScaffold
@@ -92,13 +89,6 @@ private fun NavGraphBuilder.inShellTopLevel(
}
}
}
composable<Discover> {
WithAnimatedScope {
ShellScaffold(onExpandPlayer = expandPlayer) {
DiscoverScreen(navController = navController)
}
}
}
composable<Playlists> {
WithAnimatedScope {
ShellScaffold(onExpandPlayer = expandPlayer) {
@@ -120,13 +110,6 @@ private fun NavGraphBuilder.inShellTopLevel(
}
}
}
composable<Requests> {
WithAnimatedScope {
ShellScaffold(onExpandPlayer = expandPlayer) {
RequestsScreen(navController = navController)
}
}
}
}
/**
@@ -172,13 +155,6 @@ private fun NavGraphBuilder.inShellDetail(
}
}
}
composable<AdminRequests> {
WithAnimatedScope {
ShellScaffold(onExpandPlayer = expandPlayer) {
AdminRequestsScreen(navController = navController)
}
}
}
composable<AdminQuarantine> {
WithAnimatedScope {
ShellScaffold(onExpandPlayer = expandPlayer) {
@@ -8,11 +8,9 @@ import kotlinx.serialization.Serializable
@Serializable data object Home
@Serializable data object Library
@Serializable data object Search
@Serializable data object Discover
@Serializable data object Playlists
@Serializable data object Settings
@Serializable data object Admin
@Serializable data object Requests
@Serializable data object Notifications
@Serializable data object NotificationSettings
@@ -21,7 +19,6 @@ import kotlinx.serialization.Serializable
@Serializable data class AlbumDetail(val id: String)
@Serializable data class ArtistDetail(val id: String)
@Serializable data class PlaylistDetail(val id: String)
@Serializable data object AdminRequests
@Serializable data object AdminQuarantine
@Serializable data object AdminUsers
@Serializable data object AdminTagSources
@@ -76,7 +76,7 @@ internal fun announcementFor(fresh: List<CachedNotificationEntity>): Announcemen
channel = if (fresh.all { shadeChannelFor(it.kind) == ShadeChannel.LIBRARY_HEALTH }) {
ShadeChannel.LIBRARY_HEALTH
} else {
ShadeChannel.YOUR_REQUESTS
ShadeChannel.NEW_MUSIC
},
lines = fresh.sortedByDescending { it.createdAt }.take(PILE_LINES).map { it.title },
)
@@ -94,15 +94,18 @@ internal fun phoneOnFor(settings: NotificationSettingsWire?): (String) -> Boolea
* user's system-level choice for it.
*/
internal enum class ShadeChannel(val id: String, val title: String, val description: String) {
YOUR_REQUESTS("your_requests", "Your requests", "Approved, declined, and new music arriving"),
LIBRARY_HEALTH("library_health", "Library health", "For admins: requests to review and library problems"),
NEW_MUSIC("new_music", "New music", "Albums arriving in the library"),
LIBRARY_HEALTH("library_health", "Library health", "For admins: flagged tracks and library problems"),
}
private val requesterKinds = setOf("request_approved", "request_rejected", "request_completed")
/** Channel ids the app does not post to; deleted at startup so system settings lists only live ones. */
internal val retiredShadeChannelIds = listOf("your_requests")
private val listenerKinds = setOf("new_music")
/** Everything a listener can receive is theirs; the rest is admin work. */
internal fun shadeChannelFor(kind: String): ShadeChannel =
if (kind in requesterKinds) ShadeChannel.YOUR_REQUESTS else ShadeChannel.LIBRARY_HEALTH
if (kind in listenerKinds) ShadeChannel.NEW_MUSIC else ShadeChannel.LIBRARY_HEALTH
/** The delivery service runs exactly while signed in with background delivery on. */
internal fun deliveryWanted(signedIn: Boolean, enabled: Boolean): Boolean = signedIn && enabled
@@ -79,6 +79,7 @@ class NotificationPoster @Inject constructor(
private fun ensureChannels() {
val manager = context.getSystemService(NotificationManager::class.java) ?: return
retiredShadeChannelIds.forEach { manager.deleteNotificationChannel(it) }
ShadeChannel.entries.forEach { c ->
manager.createNotificationChannel(
NotificationChannel(c.id, c.title, NotificationManager.IMPORTANCE_DEFAULT)
@@ -2,14 +2,14 @@ package com.fabledsword.minstrel.notifications.ui
import com.fabledsword.minstrel.nav.Admin
import com.fabledsword.minstrel.nav.AdminQuarantine
import com.fabledsword.minstrel.nav.AdminRequests
import com.fabledsword.minstrel.nav.AlbumDetail
import com.fabledsword.minstrel.nav.ArtistDetail
import com.fabledsword.minstrel.nav.Requests
import com.fabledsword.minstrel.nav.Home
/**
* The app screen for a notice's link. The server writes web paths, the same
* for every client; this maps them onto the app's routes. The library's
* for every client; this maps them onto the app's routes. "/" is Home,
* where several new albums at once are found under Recently added. The library's
* health pages sit under Collection on the web: Reports opens the
* app's report screen, and the ones the app has no screen for (duplicates,
* suspect sources, missing files) open the Admin landing, as do other Admin
@@ -20,10 +20,10 @@ private val ADMIN_COLLECTION_PAGES = setOf("duplicates", "suspect-sources", "mis
internal fun routeForLink(link: String): Any? {
val parts = link.substringBefore('?').trim('/').split('/').filter { it.isNotEmpty() }
return when {
link.isBlank() -> null
parts.isEmpty() -> Home
parts.size == 2 && parts[0] == "albums" -> AlbumDetail(parts[1])
parts.size == 2 && parts[0] == "artists" -> ArtistDetail(parts[1])
parts == listOf("requests") -> Requests
parts == listOf("admin", "requests") -> AdminRequests
parts == listOf("collection", "reports") -> AdminQuarantine
parts.firstOrNull() == "collection" && parts.getOrNull(1) in ADMIN_COLLECTION_PAGES -> Admin
parts.firstOrNull() == "admin" -> Admin
@@ -9,23 +9,17 @@ import android.os.Build
import android.provider.Settings
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
@@ -35,7 +29,6 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
@@ -45,8 +38,6 @@ import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import com.composables.icons.lucide.ChevronRight
import com.composables.icons.lucide.Lucide
import com.fabledsword.minstrel.api.endpoints.NotificationKindSettingWire
import com.fabledsword.minstrel.api.endpoints.NotificationSettingsWire
import com.fabledsword.minstrel.nav.NotificationSettings
@@ -54,13 +45,19 @@ import com.fabledsword.minstrel.notifications.data.NotificationChannel
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.theme.Muted
import com.fabledsword.minstrel.theme.RowChevron
import com.fabledsword.minstrel.theme.Section
import com.fabledsword.minstrel.theme.SectionEdge
import com.fabledsword.minstrel.theme.SectionGap
import com.fabledsword.minstrel.theme.SettingRow
import com.fabledsword.minstrel.theme.SwitchRow
private val CELL_WIDTH = 56.dp
private val CELL_WIDTH = 48.dp
/**
* Per-user notification settings: a row per kind with a box for each
* channel. Rows read as a menu; anything that needs explaining
* is one short line.
* Per-user notification settings: what this device does, then a row per
* kind with a box for each channel.
*/
@Composable
fun NotificationSettingsScreen(
@@ -109,29 +106,28 @@ private fun SettingsBody(
modifier = modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(vertical = 8.dp),
.padding(horizontal = SectionEdge, vertical = SectionEdge),
verticalArrangement = Arrangement.spacedBy(SectionGap),
) {
deviceRows()
HeaderRow()
Section("This device") { deviceRows() }
Section("New music", trailing = { ChannelHeaders() }) {
settings.kinds.filter { !it.adminOnly }.forEach { KindRow(it, settings.emailAvailable, onSet) }
val adminKinds = settings.kinds.filter { it.adminOnly }
if (adminKinds.isNotEmpty()) {
SectionLabel("Library health")
adminKinds.forEach { KindRow(it, settings.emailAvailable, onSet) }
}
if (!settings.emailAvailable) {
Muted(emailUnavailableLine(settings.emailUnavailableReason, isAdmin))
}
}
val adminKinds = settings.kinds.filter { it.adminOnly }
if (adminKinds.isNotEmpty()) {
Section("Library health", trailing = { ChannelHeaders() }) {
adminKinds.forEach { KindRow(it, settings.emailAvailable, onSet) }
}
}
}
}
/** The channel names over the boxes, in the section's title line. */
@Composable
private fun HeaderRow() {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(Modifier.weight(1f))
private fun ChannelHeaders() {
NotificationChannel.entries.forEach { c ->
Text(
text = channelLabel(c),
@@ -141,7 +137,6 @@ private fun HeaderRow() {
textAlign = TextAlign.Center,
)
}
}
}
@Composable
@@ -151,11 +146,7 @@ private fun KindRow(
onSet: (String, NotificationChannel, Boolean) -> Unit,
) {
val label = kindLabel(row.kind)
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(label, modifier = Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge)
SettingRow(title = label) {
NotificationChannel.entries.forEach { c ->
val enabled = channelEnabled(row, c, emailAvailable)
Box(Modifier.width(CELL_WIDTH), contentAlignment = Alignment.Center) {
@@ -204,60 +195,24 @@ private fun DeviceRows(backgroundDelivery: Boolean, onBackgroundDelivery: (Boole
@Composable
private fun BackgroundDeliveryRow(checked: Boolean, onChange: (Boolean) -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.toggleable(value = checked, role = Role.Switch, onValueChange = onChange)
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Column(Modifier.weight(1f)) {
Text("Notifications when the app is closed", style = MaterialTheme.typography.bodyLarge)
// The ongoing notice is the price of not using Google's push;
// said plainly rather than left to be discovered.
Muted("Keeps a quiet notice in the shade, in place of Google's push", padded = false)
}
Switch(checked = checked, onCheckedChange = null)
}
// The ongoing notice is the price of not using Google's push; said
// plainly rather than left to be discovered.
SwitchRow(
title = "Notifications when the app is closed",
summary = "Keeps a quiet notice in the shade, in place of Google's push",
checked = checked,
onCheckedChange = onChange,
)
}
@Composable
private fun PhoneBlockedRow(onClick: () -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Column(Modifier.weight(1f)) {
Text("Phone alerts are off", style = MaterialTheme.typography.bodyLarge)
Muted("Allow notifications for Minstrel in system settings", padded = false)
}
Icon(Lucide.ChevronRight, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
@Composable
private fun SectionLabel(text: String) {
Text(
text = text,
modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 4.dp),
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
@Composable
private fun Muted(text: String, padded: Boolean = true) {
Text(
text = text,
modifier = if (padded) Modifier.padding(horizontal = 16.dp, vertical = 12.dp) else Modifier,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
SettingRow(
title = "Phone alerts are off",
summary = "Allow notifications for Minstrel in system settings",
tone = MaterialTheme.colorScheme.error,
onClick = onClick,
) { RowChevron() }
}
private fun openAppNotificationSettings(context: Context) {
@@ -293,10 +248,7 @@ internal fun channelLabel(c: NotificationChannel): String = when (c) {
/** Short row labels, the same as the web's. Unknown kinds show their key. */
internal fun kindLabel(kind: String): String = when (kind) {
"request_approved" -> "Request approved"
"request_rejected" -> "Request declined"
"request_completed" -> "New music arrived"
"request_pending" -> "Requests to review"
"new_music" -> "New music arrived"
"quarantine_flagged" -> "Tracks flagged"
"scan_failed" -> "Library scan failed"
"tracks_missing" -> "Tracks gone missing"
@@ -80,7 +80,7 @@ fun NotificationsScreen(
list == null -> LoadingCentered()
list.isEmpty() -> EmptyState(
title = "Nothing waiting for you",
body = "Requests, new music and anything needing a look will gather here.",
body = "Library problems and anything needing a look will gather here.",
icon = Lucide.Bell,
)
else -> LazyColumn(modifier = Modifier.fillMaxSize()) {
@@ -171,6 +171,7 @@ private fun systemLabelFor(variant: String?): String = when (variant) {
"new_for_you" -> "New for you"
"on_this_day" -> "On this day"
"first_listens" -> "First listens"
"genre_mix" -> "Genre mix"
null -> ""
else -> variant.replace('_', ' ').replaceFirstChar { it.uppercase() }
}
@@ -1,73 +0,0 @@
package com.fabledsword.minstrel.requests.data
import com.fabledsword.minstrel.api.endpoints.RequestsApi
import com.fabledsword.minstrel.cache.mutations.MutationQueue
import com.fabledsword.minstrel.models.RequestRef
import com.fabledsword.minstrel.models.RequestStatus
import com.fabledsword.minstrel.models.wire.RequestWire
import retrofit2.Retrofit
import retrofit2.create
import java.io.IOException
import javax.inject.Inject
import javax.inject.Singleton
/**
* Outcome of a [RequestsRepository.cancel] call. Mirrors the
* [com.fabledsword.minstrel.likes.data.UnflagOutcome] / etc. shape.
*/
enum class CancelOutcome { Synced, Queued }
/**
* Read-through accessor for the caller's own requests +
* cancel-while-pending write. No Room caching. Cancel is offline-first:
* direct REST on the happy
* path, MutationQueue fallback on transport failure so the user's
* intent persists across connectivity loss.
*/
@Singleton
class RequestsRepository @Inject constructor(
private val mutationQueue: MutationQueue,
retrofit: Retrofit,
) {
private val api: RequestsApi = retrofit.create()
suspend fun listMine(): List<RequestRef> =
api.listMine().map { it.toDomain() }
/**
* Cancels a pending request. On 2xx, returns the canonical
* cancelled row from the server (status=rejected). On transport
* failure, enqueues a REQUEST_CANCEL mutation for later replay
* and returns null — the caller's optimistic UI removal already
* reflects the user's intent, and the next listMine() refetch
* (post-replay) will surface the canonical row.
*/
suspend fun cancel(id: String): Pair<CancelOutcome, RequestRef?> = try {
CancelOutcome.Synced to api.cancel(id).toDomain()
} catch (
@Suppress("SwallowedException") _: IOException,
) {
mutationQueue.enqueueRequestCancel(id)
CancelOutcome.Queued to null
}
}
// ── Mappers (internal — wire stays out of UI) ──
private fun RequestWire.toDomain(): RequestRef = RequestRef(
id = id,
userId = userId,
status = RequestStatus.fromWire(status),
kind = kind,
artistName = artistName,
albumTitle = albumTitle,
trackTitle = trackTitle,
requestedAt = requestedAt,
decidedAt = decidedAt,
notes = notes,
importedAlbumCount = importedAlbumCount,
importedTrackCount = importedTrackCount,
matchedTrackId = matchedTrackId,
matchedAlbumId = matchedAlbumId,
matchedArtistId = matchedArtistId,
)
@@ -1,313 +0,0 @@
@file:Suppress("TooManyFunctions") // Compose screen + private helper composables
package com.fabledsword.minstrel.requests.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.layout.size
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.AssistChip
import androidx.compose.material3.Button
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import com.composables.icons.lucide.Disc3
import com.composables.icons.lucide.LibraryBig
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Music
import com.composables.icons.lucide.Play
import com.composables.icons.lucide.X
import com.fabledsword.minstrel.models.RequestRef
import com.fabledsword.minstrel.models.RequestStatus
import com.fabledsword.minstrel.nav.AlbumDetail
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.nav.ArtistDetail
import com.fabledsword.minstrel.nav.Requests
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
@Composable
fun RequestsScreen(
navController: NavHostController,
viewModel: RequestsViewModel = hiltViewModel(),
) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
Scaffold(
contentWindowInsets = ShellContentWindowInsets,
modifier = Modifier.fillMaxSize(),
topBar = {
MinstrelTopAppBar(
title = "Your requests",
navController = navController,
currentRouteName = Requests::class.qualifiedName,
onBack = { navController.popBackStack() },
)
},
) { inner ->
PullToRefreshScaffold(
onRefresh = { viewModel.refresh().join() },
modifier = Modifier.fillMaxSize().padding(inner),
) {
when (val s = state) {
UiState.Loading -> LoadingCentered()
UiState.Empty -> EmptyState(
title = "Nothing requested yet",
body = "Use Discover to ask for new music; your " +
"requests show up here.",
)
is UiState.Error -> ErrorRetry(
title = "Couldn't load requests",
message = s.message,
onRetry = { viewModel.refresh() },
)
is UiState.Success -> RequestList(
rows = s.data,
onCancel = viewModel::cancel,
onListen = { id -> navController.navigate(id) },
)
}
}
}
}
@Composable
private fun RequestList(
rows: List<RequestRef>,
onCancel: (String) -> Unit,
onListen: (Any) -> Unit,
) {
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(items = rows, key = { it.id }) { req ->
RequestRow(
req = req,
onCancel = { onCancel(req.id) },
onListen = req.listenRoute()?.let { route -> { onListen(route) } },
)
HorizontalDivider()
}
}
}
@Composable
private fun RequestRow(
req: RequestRef,
onCancel: () -> Unit,
onListen: (() -> Unit)?,
) {
var showCancelConfirm by remember { mutableStateOf(false) }
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
KindAvatar(kind = req.kind)
RequestRowBody(req = req, modifier = Modifier.weight(1f))
RequestRowAction(
req = req,
onListen = onListen,
onAskCancel = { showCancelConfirm = true },
)
}
if (showCancelConfirm) {
CancelConfirmDialog(
displayName = req.displayName,
onConfirm = {
showCancelConfirm = false
onCancel()
},
onDismiss = { showCancelConfirm = false },
)
}
}
@Composable
private fun RequestRowBody(req: RequestRef, modifier: Modifier = Modifier) {
Column(modifier = modifier) {
Text(
text = req.displayName,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Row(
modifier = Modifier.padding(top = 4.dp),
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
StatusPill(status = req.status)
KindPill(label = req.kind)
}
val progress = req.ingestProgressText()
if (progress != null) {
Text(
text = progress,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 4.dp),
)
}
if (req.status == RequestStatus.REJECTED && !req.notes.isNullOrEmpty()) {
Text(
text = req.notes,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 4.dp),
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
}
}
@Composable
private fun RequestRowAction(
req: RequestRef,
onListen: (() -> Unit)?,
onAskCancel: () -> Unit,
) {
when {
onListen != null -> OutlinedButton(onClick = onListen) {
Icon(
Lucide.Play,
contentDescription = null,
modifier = Modifier.size(16.dp).padding(end = 4.dp),
)
Text("Listen")
}
req.status == RequestStatus.PENDING -> TextButton(onClick = onAskCancel) {
Icon(Lucide.X, contentDescription = null, modifier = Modifier.padding(end = 4.dp))
Text("Cancel")
}
}
}
@Composable
private fun CancelConfirmDialog(
displayName: String,
onConfirm: () -> Unit,
onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Cancel request?") },
text = { Text("Cancel “$displayName”? Your request is withdrawn.") },
confirmButton = {
Button(onClick = onConfirm) { Text("Cancel request") }
},
dismissButton = {
TextButton(onClick = onDismiss) { Text("Keep") }
},
)
}
@Composable
private fun KindAvatar(kind: String) {
// Icons: disc-3 for artist, library-big for album, music for track.
val icon = when (kind) {
"artist" -> Lucide.Disc3
"album" -> Lucide.LibraryBig
"track" -> Lucide.Music
else -> Lucide.Music
}
Icon(
imageVector = icon,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(28.dp),
)
}
/**
* Most-specific listenable detail-screen route for a completed
* request, or null when nothing's been matched / the status isn't
* completed. Track-level matches resolve to AlbumDetail since the
* client has no TrackDetail screen.
*/
private fun RequestRef.listenRoute(): Any? = when {
status != RequestStatus.COMPLETED -> null
!matchedAlbumId.isNullOrEmpty() -> AlbumDetail(matchedAlbumId)
!matchedArtistId.isNullOrEmpty() -> ArtistDetail(matchedArtistId)
else -> null
}
/**
* "2 albums · 14 tracks ingested" — null when both counts are zero.
* Singular when the count is 1 ("1 album · 1 track ingested").
*/
private fun RequestRef.ingestProgressText(): String? {
if (importedAlbumCount == 0 && importedTrackCount == 0) return null
val parts = buildList {
if (importedAlbumCount > 0) {
add(
"$importedAlbumCount ${if (importedAlbumCount == 1) "album" else "albums"}",
)
}
if (importedTrackCount > 0) {
add(
"$importedTrackCount ${if (importedTrackCount == 1) "track" else "tracks"}",
)
}
}
return "${parts.joinToString(" · ")} ingested"
}
@Composable
private fun StatusPill(status: RequestStatus) {
val (label, isError) = when (status) {
RequestStatus.PENDING -> "pending" to false
RequestStatus.APPROVED -> "approved" to false
RequestStatus.COMPLETED -> "completed" to false
RequestStatus.REJECTED -> "rejected" to true
RequestStatus.FAILED -> "failed" to true
RequestStatus.UNKNOWN -> "unknown" to false
}
val color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary
AssistChip(
onClick = {},
enabled = false,
label = { Text(label, color = color) },
)
}
@Composable
private fun KindPill(label: String) {
AssistChip(
onClick = {},
enabled = false,
label = {
Text(
label,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
},
)
}
@@ -1,177 +0,0 @@
package com.fabledsword.minstrel.requests.ui
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fabledsword.minstrel.api.ErrorCopy
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.recoveries
import com.fabledsword.minstrel.events.EventsStream
import com.fabledsword.minstrel.models.RequestRef
import com.fabledsword.minstrel.models.RequestStatus
import com.fabledsword.minstrel.requests.data.CancelOutcome
import com.fabledsword.minstrel.requests.data.RequestsRepository
import com.fabledsword.minstrel.shared.UiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
private val RELEVANT_EVENT_KINDS = setOf("request.status_changed")
// Cadence for in-flight request polling — matches the web client:
// fast enough to feel live, slow enough not to hammer the server.
private const val POLL_INTERVAL_MS = 12_000L
@HiltViewModel
class RequestsViewModel @Inject constructor(
private val repository: RequestsRepository,
private val eventsStream: EventsStream,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow<UiState<List<RequestRef>>>(UiState.Loading)
val uiState: StateFlow<UiState<List<RequestRef>>> = internal.asStateFlow()
init {
refresh()
// SSE push: reconciler completions arrive here; reload silently so the
// row updates in place rather than flashing the loading spinner.
viewModelScope.launch {
eventsStream.events
.filter { it.kind in RELEVANT_EVENT_KINDS }
.collect { silentReload() }
}
viewModelScope.launch { pollWhileInFlight() }
// Screen-level auto-recovery: a load that failed while
// the server was unreachable heals the moment health returns, without
// waiting for the next poll tick.
viewModelScope.launch {
networkStatus.recoveries().collect {
if (internal.value is UiState.Error) silentReload()
}
}
}
fun refresh(): Job = viewModelScope.launch {
internal.value = UiState.Loading
try {
val rows = repository.listMine()
internal.value = if (rows.isEmpty()) {
UiState.Empty
} else {
UiState.Success(rows)
}
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = UiState.Error(ErrorCopy.fromThrowable(e))
}
}
/**
* Auto-poll while any request is mid-ingest (status APPROVED), matching the
* web client. Reloads silently every [POLL_INTERVAL_MS] and pauses
* when nothing is in-flight — complements the SSE push so progress stays
* live even if the event stream drops.
*/
private suspend fun pollWhileInFlight() {
while (true) {
// Also retry from a failed load: from UiState.Error
// the in-flight predicate can never become true, so without this
// the poll never self-heals the screen — e.g. after a transient
// 500 that health monitoring (transport-level) never saw.
if (hasInFlightRequest() || internal.value is UiState.Error) {
silentReload()
}
delay(POLL_INTERVAL_MS)
}
}
private fun hasInFlightRequest(): Boolean {
val state = internal.value
return state is UiState.Success &&
state.data.any { it.status == RequestStatus.APPROVED }
}
/**
* Reload the list in place without flipping to Loading — used by the poll
* loop and the SSE collector so visible rows update without a spinner
* flash. A transient failure keeps the current view; the next reload wins.
*/
private suspend fun silentReload() {
try {
val rows = repository.listMine()
internal.value = if (rows.isEmpty()) UiState.Empty else UiState.Success(rows)
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
// Keep the current view; the next poll / SSE / pull reconciles.
}
}
/**
* Optimistically removes [id] from the success list so the row
* disappears immediately; on server-side success the row is
* replaced by the canonical cancelled state from the return value.
* On error rolls back by refetching the list.
*/
fun cancel(id: String) {
val before = internal.value
if (before is UiState.Success) {
val filtered = before.data.filterNot { it.id == id }
internal.value = if (filtered.isEmpty()) {
UiState.Empty
} else {
UiState.Success(filtered)
}
}
viewModelScope.launch {
try {
val (outcome, updated) = repository.cancel(id)
if (updated != null) {
internal.update { state ->
if (state !is UiState.Success) {
// Mid-refresh — let the refresh result win, but
// splice the cancelled row in so it shows the new
// status if the user re-pulls.
UiState.Success(listOf(updated))
} else {
// Re-insert the cancelled row in its old position
// would require remembering the prior ordering;
// simpler to refetch in the background.
state
}
}
}
// Only refetch on the Synced outcome. The
// Queued path is offline by definition — the optimistic
// removal at the top of cancel() is correct, and a
// refresh() call here would either (a) get the
// not-yet-delivered cancelled row back from the server
// and snap it into the list (confusing), or (b) fail
// with a transport error and flip the whole screen to
// UiState.Error, making the user think the cancel
// failed. The mutation queue will replay the cancel
// when connectivity returns; the next on-screen refresh
// (pull-to-refresh, navigation back) reconciles.
if (outcome == CancelOutcome.Synced) {
refresh()
}
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
// Roll back by re-fetching; the failed cancel might
// already be visible to the server (eventual consistency)
// or not at all (transport drop). The refetch makes
// local state match either outcome.
refresh()
}
}
}
}
@@ -1,20 +1,14 @@
package com.fabledsword.minstrel.settings.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
@@ -25,28 +19,14 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fabledsword.minstrel.models.ListenBrainzStatus
import com.fabledsword.minstrel.theme.Muted
import com.fabledsword.minstrel.theme.Section
import com.fabledsword.minstrel.theme.SwitchRow
@Composable
fun ListenBrainzCard(viewModel: ListenBrainzViewModel = hiltViewModel()) {
val state by viewModel.state.collectAsStateWithLifecycle()
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
text = "ListenBrainz",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
)
Text(
text = "Send your plays to ListenBrainz so you can keep your " +
"scrobble history portable. Get a token at " +
"listenbrainz.org/profile — it's stored encrypted on " +
"the server and never read back.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Section("ListenBrainz") {
if (state.isLoading) {
Box(
modifier = Modifier.fillMaxWidth().padding(16.dp),
@@ -64,7 +44,6 @@ fun ListenBrainzCard(viewModel: ListenBrainzViewModel = hiltViewModel()) {
)
}
}
}
}
@Composable
@@ -77,25 +56,25 @@ private fun ListenBrainzForm(
onSaveToken: () -> Unit,
onSetEnabled: (Boolean) -> Unit,
) {
TokenField(
tokenInput = tokenInput,
tokenSet = status?.tokenSet == true,
onChange = onTokenChange,
val tokenSet = status?.tokenSet == true
SwitchRow(
title = "Send my plays to ListenBrainz",
summary = when {
!tokenSet -> "Save a token first"
status?.lastScrobbledAt != null -> "Last scrobble: ${status.lastScrobbledAt}"
else -> null
},
checked = status?.enabled == true,
onCheckedChange = onSetEnabled,
enabled = !isSaving && tokenSet,
)
Spacer(Modifier.height(4.dp))
TokenField(tokenInput = tokenInput, tokenSet = tokenSet, onChange = onTokenChange)
SaveTokenButton(
isSaving = isSaving,
enabled = !isSaving && tokenInput.isNotBlank(),
onClick = onSaveToken,
)
EnabledRow(status = status, isSaving = isSaving, onSetEnabled = onSetEnabled)
if (message != null) {
Text(
text = message,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (message != null) Muted(message)
}
@Composable
@@ -105,6 +84,7 @@ private fun TokenField(tokenInput: String, tokenSet: Boolean, onChange: (String)
onValueChange = onChange,
label = { Text(if (tokenSet) "Replace token" else "Token") },
placeholder = { Text(if (tokenSet) "Token saved" else "") },
supportingText = { Text("From listenbrainz.org/profile; never shown again") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
@@ -129,36 +109,3 @@ private fun SaveTokenButton(isSaving: Boolean, enabled: Boolean, onClick: () ->
Text(if (isSaving) "Saving…" else "Save token")
}
}
@Composable
private fun EnabledRow(
status: ListenBrainzStatus?,
isSaving: Boolean,
onSetEnabled: (Boolean) -> Unit,
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Column(modifier = Modifier.padding(end = 12.dp)) {
Text(
text = "Send my plays to ListenBrainz",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface,
)
if (status?.lastScrobbledAt != null) {
Text(
text = "Last scrobble: ${status.lastScrobbledAt}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
Switch(
checked = status?.enabled == true,
onCheckedChange = onSetEnabled,
enabled = !isSaving && status?.tokenSet == true,
)
}
}
@@ -1,30 +1,15 @@
package com.fabledsword.minstrel.settings.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fabledsword.minstrel.settings.data.NormalizationBoost
import com.fabledsword.minstrel.settings.data.NormalizationMode
import com.fabledsword.minstrel.settings.data.NormalizationPrefs
import com.fabledsword.minstrel.theme.ChoiceRow
import com.fabledsword.minstrel.theme.Section
import com.fabledsword.minstrel.theme.SwitchRow
/**
* Volume leveling. The choice is stored on the server, so the
@@ -36,80 +21,29 @@ fun NormalizationCard(viewModel: NormalizationViewModel = hiltViewModel()) {
NormalizationCardContent(prefs = prefs, onChange = viewModel::update)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun NormalizationCardContent(
prefs: NormalizationPrefs,
onChange: (NormalizationPrefs) -> Unit,
) {
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
text = "Volume leveling",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
Section("Volume leveling") {
ChoiceRow(
title = "Leveling",
summary = modeHint(prefs.mode),
options = NormalizationMode.entries.map { it to modeLabel(it) },
selected = prefs.mode,
onSelect = { onChange(prefs.copy(mode = it)) },
)
Hint(modeHint(prefs.mode))
val modes = NormalizationMode.entries
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
modes.forEachIndexed { index, mode ->
SegmentedButton(
selected = mode == prefs.mode,
onClick = { onChange(prefs.copy(mode = mode)) },
shape = SegmentedButtonDefaults.itemShape(
index = index,
count = modes.size,
),
) { Text(modeLabel(mode)) }
}
}
if (prefs.mode != NormalizationMode.OFF) {
TargetRow(prefs = prefs, onChange = onChange)
BoostRow(prefs = prefs, onChange = onChange)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun TargetRow(prefs: NormalizationPrefs, onChange: (NormalizationPrefs) -> Unit) {
Text(
text = "Target loudness",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface,
ChoiceRow(
title = "Target loudness",
options = NormalizationPrefs.TARGETS.map { it to "$it LUFS" },
selected = prefs.targetLufs,
onSelect = { onChange(prefs.copy(targetLufs = it)) },
)
val targets = NormalizationPrefs.TARGETS
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
targets.forEachIndexed { index, lufs ->
SegmentedButton(
selected = lufs == prefs.targetLufs,
onClick = { onChange(prefs.copy(targetLufs = lufs)) },
shape = SegmentedButtonDefaults.itemShape(
index = index,
count = targets.size,
),
) { Text("$lufs LUFS") }
}
}
}
@Composable
private fun BoostRow(prefs: NormalizationPrefs, onChange: (NormalizationPrefs) -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Boost quiet tracks fully",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface,
)
Hint("A limiter catches the peaks.")
}
Spacer(Modifier.size(12.dp))
Switch(
SwitchRow(
title = "Boost quiet tracks fully",
summary = "A limiter catches the peaks",
checked = prefs.boost == NormalizationBoost.LIMITER,
onCheckedChange = { on ->
val boost = if (on) NormalizationBoost.LIMITER else NormalizationBoost.HEADROOM
@@ -117,15 +51,7 @@ private fun BoostRow(prefs: NormalizationPrefs, onChange: (NormalizationPrefs) -
},
)
}
}
@Composable
private fun Hint(text: String) {
Text(
text = text,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
private fun modeLabel(mode: NormalizationMode): String = when (mode) {
@@ -1,7 +1,5 @@
package com.fabledsword.minstrel.settings.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
@@ -10,7 +8,6 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
@@ -22,20 +19,13 @@ import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fabledsword.minstrel.theme.Muted
import com.fabledsword.minstrel.theme.Section
@Composable
fun PasswordCard(viewModel: PasswordViewModel = hiltViewModel()) {
val state by viewModel.state.collectAsStateWithLifecycle()
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
text = "Password",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
)
Section("Password") {
PasswordField(
value = state.current,
label = "Current password",
@@ -67,14 +57,7 @@ fun PasswordCard(viewModel: PasswordViewModel = hiltViewModel()) {
}
Text(if (state.isChanging) "Changing…" else "Change password")
}
if (state.message != null) {
Text(
text = state.message!!,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
state.message?.let { Muted(it) }
}
}
@@ -1,8 +1,6 @@
package com.fabledsword.minstrel.settings.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
@@ -10,7 +8,6 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
@@ -21,20 +18,13 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fabledsword.minstrel.theme.Muted
import com.fabledsword.minstrel.theme.Section
@Composable
fun ProfileCard(viewModel: ProfileViewModel = hiltViewModel()) {
val state by viewModel.state.collectAsStateWithLifecycle()
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
text = "Profile",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
)
Section("Profile") {
if (state.isLoading) {
Box(
modifier = Modifier.fillMaxWidth().padding(16.dp),
@@ -52,7 +42,6 @@ fun ProfileCard(viewModel: ProfileViewModel = hiltViewModel()) {
)
}
}
}
}
@Composable
@@ -95,11 +84,5 @@ private fun ProfileForm(
}
Text(if (isSaving) "Saving…" else "Save profile")
}
if (message != null) {
Text(
text = message,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (message != null) Muted(message)
}
@@ -1,34 +1,19 @@
@file:Suppress("TooManyFunctions") // Settings screen + per-card helper composables
@file:Suppress("TooManyFunctions") // Settings screen + per-section composables
package com.fabledsword.minstrel.settings.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@@ -37,27 +22,28 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import com.composables.icons.lucide.Bell
import com.composables.icons.lucide.ChevronRight
import com.composables.icons.lucide.ListMusic
import com.composables.icons.lucide.LogOut
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Shield
import com.fabledsword.minstrel.nav.Admin
import com.fabledsword.minstrel.nav.NotificationSettings
import com.fabledsword.minstrel.nav.Requests
import com.fabledsword.minstrel.nav.Settings as SettingsRoute
import com.fabledsword.minstrel.nav.ServerUrl
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.nav.Settings as SettingsRoute
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.theme.ChoiceRow
import com.fabledsword.minstrel.theme.RowChevron
import com.fabledsword.minstrel.theme.RowSpinner
import com.fabledsword.minstrel.theme.Section
import com.fabledsword.minstrel.theme.SectionEdge
import com.fabledsword.minstrel.theme.SectionGap
import com.fabledsword.minstrel.theme.SettingRow
import com.fabledsword.minstrel.theme.SwitchRow
import com.fabledsword.minstrel.theme.ThemeMode
import com.fabledsword.minstrel.theme.ThemePreferenceViewModel
import com.fabledsword.minstrel.update.ui.AppVersionCard
@@ -99,7 +85,6 @@ fun SettingsScreen(
state = state,
themeMode = themeMode,
onPickTheme = themeVm::setThemeMode,
onNavToRequests = { navController.navigate(Requests) },
onNavToNotifications = { navController.navigate(NotificationSettings) },
onNavToAdmin = { navController.navigate(Admin) },
onToggleDiagnostics = viewModel::setDiagnosticsOptOut,
@@ -119,11 +104,10 @@ fun SettingsScreen(
@Composable
private fun SettingsList(
inner: androidx.compose.foundation.layout.PaddingValues,
inner: PaddingValues,
state: SettingsState,
themeMode: ThemeMode,
onPickTheme: (ThemeMode) -> Unit,
onNavToRequests: () -> Unit,
onNavToNotifications: () -> Unit,
onNavToAdmin: () -> Unit,
onToggleDiagnostics: (Boolean) -> Unit,
@@ -134,48 +118,25 @@ private fun SettingsList(
.fillMaxSize()
.padding(inner)
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
.padding(horizontal = SectionEdge, vertical = SectionEdge),
verticalArrangement = Arrangement.spacedBy(SectionGap),
) {
AccountCard(
username = state.username,
isAdmin = state.isAdmin,
serverUrl = state.serverUrl,
AccountSection(
state = state,
onNavToNotifications = onNavToNotifications,
onNavToAdmin = onNavToAdmin,
onSignOutClick = onSignOutClick,
)
NavTile(
icon = Lucide.ListMusic,
title = "My requests",
subtitle = "Track what you've asked Minstrel to add",
onClick = onNavToRequests,
)
NavTile(
icon = Lucide.Bell,
title = "Notifications",
subtitle = "What reaches you, and where",
onClick = onNavToNotifications,
)
if (state.isAdmin) {
NavTile(
icon = Lucide.Shield,
title = "Admin",
subtitle = "Manage requests, quarantine, and users",
onClick = onNavToAdmin,
)
}
ProfileCard()
PasswordCard()
ListenBrainzCard()
if (state.diagnosticsEnabledByAdmin) {
DiagnosticsCard(
optOut = state.diagnosticsOptOut,
onToggle = onToggleDiagnostics,
)
DiagnosticsSection(optOut = state.diagnosticsOptOut, onToggle = onToggleDiagnostics)
}
NormalizationCard()
AppearanceCard(themeMode = themeMode, onPick = onPickTheme)
AppearanceSection(themeMode = themeMode, onPick = onPickTheme)
StorageCard()
AboutCard()
SignOutButton(isSigningOut = state.isSigningOut, onSignOut = onSignOutClick)
}
}
@@ -205,84 +166,41 @@ private fun SignOutConfirmDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) {
)
}
/** Who is signed in, where, the screens that belong to the account, and signing out. */
@Composable
private fun NavTile(
icon: ImageVector,
title: String,
subtitle: String,
onClick: () -> Unit,
private fun AccountSection(
state: SettingsState,
onNavToNotifications: () -> Unit,
onNavToAdmin: () -> Unit,
onSignOutClick: () -> Unit,
) {
ElevatedCard(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick),
) {
Row(
modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
imageVector = icon,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurface,
)
Spacer(Modifier.size(16.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = title,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
)
Text(
text = subtitle,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Icon(
imageVector = Lucide.ChevronRight,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
@Composable
private fun AccountCard(username: String, isAdmin: Boolean, serverUrl: String) {
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Text(
text = "Account",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
)
val adminTag = if (isAdmin) " · admin" else ""
Text(
text = when {
username.isEmpty() -> "Signed in"
else -> "Signed in as $username$adminTag"
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(8.dp))
Text(
text = "Server",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
)
Text(
text = serverUrl,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
Section("Account") {
SettingRow(
title = state.username.ifEmpty { "Signed in" },
summary = if (state.isAdmin) "Signed in · admin" else "Signed in",
)
SettingRow(title = "Server", summary = state.serverUrl)
SettingRow(
title = "Notifications",
summary = "What reaches you, and where",
icon = Lucide.Bell,
onClick = onNavToNotifications,
) { RowChevron() }
if (state.isAdmin) {
SettingRow(
title = "Admin",
summary = "Library health, users and metadata",
icon = Lucide.Shield,
onClick = onNavToAdmin,
) { RowChevron() }
}
SettingRow(
title = if (state.isSigningOut) "Signing out…" else "Sign out",
icon = Lucide.LogOut,
tone = MaterialTheme.colorScheme.error,
enabled = !state.isSigningOut,
onClick = onSignOutClick,
) { if (state.isSigningOut) RowSpinner() }
}
}
@@ -290,74 +208,27 @@ private fun AccountCard(username: String, isAdmin: Boolean, serverUrl: String) {
// the user turn reporting OFF on this device (battery/privacy) without
// touching the account flag. Checked = reporting on = NOT opted out.
@Composable
private fun DiagnosticsCard(optOut: Boolean, onToggle: (Boolean) -> Unit) {
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
text = "Diagnostics",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
)
Row(verticalAlignment = Alignment.CenterVertically) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Send diagnostic reports",
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface,
)
Text(
text = "Your admin enabled debug mode to investigate an " +
"issue. This device streams connectivity and playback " +
"diagnostics. Turn off any time.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Spacer(Modifier.size(12.dp))
Switch(
private fun DiagnosticsSection(optOut: Boolean, onToggle: (Boolean) -> Unit) {
Section("Diagnostics") {
SwitchRow(
title = "Send diagnostic reports",
summary = "Your admin turned on debug mode",
checked = !optOut,
onCheckedChange = { checked -> onToggle(!checked) },
)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun AppearanceCard(themeMode: ThemeMode, onPick: (ThemeMode) -> Unit) {
val options = ThemeMode.entries
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
text = "Appearance",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
private fun AppearanceSection(themeMode: ThemeMode, onPick: (ThemeMode) -> Unit) {
Section("Appearance") {
ChoiceRow(
title = "Theme",
summary = if (themeMode == ThemeMode.SYSTEM) "Follows your device" else null,
options = ThemeMode.entries.map { it to displayName(it) },
selected = themeMode,
onSelect = onPick,
)
Text(
text = "System follows your device setting.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
options.forEachIndexed { index, mode ->
SegmentedButton(
selected = mode == themeMode,
onClick = { onPick(mode) },
shape = SegmentedButtonDefaults.itemShape(
index = index,
count = options.size,
),
) { Text(displayName(mode)) }
}
}
}
}
}
@@ -376,29 +247,3 @@ private fun AboutCard(model: UpdateViewModel = hiltViewModel()) {
CheckWhileShown(model)
AppVersionCard(model)
}
@Composable
private fun SignOutButton(isSigningOut: Boolean, onSignOut: () -> Unit) {
Button(
onClick = onSignOut,
enabled = !isSigningOut,
modifier = Modifier.fillMaxWidth(),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.errorContainer,
contentColor = MaterialTheme.colorScheme.onErrorContainer,
),
) {
if (isSigningOut) {
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
color = MaterialTheme.colorScheme.onErrorContainer,
strokeWidth = 2.dp,
)
} else {
Box(modifier = Modifier.padding(end = 4.dp)) {
Icon(Lucide.LogOut, contentDescription = null)
}
Text("Sign out")
}
}
}
@@ -1,23 +1,9 @@
package com.fabledsword.minstrel.settings.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@@ -25,12 +11,13 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fabledsword.minstrel.theme.ChoiceRow
import com.fabledsword.minstrel.theme.RowSpinner
import com.fabledsword.minstrel.theme.Section
import com.fabledsword.minstrel.theme.SettingRow
import com.fabledsword.minstrel.theme.SwitchRow
private const val GIB: Long = 1024L * 1024 * 1024
private const val MIB: Long = 1024L * 1024
@@ -48,44 +35,39 @@ private val CAP_OPTIONS: List<Pair<Long, String>> = listOf(
fun StorageCard(viewModel: StorageViewModel = hiltViewModel()) {
val state by viewModel.state.collectAsStateWithLifecycle()
var showClearConfirm by remember { mutableStateOf(false) }
ElevatedCard(modifier = Modifier.fillMaxWidth()) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
text = "Storage",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
)
Section("Storage") {
// Two budgets: a liked track that is also recently played counts
// against Liked songs only. The prefetch window has no control;
// AudioPrefetcher uses the stored value (default 5).
CapDropdown(
label = "Liked songs",
hint = "${formatBytes(state.likedBytes)} used",
CapRow(
title = "Liked songs",
used = state.likedBytes,
value = state.settings.likedCapBytes,
onSet = viewModel::setLikedCapBytes,
)
CapDropdown(
label = "Recently played",
hint = "${formatBytes(state.recentBytes)} used",
CapRow(
title = "Recently played",
used = state.recentBytes,
value = state.settings.rollingCapBytes,
onSet = viewModel::setRollingCapBytes,
)
SwitchRow(
label = "Keep liked songs offline",
hint = "Downloads on Wi-Fi",
title = "Keep liked songs offline",
summary = "Downloads on Wi-Fi",
checked = state.settings.cacheLikedTracks,
onCheckedChange = viewModel::setCacheLikedTracks,
)
StorageActions(
isSyncing = state.isSyncing,
isClearing = state.isClearing,
onSync = viewModel::syncNow,
onClear = { showClearConfirm = true },
)
}
SettingRow(
title = if (state.isSyncing) "Syncing…" else "Sync library now",
enabled = !state.isSyncing,
onClick = viewModel::syncNow,
) { if (state.isSyncing) RowSpinner() }
SettingRow(
title = if (state.isClearing) "Clearing…" else "Clear cached audio",
tone = MaterialTheme.colorScheme.error,
enabled = !state.isClearing,
onClick = { showClearConfirm = true },
) { if (state.isClearing) RowSpinner() }
}
if (showClearConfirm) {
ClearCacheConfirmDialog(
@@ -98,128 +80,19 @@ fun StorageCard(viewModel: StorageViewModel = hiltViewModel()) {
}
}
/** A storage budget: how much it holds now, and the cap it may grow to. */
@Composable
private fun CapDropdown(label: String, hint: String, value: Long, onSet: (Long) -> Unit) {
val selectedLabel = CAP_OPTIONS.firstOrNull { it.first == value }?.second
?: formatBytes(value)
LabeledDropdown(
label = label,
hint = hint,
selectedLabel = selectedLabel,
private fun CapRow(title: String, used: Long, value: Long, onSet: (Long) -> Unit) {
ChoiceRow(
title = title,
summary = "${formatBytes(used)} used",
options = CAP_OPTIONS,
selected = value,
onSelect = onSet,
selectedLabel = CAP_OPTIONS.firstOrNull { it.first == value }?.second ?: formatBytes(value),
)
}
/** A setting's name, with one short line under it. */
@Composable
private fun RowLabel(label: String, hint: String, modifier: Modifier = Modifier) {
Column(modifier = modifier) {
Text(
text = label,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface,
)
Text(
text = hint,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun SwitchRow(label: String, hint: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.toggleable(value = checked, role = Role.Switch, onValueChange = onCheckedChange),
verticalAlignment = Alignment.CenterVertically,
) {
RowLabel(label = label, hint = hint, modifier = Modifier.weight(1f))
Spacer(Modifier.size(12.dp))
Switch(checked = checked, onCheckedChange = null)
}
}
/**
* Label and hint on the left, button-with-current-value on the right that
* opens a DropdownMenu of [options]. Used by the cap selectors.
*/
@Composable
private fun <T> LabeledDropdown(
label: String,
hint: String,
selectedLabel: String,
options: List<Pair<T, String>>,
onSelect: (T) -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
RowLabel(label = label, hint = hint, modifier = Modifier.weight(1f))
OutlinedButton(onClick = { expanded = true }) {
Text(selectedLabel)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
) {
options.forEach { (value, name) ->
DropdownMenuItem(
text = { Text(name) },
onClick = {
expanded = false
onSelect(value)
},
)
}
}
}
}
}
@Composable
private fun StorageActions(
isSyncing: Boolean,
isClearing: Boolean,
onSync: () -> Unit,
onClear: () -> Unit,
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
OutlinedButton(
onClick = onClear,
enabled = !isClearing,
) {
if (isClearing) {
CircularProgressIndicator(
modifier = Modifier.size(16.dp),
strokeWidth = 2.dp,
)
Spacer(Modifier.size(8.dp))
}
Text(if (isClearing) "Clearing…" else "Clear cache")
}
OutlinedButton(
onClick = onSync,
enabled = !isSyncing,
) {
if (isSyncing) {
CircularProgressIndicator(
modifier = Modifier.size(16.dp),
strokeWidth = 2.dp,
)
Spacer(Modifier.size(8.dp))
}
Text(if (isSyncing) "Syncing…" else "Sync now")
}
}
}
@Composable
private fun ClearCacheConfirmDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) {
AlertDialog(
@@ -24,7 +24,6 @@ import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.EllipsisVertical
import com.composables.icons.lucide.Search as SearchIcon
import com.fabledsword.minstrel.nav.Admin
import com.fabledsword.minstrel.nav.Discover
import com.fabledsword.minstrel.nav.Home
import com.fabledsword.minstrel.nav.Library
import com.fabledsword.minstrel.nav.Notifications
@@ -37,7 +36,7 @@ import com.fabledsword.minstrel.nav.Settings as SettingsRoute
* bottom nav, drawer, or rail; every
* top-level AppBar carries this row, and the kebab covers the rest.
*
* [Home] [Library] [Search] [ ⋮ Playlists / Discover / Settings / Admin ]
* [Home] [Library] [Search] [ ⋮ Playlists / Settings / Admin ]
*
* The icon for the screen the user is currently on is suppressed so
* the action set looks contextual. The "Admin" overflow item is
@@ -124,10 +123,6 @@ private fun OverflowMenu(navController: NavHostController, isAdmin: Boolean) {
text = { Text("Playlists") },
onClick = { expanded = false; navController.navigate(Playlists) },
)
DropdownMenuItem(
text = { Text("Discover") },
onClick = { expanded = false; navController.navigate(Discover) },
)
DropdownMenuItem(
text = { Text("Settings") },
onClick = { expanded = false; navController.navigate(SettingsRoute) },
@@ -0,0 +1,262 @@
@file:Suppress("TooManyFunctions") // the settings vocabulary: a plate and its row kinds
package com.fabledsword.minstrel.theme
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import com.composables.icons.lucide.ChevronRight
import com.composables.icons.lucide.ChevronDown
import com.composables.icons.lucide.Lucide
/**
* The plate every group of settings sits on. Every section gets the same
* plate, so the screen reads as one thing; a section that matters earns its
* weight with what is inside it, never with a louder box.
*
* The rhythm between lines lives here, not at the call sites.
*/
@Composable
fun Section(
title: String,
modifier: Modifier = Modifier,
trailing: @Composable (RowScope.() -> Unit)? = null,
content: @Composable ColumnScope.() -> Unit,
) {
Surface(
modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(FabledSwordFlatTokens.radiusLg),
// `iron`, the raised surface, on the `obsidian` ground.
color = MaterialTheme.colorScheme.surface,
contentColor = MaterialTheme.colorScheme.onSurface,
) {
Column(
modifier = Modifier.padding(SectionInset),
verticalArrangement = Arrangement.spacedBy(SectionRow),
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(title, style = MaterialTheme.typography.titleMedium)
if (trailing != null) {
Row(verticalAlignment = Alignment.CenterVertically, content = trailing)
}
}
Spacer(Modifier.height(TITLE_GAP - SectionRow))
content()
}
}
}
/** The quiet line: a caption, a count, a consequence. */
@Composable
fun Muted(said: String, modifier: Modifier = Modifier, tone: Color = Color.Unspecified) {
Text(
said,
style = MaterialTheme.typography.bodySmall,
color = if (tone == Color.Unspecified) MaterialTheme.colorScheme.onSurfaceVariant else tone,
modifier = modifier,
)
}
/**
* One line of a settings section: what it is, one short line about it, and
* its control at the end. A settings screen is a menu, so the summary is one
* short line, never an explanation.
*
* With [onClick] the whole row is the tap target. [tone] colours the title of
* a row reporting something wrong, so the control beside it still reads as a
* control.
*/
@Composable
fun SettingRow(
title: String,
modifier: Modifier = Modifier,
summary: String? = null,
icon: ImageVector? = null,
tone: Color = Color.Unspecified,
enabled: Boolean = true,
onClick: (() -> Unit)? = null,
trailing: @Composable (RowScope.() -> Unit)? = null,
) {
val tappable = if (onClick != null) {
Modifier
.clip(RoundedCornerShape(FabledSwordFlatTokens.radiusMd))
.clickable(enabled = enabled, role = Role.Button, onClick = onClick)
} else {
Modifier
}
Row(
modifier = modifier
.fillMaxWidth()
.heightIn(min = ROW_HEIGHT)
.then(tappable)
.alpha(if (enabled) 1f else DISABLED_ALPHA),
verticalAlignment = Alignment.CenterVertically,
) {
if (icon != null) {
Icon(
icon,
contentDescription = null,
tint = if (tone == Color.Unspecified) MaterialTheme.colorScheme.onSurfaceVariant else tone,
modifier = Modifier.padding(end = ICON_GAP).size(ICON),
)
}
Column(Modifier.weight(1f).padding(vertical = ROW_PAD)) {
Text(
title,
style = MaterialTheme.typography.bodyLarge,
color = if (tone == Color.Unspecified) MaterialTheme.colorScheme.onSurface else tone,
)
if (summary != null) Muted(summary)
}
if (trailing != null) {
Row(
modifier = Modifier.padding(start = ICON_GAP),
verticalAlignment = Alignment.CenterVertically,
content = trailing,
)
}
}
}
/** A row whose control is a switch; the whole row toggles it. */
@Composable
fun SwitchRow(
title: String,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
modifier: Modifier = Modifier,
summary: String? = null,
enabled: Boolean = true,
) {
SettingRow(
title = title,
summary = summary,
enabled = enabled,
modifier = modifier
.clip(RoundedCornerShape(FabledSwordFlatTokens.radiusMd))
.toggleable(value = checked, enabled = enabled, role = Role.Switch, onValueChange = onCheckedChange),
) {
Switch(checked = checked, onCheckedChange = null, enabled = enabled)
}
}
/**
* A one-of-N setting: the row shows the current choice, and a tap opens the
* choices under it.
*/
@Composable
fun <T> ChoiceRow(
title: String,
options: List<Pair<T, String>>,
selected: T,
onSelect: (T) -> Unit,
modifier: Modifier = Modifier,
summary: String? = null,
selectedLabel: String = options.firstOrNull { it.first == selected }?.second.orEmpty(),
) {
var open by remember { mutableStateOf(false) }
Box(modifier) {
SettingRow(title = title, summary = summary, onClick = { open = true }) {
RowValue(selectedLabel)
Icon(
Lucide.ChevronDown,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 4.dp).size(SMALL_ICON),
)
}
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
options.forEach { (value, name) ->
DropdownMenuItem(
text = { Text(name) },
onClick = {
open = false
onSelect(value)
},
)
}
}
}
}
/** A row's value, set to the right: a count, a version, a size. */
@Composable
fun RowValue(said: String) {
Text(
said,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
/** Work in progress, at the size a row's trailing slot expects. */
@Composable
fun RowSpinner() {
CircularProgressIndicator(modifier = Modifier.size(SPINNER), strokeWidth = 2.dp)
}
/** "This opens something", for a row whose tap leads somewhere. */
@Composable
fun RowChevron() {
Icon(Lucide.ChevronRight, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant)
}
/** The screen margin either side of a plate. */
val SectionEdge = 16.dp
/** Between one plate and the next. */
val SectionGap = 14.dp
/** Inside a plate. */
val SectionInset = 18.dp
/** Between one line of a plate and the next. */
val SectionRow = 6.dp
private val TITLE_GAP = 12.dp
/** Material's one-line list item height: the smallest a thumb reliably hits. */
private val ROW_HEIGHT = 48.dp
private val ROW_PAD = 6.dp
private val ICON = 22.dp
private val SMALL_ICON = 16.dp
private val ICON_GAP = 14.dp
private const val DISABLED_ALPHA = 0.5f
private val SPINNER = 16.dp
@@ -1,24 +1,23 @@
package com.fabledsword.minstrel.update.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fabledsword.minstrel.BuildConfig
import com.fabledsword.minstrel.models.UpdateInfo
import com.fabledsword.minstrel.settings.ui.formatBytes
import com.fabledsword.minstrel.theme.Muted
import com.fabledsword.minstrel.theme.RowSpinner
import com.fabledsword.minstrel.theme.RowValue
import com.fabledsword.minstrel.theme.Section
import com.fabledsword.minstrel.theme.SettingRow
import com.fabledsword.minstrel.update.data.InstallStage
import com.fabledsword.minstrel.update.data.UpdateUiState
@@ -36,53 +35,41 @@ fun AppVersionCard(model: UpdateViewModel, modifier: Modifier = Modifier) {
onPauseOrDispose {}
}
val state by model.state.collectAsStateWithLifecycle()
ElevatedCard(modifier = modifier.fillMaxWidth()) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
text = "About",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
)
Text(
text = "Installed: Minstrel ${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Section("About", modifier) {
SettingRow(title = "Version") {
RowValue("${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})")
}
val offer = state.offer
if (offer != null) {
Offered(offer, state, model::update)
} else {
Text(
text = versionWords(state, selfUpdates = !BuildConfig.DEBUG),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
state.problem?.let {
Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
}
TextButton(
onClick = model::check,
enabled = !BuildConfig.DEBUG && !state.checking && state.stage == InstallStage.IDLE,
) { Text(if (state.checking) "Checking…" else "Check for updates") }
val canCheck = !BuildConfig.DEBUG && !state.checking && state.stage == InstallStage.IDLE
SettingRow(
title = "Check for updates",
summary = versionWords(state, selfUpdates = !BuildConfig.DEBUG),
enabled = canCheck || state.checking,
onClick = if (canCheck) model::check else null,
) { if (state.checking) RowSpinner() }
}
state.problem?.let { Muted(it, tone = MaterialTheme.colorScheme.error) }
}
}
/** The newer build, and the one button that fetches and installs it. */
@Composable
private fun Offered(offer: UpdateInfo, state: UpdateUiState, update: () -> Unit) {
Text(offeredWords(offer, state.ready), style = MaterialTheme.typography.bodyMedium)
SettingRow(
title = if (state.ready) "Ready to install" else "New version on your server",
summary = describe(offer),
) {
when (state.stage) {
InstallStage.IDLE -> Button(onClick = update, modifier = Modifier.fillMaxWidth()) {
Text(if (state.ready) "Install" else "Update")
InstallStage.IDLE -> Button(onClick = update) { Text(if (state.ready) "Install" else "Update") }
InstallStage.DOWNLOADING -> RowSpinner()
InstallStage.INSTALLING -> RowValue("Installing…")
}
InstallStage.DOWNLOADING ->
}
if (state.stage == InstallStage.DOWNLOADING) {
LinearProgressIndicator(progress = { state.progress }, modifier = Modifier.fillMaxWidth())
InstallStage.INSTALLING -> Text("Installing…", style = MaterialTheme.typography.bodyMedium)
}
}
@@ -95,14 +82,6 @@ internal fun versionWords(state: UpdateUiState, selfUpdates: Boolean = true): St
else -> "This is the newest version."
}
/** The newer build, and whether it is already downloaded. */
internal fun offeredWords(offer: UpdateInfo, ready: Boolean): String =
if (ready) {
"A new version of the app is downloaded and ready: ${describe(offer)}"
} else {
"A new version of the app is on your server: ${describe(offer)}"
}
/** The name, the channel when it is the test line, and the size. */
internal fun describe(offer: UpdateInfo): String {
val channel = if (offer.channel == "dev") " (test build)" else ""
@@ -1,39 +0,0 @@
package com.fabledsword.minstrel.admin.data
import com.fabledsword.minstrel.api.endpoints.AdminRequestsApi
import com.fabledsword.minstrel.models.wire.RequestWire
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Test
import retrofit2.Retrofit
import kotlin.test.assertEquals
/**
* The admin queue names who asked from the row itself: the server
* sends the requester's username, so the screen needs no users-list fetch.
*/
class AdminRequestsRepositoryTest {
private val api: AdminRequestsApi = mockk(relaxed = true)
private val retrofit: Retrofit = mockk {
every { create(AdminRequestsApi::class.java) } returns api
}
private val repo = AdminRequestsRepository(retrofit)
@Test
fun `a request carries the requester's username`() = runTest {
coEvery { api.list() } returns listOf(
RequestWire(id = "r1", userId = "f7e1ec86-0e76-4cad-8191-b0cc78492851", username = "alice"),
)
assertEquals("alice", repo.list().single().username)
}
@Test
fun `a request without a username keeps it empty`() = runTest {
coEvery { api.list() } returns listOf(RequestWire(id = "r1", userId = "u1"))
assertEquals("", repo.list().single().username)
}
}
@@ -2,23 +2,32 @@ package com.fabledsword.minstrel.api
import com.fabledsword.minstrel.auth.AuthStore
import com.fabledsword.minstrel.auth.FakeSessionVault
import com.fabledsword.minstrel.auth.SessionVault
import com.fabledsword.minstrel.cache.db.dao.AuthSessionDao
import com.fabledsword.minstrel.cache.db.entities.AuthSessionEntity
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
@OptIn(ExperimentalCoroutinesApi::class)
class AuthCookieInterceptorTest {
@@ -92,6 +101,87 @@ class AuthCookieInterceptorTest {
assertNull(authStore.sessionCookie.value)
}
@Test
fun `a refused session asks the UI to open sign-in`() {
authStore.setSessionCookie("session=expired")
server.enqueue(MockResponse().setResponseCode(401))
client.newCall(Request.Builder().url(placeholderUrl("/api/test")).build()).execute()
assertTrue(authStore.sessionRejected.value)
}
// A refusal of a request that carried no cookie says nothing about the
// stored login, and must not raise the sign-in screen either.
@Test
fun `a 401 to a request sent without a cookie signs nobody out`() {
server.enqueue(MockResponse().setResponseCode(401))
client.newCall(Request.Builder().url(placeholderUrl("/api/test")).build()).execute()
assertFalse(authStore.sessionRejected.value)
}
// The interceptor reads the cookie when the request starts. A sign-in
// that lands while an old request is in flight must survive that old
// request's 401.
@Test
fun `a 401 for an older cookie keeps the one stored since`() {
authStore.setSessionCookie("session=old")
server.dispatcher =
object : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse {
authStore.setSessionCookie("session=new")
return MockResponse().setResponseCode(401)
}
}
client.newCall(Request.Builder().url(placeholderUrl("/api/test")).build()).execute()
assertEquals("session=new", authStore.sessionCookie.value)
assertFalse(authStore.sessionRejected.value)
}
// At launch the stored cookie loads from the Keystore off the main
// thread. A request made before that finishes waits for it rather than
// going out without the login.
@Test
fun `a request made while the stored cookie is still loading carries it`() {
val slowVault =
object : SessionVault {
override fun read(): String? {
Thread.sleep(SLOW_VAULT_MS)
return "session=stored"
}
override fun write(value: String?): Boolean = true
}
// The store runs on a real background dispatcher here, so its row
// collector lands after construction; the row itself carries the
// server URL so that collector cannot reset it to the default.
val row = AuthSessionEntity(baseUrl = server.url("/").toString())
val dao =
mockk<AuthSessionDao> {
every { observe() } returns flowOf(row)
coEvery { get() } returns row
coEvery { upsert(any()) } returns Unit
coEvery { setSessionCookie(any()) } returns Unit
coEvery { setBaseUrl(any()) } returns Unit
}
val loading = AuthStore(dao, slowVault, CoroutineScope(SupervisorJob() + Dispatchers.Default))
val launchClient =
OkHttpClient.Builder()
.addInterceptor(AuthCookieInterceptor(loading))
.addInterceptor(BaseUrlInterceptor(loading))
.build()
server.enqueue(MockResponse().setResponseCode(200))
launchClient.newCall(Request.Builder().url(placeholderUrl("/api/library/sync")).build()).execute()
assertEquals("session=stored", server.takeRequest().getHeader("Cookie"))
assertEquals("session=stored", loading.sessionCookie.value)
}
@Test
fun `captures Set-Cookie on successful response`() {
server.enqueue(
@@ -145,4 +235,8 @@ class AuthCookieInterceptorTest {
assertEquals("session=keep", authStore.sessionCookie.value)
}
private companion object {
const val SLOW_VAULT_MS = 300L
}
}
@@ -70,8 +70,7 @@ class BaseUrlInterceptorTest {
// External artwork hosts (artwork.musicbrainz.org,
// coverartarchive.org) are absolute external URLs. The
// interceptor must NOT rewrite them to the Minstrel base —
// doing so produces 404s the user saw as missing Discover
// suggestion covers.
// doing so produces 404s, and the art never shows.
authStore.setBaseUrl(server.url("/").toString())
var seen: HttpUrl? = null
val client =
@@ -0,0 +1,87 @@
package com.fabledsword.minstrel.auth
import com.fabledsword.minstrel.cache.db.dao.AuthSessionDao
import com.fabledsword.minstrel.cache.db.entities.AuthSessionEntity
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.flowOf
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class AuthControllerTest {
private lateinit var server: MockWebServer
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val json = Json { ignoreUnknownKeys = true }
@BeforeEach
fun setup() {
server = MockWebServer().apply { start() }
}
@AfterEach
fun teardown() {
scope.cancel()
server.shutdown()
}
// At launch the controller refreshes the profile (it carries account
// flags such as debug mode). The stored login loads from the Keystore
// off the main thread, so the refresh has to wait for it rather than
// read the user as signed out and skip.
@Test
fun `the launch profile refresh waits for the stored login`() {
val slowVault =
object : SessionVault {
override fun read(): String? {
Thread.sleep(SLOW_VAULT_MS)
return "session=stored"
}
override fun write(value: String?): Boolean = true
}
val row = AuthSessionEntity(baseUrl = server.url("/").toString())
val dao =
mockk<AuthSessionDao> {
every { observe() } returns flowOf(row)
coEvery { get() } returns row
coEvery { upsert(any()) } returns Unit
coEvery { setSessionCookie(any()) } returns Unit
coEvery { setBaseUrl(any()) } returns Unit
}
val store = AuthStore(dao, slowVault, scope)
val retrofit =
Retrofit.Builder()
.baseUrl(server.url("/"))
.client(OkHttpClient.Builder().build())
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.build()
server.enqueue(MockResponse().setResponseCode(200).setBody("""{"id":"u1","username":"listener"}"""))
AuthController(store, json, scope, retrofit)
val request = server.takeRequest(REQUEST_WAIT_SECONDS, TimeUnit.SECONDS)
assertNotNull(request, "the profile refresh never reached the server")
assertEquals("/api/me", request.path)
}
private companion object {
const val SLOW_VAULT_MS = 300L
const val REQUEST_WAIT_SECONDS = 5L
}
}
@@ -13,22 +13,13 @@ import kotlin.test.assertTrue
* Collapse rules for desired-state toggles in the offline queue.
*
* The hazard this guards against is real and silent: without collapsing, a
* queued snooze that replays AFTER the user's undo re-hides an artist they
* asked to see again, and nothing surfaces the contradiction.
* queued like that replays AFTER the user's unlike likes the artist again,
* and nothing surfaces the contradiction.
*/
class SupersededToggleIdsTest {
private val json = Json { ignoreUnknownKeys = true }
private fun snoozeRow(id: Long, mbid: String, desiredSnoozed: Boolean) = CachedMutationEntity(
id = id,
kind = MutationKind.SUGGESTION_SNOOZE_TOGGLE,
payload = json.encodeToString(
SuggestionSnoozeTogglePayload.serializer(),
SuggestionSnoozeTogglePayload(mbid, "Name", desiredSnoozed),
),
)
private fun likeRow(id: Long, entityId: String, desired: Boolean) = CachedMutationEntity(
id = id,
kind = MutationKind.LIKE_TOGGLE,
@@ -39,54 +30,46 @@ class SupersededToggleIdsTest {
)
@Test
fun `a snooze followed by its undo drops the snooze`() {
fun `a like followed by its undo drops the like`() {
val rows = listOf(
snoozeRow(1, "mb-a", desiredSnoozed = true),
snoozeRow(2, "mb-a", desiredSnoozed = false),
likeRow(1, "artist-1", desired = true),
likeRow(2, "artist-1", desired = false),
)
// Only the later intent (the undo) survives to be replayed.
assertEquals(setOf(1L), supersededToggleIds(rows, json))
}
@Test
fun `toggles for different candidates never collapse into each other`() {
fun `toggles for different entities never collapse into each other`() {
val rows = listOf(
snoozeRow(1, "mb-a", desiredSnoozed = true),
snoozeRow(2, "mb-b", desiredSnoozed = true),
likeRow(1, "artist-1", desired = true),
likeRow(2, "artist-2", desired = true),
)
assertTrue(supersededToggleIds(rows, json).isEmpty())
}
@Test
fun `only the newest of several toggles for one candidate survives`() {
fun `only the newest of several toggles for one entity survives`() {
val rows = listOf(
snoozeRow(1, "mb-a", desiredSnoozed = true),
snoozeRow(2, "mb-a", desiredSnoozed = false),
snoozeRow(3, "mb-a", desiredSnoozed = true),
likeRow(1, "artist-1", desired = true),
likeRow(2, "artist-1", desired = false),
likeRow(3, "artist-1", desired = true),
)
assertEquals(setOf(1L, 2L), supersededToggleIds(rows, json))
}
// The kind is part of the collapse key, so a snooze and a like that happen
// to share an id string must not shadow one another.
// The kind is part of the collapse key, so a like and a notification
// setting whose fields happen to spell the same strings must not shadow
// one another.
@Test
fun `a like and a snooze on the same id string do not collide`() {
fun `a like and a setting with the same strings do not collide`() {
val rows = listOf(
likeRow(1, "same-id", desired = true),
snoozeRow(2, "same-id", desiredSnoozed = true),
settingRow(2, "artist", "same-id", value = true),
)
assertTrue(supersededToggleIds(rows, json).isEmpty())
}
@Test
fun `like toggles still collapse — the pre-existing behaviour is intact`() {
val rows = listOf(
likeRow(1, "artist-1", desired = true),
likeRow(2, "artist-1", desired = false),
)
assertEquals(setOf(1L), supersededToggleIds(rows, json))
}
@Test
fun `non-toggle kinds are never collapsed, even repeated for one entity`() {
// Two appends to the same playlist are two real actions, not one
@@ -120,10 +103,10 @@ class SupersededToggleIdsTest {
val rows = listOf(
CachedMutationEntity(
id = 1,
kind = MutationKind.SUGGESTION_SNOOZE_TOGGLE,
kind = MutationKind.LIKE_TOGGLE,
payload = "{ not json",
),
snoozeRow(2, "mb-a", desiredSnoozed = true),
likeRow(2, "artist-1", desired = true),
)
assertTrue(supersededToggleIds(rows, json).isEmpty())
}
@@ -148,7 +131,7 @@ class SupersededToggleIdsTest {
fun `only the newest queued normalization change survives`() {
val rows = listOf(
normalizationRow(1, NormalizationMode.TRACK),
snoozeRow(2, "mb-a", desiredSnoozed = true),
likeRow(2, "artist-1", desired = true),
normalizationRow(3, NormalizationMode.OFF),
normalizationRow(4, NormalizationMode.ALBUM),
)
@@ -167,12 +150,12 @@ class SupersededToggleIdsTest {
@Test
fun `notification settings collapse per kind and channel, never across them`() {
val rows = listOf(
settingRow(1, "request_completed", "email", false),
settingRow(2, "request_completed", "phone", false),
settingRow(3, "request_completed", "email", true),
settingRow(4, "request_approved", "email", false),
settingRow(1, "tracks_missing", "email", false),
settingRow(2, "tracks_missing", "phone", false),
settingRow(3, "tracks_missing", "email", true),
settingRow(4, "quarantine_flagged", "email", false),
)
// Only the older email toggle for request_completed is superseded.
// Only the older email toggle for tracks_missing is superseded.
assertEquals(setOf(1L), supersededToggleIds(rows, json))
}
@@ -4,6 +4,7 @@ import com.fabledsword.minstrel.models.PlaylistRef
import com.fabledsword.minstrel.models.SystemPlaylistsStatus
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class BuildPlaylistsRowTest {
@@ -103,4 +104,40 @@ class BuildPlaylistsRowTest {
assertTrue(buildSongsLikeRow(emptyList(), SystemPlaylistsStatus(), offline = true).isEmpty())
}
private fun genreMix(name: String, cached: Boolean) = PlaylistRef(
id = name,
userId = "u",
name = name,
systemVariant = "genre_mix",
trackCount = 50,
fullyCached = cached,
)
@Test
fun `genre mixes get their own row in name order and stay out of the carousel`() {
val owned = listOf(
genreMix("Shoegaze mix", cached = true),
genreMix("dub mix", cached = true),
genreMix("Jazz mix", cached = true),
user("u1", cached = true),
)
val row = buildGenreMixRow(owned, offline = false)
val names = row.filterIsInstance<PlaylistRowItem.Real>().map { it.playlist.name }
assertEquals(listOf("dub mix", "Jazz mix", "Shoegaze mix"), names)
val carousel = buildPlaylistsRow(owned, SystemPlaylistsStatus(), offline = false)
.filterIsInstance<PlaylistRowItem.Real>().map { it.playlist.id }
assertEquals(listOf("u1"), carousel)
}
@Test
fun `genre mixes are not refreshable, so a cached one plays offline`() {
assertFalse(genreMix("Jazz mix", cached = true).refreshable)
val owned = listOf(genreMix("A mix", cached = false), genreMix("B mix", cached = true))
val names = buildGenreMixRow(owned, offline = true)
.filterIsInstance<PlaylistRowItem.Real>().map { it.playlist.name }
assertEquals(listOf("B mix", "A mix"), names)
assertTrue(buildGenreMixRow(emptyList(), offline = false).isEmpty())
}
}
@@ -1,85 +0,0 @@
package com.fabledsword.minstrel.models
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
/**
* The card's subtitle line. Wording is kept in lockstep with the web
* client's reasonText() in SuggestionFeed.svelte — these assertions are the
* record of what that wording IS, so a change on one client without the other
* shows up as a failure rather than as silent divergence between the two
* surfaces.
*/
class ArtistSuggestionReasonTest {
private val seeds = listOf(
SeedContributionRef(name = "Seed", isLiked = true),
)
private fun suggestion(
matched: List<String> = emptyList(),
attribution: List<SeedContributionRef> = seeds,
) = ArtistSuggestionRef(
mbid = "mb",
name = "Candidate",
attribution = attribution,
matchedTags = matched,
)
@Test
fun `one matched tag reads in the singular`() {
assertEquals(
"Matches your taste in shoegaze.",
suggestion(matched = listOf("shoegaze")).reasonText,
)
}
@Test
fun `two matched tags join with and`() {
assertEquals(
"Matches your taste in shoegaze and dream pop.",
suggestion(matched = listOf("shoegaze", "dream pop")).reasonText,
)
}
@Test
fun `three matched tags use an Oxford comma`() {
assertEquals(
"Matches your taste in a, b, and c.",
suggestion(matched = listOf("a", "b", "c")).reasonText,
)
}
// The server caps at 3, but the client must not render a run-on line if a
// future server sends more.
@Test
fun `more than three matched tags are capped at three`() {
assertEquals(
"Matches your taste in a, b, and c.",
suggestion(matched = listOf("a", "b", "c", "d", "e")).reasonText,
)
}
// The COMMON case: most candidates have no cached tags, so the card
// must fall back to seed attribution rather than going blank.
@Test
fun `no matched tags falls back to seed attribution`() {
assertEquals("Because you liked Seed.", suggestion().reasonText)
}
// Nothing to say at all — a candidate with neither tags nor attribution
// yields an empty line, which the tile suppresses rather than rendering as
// a blank row.
@Test
fun `neither tags nor attribution yields an empty line`() {
assertEquals("", suggestion(attribution = emptyList()).reasonText)
}
// The taste reason WINS over attribution when both exist: describing the
// music beats describing the similarity graph.
@Test
fun `a taste match supersedes seed attribution`() {
val got = suggestion(matched = listOf("shoegaze")).reasonText
assertEquals("Matches your taste in shoegaze.", got)
}
}
@@ -1,83 +0,0 @@
package com.fabledsword.minstrel.models
import kotlinx.datetime.Instant
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
/**
* `returnsIn` phrasing for the parked-suggestions list. The clock is
* injected rather than frozen, so these assertions are stable.
*/
class SuggestionSnoozeRefTest {
private val now = 1_800_000_000_000L // fixed epoch ms; any value works
private fun snoozeIn(days: Double) = SuggestionSnoozeRef(
mbid = "mb",
name = "Parked",
snoozedUntil = Instant
.fromEpochMilliseconds(now + (days * 86_400_000L).toLong())
.toString(),
)
@Test
fun `the default 90-day snooze reads as about 3 months`() {
assertEquals("in about 3 months", snoozeIn(90.0).returnsIn(now))
}
@Test
fun `a month reads in the singular`() {
assertEquals("in about a month", snoozeIn(30.0).returnsIn(now))
}
@Test
fun `under the month threshold it counts days`() {
assertEquals("in 14 days", snoozeIn(14.0).returnsIn(now))
}
// Pins the days→months boundary. The singular branch was originally dead
// code because the threshold (45) sat above the divisor (30), so no day
// count could ever round to one month without being caught by the days
// branch first. Asserting both sides of the seam keeps that from
// regressing silently.
@Test
fun `the days-to-months boundary is exactly at 30 days`() {
assertEquals("in 29 days", snoozeIn(29.0).returnsIn(now))
assertEquals("in about a month", snoozeIn(30.0).returnsIn(now))
}
@Test
fun `well past a month still reads in the singular rather than jumping to two`() {
assertEquals("in about a month", snoozeIn(40.0).returnsIn(now))
}
@Test
fun `tomorrow is named, not rendered as 1 days`() {
assertEquals("tomorrow", snoozeIn(1.0).returnsIn(now))
}
@Test
fun `later today rounds down to today rather than going negative`() {
assertEquals("today", snoozeIn(0.1).returnsIn(now))
}
// The server only ever returns unexpired rows, so a past timestamp means
// our clock and the server's disagree. The row is on screen either way, so
// say something plausible rather than leaving the line blank.
@Test
fun `an already-past expiry degrades to shortly`() {
assertEquals("shortly", snoozeIn(-5.0).returnsIn(now))
}
@Test
fun `an unparseable timestamp degrades to shortly`() {
val row = SuggestionSnoozeRef(mbid = "mb", name = "Parked", snoozedUntil = "not-a-date")
assertEquals("shortly", row.returnsIn(now))
}
@Test
fun `an empty timestamp degrades to shortly`() {
val row = SuggestionSnoozeRef(mbid = "mb", name = "Parked", snoozedUntil = "")
assertEquals("shortly", row.returnsIn(now))
}
}
@@ -38,7 +38,7 @@ class NotificationSettingsRepositoryTest {
private val settings = NotificationSettingsWire(
kinds = listOf(
NotificationKindSettingWire("request_completed", false, inbox = true, phone = true, email = true),
NotificationKindSettingWire("new_music", false, inbox = true, phone = true, email = true),
),
emailAvailable = true,
)
@@ -58,12 +58,12 @@ class NotificationSettingsRepositoryTest {
val body = slot<PutNotificationSettingsBody>()
coEvery { api.putSettings(capture(body)) } returns settings
repo.set("request_completed", NotificationChannel.EMAIL, false)
repo.set("new_music", NotificationChannel.EMAIL, false)
val optimistic = json.decodeFromString(NotificationSettingsWire.serializer(), saved.first().json)
assertFalse(optimistic.kinds.single().email)
assertEquals(
listOf(NotificationSettingChangeWire(kind = "request_completed", email = false)),
listOf(NotificationSettingChangeWire(kind = "new_music", email = false)),
body.captured.kinds,
)
coVerify(exactly = 0) { queue.enqueueNotificationSettingSet(any()) }
@@ -75,10 +75,10 @@ class NotificationSettingsRepositoryTest {
coEvery { mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET) } returns false
coEvery { api.putSettings(any()) } throws IOException("offline")
repo.set("request_completed", NotificationChannel.PHONE, false)
repo.set("new_music", NotificationChannel.PHONE, false)
coVerify {
queue.enqueueNotificationSettingSet(NotificationSettingPayload("request_completed", "phone", false))
queue.enqueueNotificationSettingSet(NotificationSettingPayload("new_music", "phone", false))
}
}
@@ -87,11 +87,11 @@ class NotificationSettingsRepositoryTest {
cached()
coEvery { mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET) } returns true
repo.set("request_completed", NotificationChannel.INBOX, false)
repo.set("new_music", NotificationChannel.INBOX, false)
coVerify(exactly = 0) { api.putSettings(any()) }
coVerify {
queue.enqueueNotificationSettingSet(NotificationSettingPayload("request_completed", "inbox", false))
queue.enqueueNotificationSettingSet(NotificationSettingPayload("new_music", "inbox", false))
}
}
@@ -41,10 +41,10 @@ class NotificationsRepositoryTest {
private fun row(id: String, created: String, readAt: Instant? = null) = CachedNotificationEntity(
id = id,
kind = "request_completed",
kind = "new_music",
title = "t",
body = "b",
link = "/requests",
link = "/",
createdAt = Instant.parse(created),
readAt = readAt,
)
@@ -108,8 +108,8 @@ class NotificationsRepositoryTest {
coEvery { dao.getAll() } returns listOf(row("a", "2026-10-08T10:00:00Z", readAt = readHere))
coEvery { api.list(any()) } returns NotificationsPageWire(
items = listOf(
NotificationWire("a", "request_completed", "t", "b", "/requests", "2026-10-08T10:00:00Z", null),
NotificationWire("b", "request_completed", "t", "b", "/requests", "2026-10-08T11:00:00Z", null),
NotificationWire("a", "new_music", "t", "b", "/", "2026-10-08T10:00:00Z", null),
NotificationWire("b", "new_music", "t", "b", "/", "2026-10-08T11:00:00Z", null),
),
unreadCount = 2,
)
@@ -17,14 +17,14 @@ class DeliveryPlanTest {
private fun notice(
id: String,
minutes: Long,
kind: String = "request_approved",
kind: String = "new_music",
read: Boolean = false,
) = CachedNotificationEntity(
id = id,
kind = kind,
title = "t-$id",
body = "b-$id",
link = "/requests",
link = "/",
createdAt = Instant.fromEpochMilliseconds(t0.toEpochMilliseconds() + minutes * 60_000),
readAt = if (read) t0 else null,
)
@@ -75,17 +75,17 @@ class DeliveryPlanTest {
fun `phone prefs come from the cached settings, with every kind on when none are cached`() {
val settings = NotificationSettingsWire(
kinds = listOf(
NotificationKindSettingWire("request_approved", false, inbox = true, phone = false, email = true),
NotificationKindSettingWire("request_completed", false, inbox = false, phone = true, email = true),
NotificationKindSettingWire("request_rejected", false, inbox = true, phone = true, email = true),
NotificationKindSettingWire("new_music", false, inbox = true, phone = false, email = true),
NotificationKindSettingWire("tracks_missing", true, inbox = false, phone = true, email = true),
NotificationKindSettingWire("quarantine_flagged", true, inbox = true, phone = true, email = true),
),
emailAvailable = true,
)
val phoneOn = phoneOnFor(settings)
assertFalse(phoneOn("request_approved"))
assertFalse(phoneOn("request_completed"), "phone rides on the inbox")
assertTrue(phoneOn("request_rejected"))
assertTrue(phoneOnFor(null)("tracks_missing"))
assertFalse(phoneOn("new_music"))
assertFalse(phoneOn("tracks_missing"), "phone rides on the inbox")
assertTrue(phoneOn("quarantine_flagged"))
assertTrue(phoneOnFor(null)("scan_failed"))
}
@Test
@@ -97,7 +97,7 @@ class DeliveryPlanTest {
val five = (1..5).map { notice("n$it", it.toLong()) }
val pile = assertIs<Announcement.Pile>(announcementFor(five))
assertEquals(5, pile.count)
assertEquals(ShadeChannel.YOUR_REQUESTS, pile.channel)
assertEquals(ShadeChannel.NEW_MUSIC, pile.channel)
assertEquals("5 new notifications", pileText(pile.count))
assertEquals(listOf("t-n5", "t-n4", "t-n3", "t-n2", "t-n1"), pile.lines)
assertNull(pileMore(pile))
@@ -116,15 +116,14 @@ class DeliveryPlanTest {
val admin = (1..4).map { notice("a$it", it.toLong(), kind = "tracks_missing") }
assertEquals(ShadeChannel.LIBRARY_HEALTH, assertIs<Announcement.Pile>(announcementFor(admin)).channel)
val mixed = admin + notice("r", 9)
assertEquals(ShadeChannel.YOUR_REQUESTS, assertIs<Announcement.Pile>(announcementFor(mixed)).channel)
assertEquals(ShadeChannel.NEW_MUSIC, assertIs<Announcement.Pile>(announcementFor(mixed)).channel)
}
@Test
fun `listener kinds are their requests, the rest is library health`() {
listOf("request_approved", "request_rejected", "request_completed").forEach {
assertEquals(ShadeChannel.YOUR_REQUESTS, shadeChannelFor(it))
}
listOf("request_pending", "quarantine_flagged", "scan_failed", "tracks_missing").forEach {
fun `new music has its own channel, the rest is library health`() {
assertEquals(ShadeChannel.NEW_MUSIC, shadeChannelFor("new_music"))
assertTrue(ShadeChannel.entries.none { it.id in retiredShadeChannelIds }, "a live channel is never deleted")
listOf("quarantine_flagged", "scan_failed", "tracks_missing").forEach {
assertEquals(ShadeChannel.LIBRARY_HEALTH, shadeChannelFor(it))
}
}
@@ -3,10 +3,9 @@ package com.fabledsword.minstrel.notifications.ui
import com.fabledsword.minstrel.api.endpoints.NotificationKindSettingWire
import com.fabledsword.minstrel.nav.Admin
import com.fabledsword.minstrel.nav.AdminQuarantine
import com.fabledsword.minstrel.nav.AdminRequests
import com.fabledsword.minstrel.nav.AlbumDetail
import com.fabledsword.minstrel.nav.ArtistDetail
import com.fabledsword.minstrel.nav.Requests
import com.fabledsword.minstrel.nav.Home
import com.fabledsword.minstrel.notifications.data.NotificationChannel
import com.fabledsword.minstrel.shared.widgets.badgeLabel
import kotlinx.datetime.Instant
@@ -19,10 +18,11 @@ import kotlin.test.assertTrue
class NotificationUiTest {
@Test
fun `server links open the matching screens`() {
assertEquals(Home, routeForLink("/"))
// A pile carries no link: it opens the inbox, not Home.
assertNull(routeForLink(""))
assertEquals(AlbumDetail("al-1"), routeForLink("/albums/al-1"))
assertEquals(ArtistDetail("ar-1"), routeForLink("/artists/ar-1"))
assertEquals(Requests, routeForLink("/requests"))
assertEquals(AdminRequests, routeForLink("/admin/requests"))
assertEquals(AdminQuarantine, routeForLink("/collection/reports"))
// Library health pages the app has no screen for open the Admin landing.
assertEquals(Admin, routeForLink("/collection/duplicates"))
@@ -30,6 +30,9 @@ class NotificationUiTest {
assertEquals(Admin, routeForLink("/collection/missing"))
assertEquals(Admin, routeForLink("/admin"))
assertNull(routeForLink("/somewhere-new"))
// A link to a page the app has no screen for and Admin does not hold
// opens nothing, rather than an empty screen.
assertNull(routeForLink("/requests"))
}
@Test
@@ -51,7 +54,7 @@ class NotificationUiTest {
@Test
fun `phone and email ride on the inbox, and email needs to be available`() {
val on = NotificationKindSettingWire("request_completed", false, inbox = true, phone = true, email = true)
val on = NotificationKindSettingWire("new_music", false, inbox = true, phone = true, email = true)
val off = on.copy(inbox = false)
assertTrue(channelEnabled(on, NotificationChannel.PHONE, emailAvailable = true))
assertFalse(channelEnabled(off, NotificationChannel.PHONE, emailAvailable = true))
@@ -29,10 +29,10 @@ class NotificationsViewModelTest {
private fun row(id: String, read: Boolean) = CachedNotificationEntity(
id = id,
kind = "request_completed",
kind = "new_music",
title = "t",
body = "b",
link = "/requests",
link = "/",
createdAt = Instant.parse("2026-10-23T12:00:00Z"),
readAt = if (read) Instant.parse("2026-10-23T12:05:00Z") else null,
)
+72 -59
View File
@@ -16,6 +16,8 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/acoustid"
"git.fabledsword.com/bvandeusen/minstrel/internal/backup"
"git.fabledsword.com/bvandeusen/minstrel/internal/buildinfo"
"git.fabledsword.com/bvandeusen/minstrel/internal/catalogue"
"git.fabledsword.com/bvandeusen/minstrel/internal/config"
"git.fabledsword.com/bvandeusen/minstrel/internal/coplay"
@@ -23,24 +25,20 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
"git.fabledsword.com/bvandeusen/minstrel/internal/gc"
"git.fabledsword.com/bvandeusen/minstrel/internal/importer"
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
"git.fabledsword.com/bvandeusen/minstrel/internal/lifecycle"
"git.fabledsword.com/bvandeusen/minstrel/internal/logging"
"git.fabledsword.com/bvandeusen/minstrel/internal/mailer"
"git.fabledsword.com/bvandeusen/minstrel/internal/notifications"
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
"git.fabledsword.com/bvandeusen/minstrel/internal/reacquisition"
"git.fabledsword.com/bvandeusen/minstrel/internal/recsettings"
"git.fabledsword.com/bvandeusen/minstrel/internal/requests"
"git.fabledsword.com/bvandeusen/minstrel/internal/scrobble"
"git.fabledsword.com/bvandeusen/minstrel/internal/scrobble/listenbrainz"
"git.fabledsword.com/bvandeusen/minstrel/internal/secret"
"git.fabledsword.com/bvandeusen/minstrel/internal/server"
"git.fabledsword.com/bvandeusen/minstrel/internal/similarity"
"git.fabledsword.com/bvandeusen/minstrel/internal/subsonic"
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
"git.fabledsword.com/bvandeusen/minstrel/internal/tags"
"git.fabledsword.com/bvandeusen/minstrel/internal/wanted"
)
func main() {
@@ -58,14 +56,40 @@ func main() {
os.Exit(1)
}
return
case "restore":
if err := runRestore(os.Args[2:]); err != nil {
fmt.Fprintf(os.Stderr, "minstrel restore: %v\n", err)
os.Exit(1)
}
return
}
}
if err := run(); err != nil {
err := run()
if errors.Is(err, errRestart) {
err = restartInPlace()
}
if err != nil {
fmt.Fprintf(os.Stderr, "minstrel: %v\n", err)
os.Exit(1)
}
}
// errRestart is run's answer when the server stopped in order to start again:
// after a web restore, so the restored settings are read at boot.
var errRestart = errors.New("restart requested")
// restartInPlace replaces this process with a fresh start of the same binary,
// arguments and environment. The process id stays the same, so a container
// keeps running without needing a restart policy.
func restartInPlace() error {
exe, err := os.Executable()
if err != nil {
return fmt.Errorf("restart: %w", err)
}
// Exec returns only when it failed.
return fmt.Errorf("restart: %w", syscall.Exec(exe, os.Args, os.Environ()))
}
// safetyNetScanInterval backstops the fsnotify watcher with a low-frequency
// full delta walk, catching anything the watcher missed (inotify watch-limit
// exhaustion, dropped events). Fixed — there is no operator configuration.
@@ -128,6 +152,18 @@ func run() error {
}
defer pool.Close()
// Stored credentials are sealed under a key derived from the stream
// secret. Install it before anything reads one, and seal any value still
// stored in the clear.
secret.Install(cfg.StreamSecret)
sealed, err := secret.SealStored(ctx, pool)
if err != nil {
return fmt.Errorf("seal stored credentials: %w", err)
}
if sealed > 0 {
logger.Info("sealed stored credentials", "count", sealed)
}
// Fingerprinting settings: one instance, shared by the scanner,
// the fingerprint backfill, the duplicate sweep and the admin API, so a save
// reaches all of them without a restart. A load failure is logged, not fatal:
@@ -162,8 +198,8 @@ func run() error {
if acoustIDErr != nil {
logger.Warn("acoustid settings: using defaults (lookup off)", "err", acoustIDErr)
}
// One AcoustID client, so the lookup worker and the import's check share
// its pace (AcoustID allows three requests a second per key).
// One AcoustID client, so every lookup shares its pace (AcoustID allows
// three requests a second per key).
acoustIDClient := acoustid.New(acoustid.DefaultBaseURL)
acoustIDLookup := library.NewAcoustIDLookupWorker(pool, logger.With("component", "acoustid_lookup"),
acoustIDSettings, acoustIDClient)
@@ -314,44 +350,12 @@ func run() error {
// same pool and bus.
notifier := notifications.New(pool, bus, logger.With("component", "notifications"))
// The request reconciler completes approved requests once the library
// holds what they asked for.
requestReconciler := requests.NewReconciler(pool, logger.With("component", "requests"), bus)
requestReconciler.SetNotifier(notifier)
library.SetNotifier(notifier)
go requestReconciler.Run(ctx)
// Release catalogue: re-reads discographies older than a
// week from MusicBrainz, a batch an hour, through the process-wide
// MusicBrainz pacer it shares with tag enrichment.
// Release track lists from MusicBrainz, read on demand by the duplicate
// resolver through the process-wide MusicBrainz pacer it shares with tag
// enrichment.
cat := catalogue.New(pool, nil, logger.With("component", "catalogue"))
go cat.Run(ctx)
// The wanted list: reads followed artists' discographies
// daily for new releases and marks wants held once the library has them.
go wanted.New(pool, cat, logger.With("component", "wanted")).Run(ctx)
// Search and grab: every ten minutes, searches the
// configured indexers for wants due, paced by each source's
// searches-per-hour, and hands the best release to the download client
// when auto-grab is on.
go wanted.NewSearcher(pool, cat, logger.With("component", "search")).Run(ctx)
// Import with verification: every minute, finished
// downloads are checked against their album (AcoustID, lengths, tags)
// and filed into the library with MusicBrainz tags, or refused.
var printer importer.Printer
if acoustIDSettings != nil {
printer = &importer.AcoustIDPrinter{Settings: acoustIDSettings, Client: acoustIDClient}
}
imp := importer.New(pool, scanner, cat, printer, scanner.Roots, logger.With("component", "import"))
imp.DataDir = cfg.Storage.DataDir
go imp.Run(ctx)
// Download lifecycle: every ten minutes, a download that
// failed or that nobody shares is retried, then given up and its album
// searched again; an imported one seeds, then is removed.
go lifecycle.New(pool, logger.With("component", "lifecycle")).Run(ctx)
// Duplicate resolver: classifies the sweep's groups and, with auto-resolve
// on, merges the copies that are safe to merge.
@@ -363,19 +367,6 @@ func run() error {
TrackLists: cat.RefreshReleaseGroup, Identify: acoustIDLookup.IdentifyRecordings,
}).Run(ctx)
// Missing-file re-acquisition: wants back albums whose files have been
// gone longer than the grace window, for the search schedule to find.
// Hourly, because the grace window is measured in hours.
//
// A settings-load failure is logged, not fatal: NewSettingsService always
// returns a usable service holding the defaults.
reacqSettings, reacqErr := reacquisition.NewSettingsService(
ctx, pool, logger.With("component", "reacquisition"))
if reacqErr != nil {
logger.Warn("reacquisition: using default settings", "err", reacqErr)
}
go reacquisition.NewSweeper(pool, reacqSettings, logger.With("component", "reacquisition")).Run(ctx)
// library_changes compactor: daily, deletes
// rows older than the configured retention so the change-log table
// doesn't grow unbounded. Clients that drop offline longer than
@@ -454,10 +445,20 @@ func run() error {
srv.FingerprintSettings = fpSettings
srv.LoudnessSettings = loudSettings
srv.AcoustIDLookup = acoustIDLookup
// The sweeper above holds this same instance, so a save from the admin
// card changes what it does on its next tick.
srv.ReacqSettings = reacqSettings
// The server's own backup: the loop runs the nightly schedule, and the
// admin page starts, tests and configures the same instance.
backups := backup.NewService(pool, logger.With("component", "backup"), buildinfo.Version)
backups.Roots = scanner.Roots
go backups.Loop(ctx)
srv.Backups = backups
srv.StreamSecret = cfg.StreamSecret
restart := make(chan struct{}, 1)
srv.Restart = func() {
select {
case restart <- struct{}{}:
default:
}
}
httpServer := &http.Server{
Addr: cfg.Server.Address,
Handler: srv.Router(),
@@ -483,20 +484,32 @@ func run() error {
close(errCh)
}()
restarting := false
select {
case <-ctx.Done():
logger.Info("shutdown signal received")
case <-restart:
logger.Info("restarting to load the restored backup")
restarting = true
case err := <-errCh:
if err != nil {
return fmt.Errorf("server: %w", err)
}
}
// Ends the background work (scans, workers, schedules) as a signal would.
stop()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := httpServer.Shutdown(shutdownCtx); err != nil {
return fmt.Errorf("shutdown: %w", err)
}
// A backup still running is stopped and records that it was cut off.
backups.Close()
if restarting {
logger.Info("minstrel stopped; starting again")
return errRestart
}
logger.Info("minstrel stopped")
return nil
}
+76
View File
@@ -0,0 +1,76 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"os"
"git.fabledsword.com/bvandeusen/minstrel/internal/backup"
"git.fabledsword.com/bvandeusen/minstrel/internal/config"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/logging"
)
const restoreUsage = "usage: minstrel restore [-config PATH] FILE"
// runRestore loads a backup file into a new Minstrel's database: one with no
// accounts and no library yet. It brings the schema up to date first, so a
// backup from an older Minstrel loads into this one. The server isn't running
// meanwhile, so the library scan waits for it to start.
func runRestore(args []string) error {
fs := flag.NewFlagSet("restore", flag.ContinueOnError)
configPath := fs.String("config", os.Getenv("MINSTREL_CONFIG"), "path to YAML config file")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 1 {
return errors.New(restoreUsage)
}
cfg, err := config.Load(*configPath)
if err != nil {
return fmt.Errorf("load config: %w", err)
}
if cfg.Database.URL == "" {
return errors.New("no database URL configured (set it in the config file or MINSTREL_DATABASE_URL)")
}
logger, err := logging.New(os.Stderr, cfg.Log.Level, cfg.Log.Format)
if err != nil {
return fmt.Errorf("init logger: %w", err)
}
f, err := os.Open(fs.Arg(0))
if err != nil {
return err
}
defer func() { _ = f.Close() }()
manifest, contents, err := backup.Read(f)
if err != nil {
return err
}
if err := db.Migrate(cfg.Database.URL, logger); err != nil {
return fmt.Errorf("migrate: %w", err)
}
ctx := context.Background()
pool, err := db.Open(ctx, cfg.Database.URL)
if err != nil {
return fmt.Errorf("open db: %w", err)
}
defer pool.Close()
if err := backup.Restore(ctx, pool, contents); err != nil {
return err
}
printRestored(os.Stdout, manifest)
return nil
}
// printRestored says what came back and what happens next.
func printRestored(w io.Writer, m backup.Manifest) {
_, _ = fmt.Fprintf(w, "minstrel: restored the backup made %s by Minstrel %s (%d accounts, %d tracks, %d playlists).\n",
m.CreatedAt.Local().Format("2 Jan 2006 15:04 MST"), m.Build,
m.Rows["users"], m.Rows["tracks"], m.Rows["playlists"])
_, _ = fmt.Fprintln(w, "Start the server. The library scan (at startup, or Scan now under Admin › Library) finds each music file at its path, and the artwork, tags and analysis the backup leaves out are fetched and worked out again.")
_, _ = fmt.Fprintln(w, "Everyone signs in with the password they had. Keys for other services, and the backup's own destination, are entered again in Admin.")
}
+1 -1
View File
@@ -30,7 +30,7 @@ library:
branding:
app_name: "Minstrel" # MINSTREL_BRANDING_APP_NAME
description: "Self-hosted music server with Subsonic compatibility, smart shuffle, and music acquisition." # MINSTREL_BRANDING_DESCRIPTION
description: "Self-hosted music server with Subsonic compatibility and smart shuffle." # MINSTREL_BRANDING_DESCRIPTION
subsonic:
# Accept the plaintext `p=` password on /rest/*. Leave off unless a client
+65
View File
@@ -83,6 +83,71 @@ Creating the first account (which becomes the admin) requires that token, so
whoever reaches a newly exposed server first can't claim it. The token
changes on every restart until an account exists.
## Backups
Minstrel can back itself up once a night: accounts, likes, playlists,
listening history and settings, in one file. It is off until an
admin switches it on under **Admin › Backups**. Anything Minstrel can fetch
or work out again (artwork, fingerprints, MusicBrainz data) is left out, and
so are the keys and passwords Minstrel keeps for other services, which are
entered again on a restored server. Sign-in passwords are kept.
A backup goes to one of:
- **an S3 bucket**, path-style (MinIO, Garage, or any S3-compatible store).
The key only needs to add and list objects. Files land under `database/`.
- **a folder** on the server, under `database/` inside it. Mount a volume
there; Minstrel refuses to write into a folder that isn't there.
Minstrel only adds files, named by date, and never deletes one. Keep as many
as you like with the destination's own retention. **Test destination** lists
what is there without writing anything.
**Include the music** also sends the library's files to `music/` in the same
destination, laid out as they are under the library folders. After each
night's database file has landed, Minstrel sends the files it hasn't sent
yet, one at a time, for up to six hours; a large library takes several
nights the first time, and the panel shows how much is in. After that, a
night sends only new files and files that changed. A changed file goes to
its old name, and Minstrel still never deletes anything there, so a file
taken out of the library stays in the backup. On a bucket that keeps
versions or locks objects, set its retention to keep what you want. A file
the bucket refuses (an overwrite a locked object won't take) is listed on
the panel and goes again once it changes or the settings are saved; three
refusals in a row stop that night's music, since that is usually a key that
may not write under `music/`. A bucket's upload limit applies
to the music as well.
### Restoring
A backup restores into a new Minstrel: one nobody has signed up to yet. If
it has already scanned the music, that's fine; the backup's library takes
the place of what the scan found.
1. **Put the music back first**, at the path the library had. The restored
settings name the old library folders, and each track is found again by
its path. If the backup includes the music, copy what is inside `music/`
into the library folder (with several library folders, into the folder
that holds them all).
2. **Load the backup**, either way:
- In the web app, choose **Create account**, then **Restore a backup**.
Pick a `minstrel-….tar` file from the backup's `database/` folder and
enter the setup token from the log (see *First account*). Minstrel
restarts by itself once the backup is in, so it runs on the restored
settings.
- Or, with the server stopped, run
`docker compose run --rm minstrel restore /backups/database/minstrel-20261102T030000Z.tar`,
with the file on a volume the container can read. It brings the database
schema up to date first, so a backup from an older Minstrel loads into a
newer one; a backup from a newer Minstrel is refused.
3. **Sign in** with the password you had. Everyone else's accounts, likes,
playlists and history are back too.
The library scan then finds each file, and the artwork, tags, fingerprints
and loudness are fetched or worked out again over the following hours. Keys
for other services (ListenBrainz, AcoustID, artwork and tag providers,
email) and the backup's own destination are entered again
under **Admin**. An app that synced with the old server starts its sync over.
## Android app
The app connects over whatever URL you give it, HTTP or HTTPS. Once the
+26 -6
View File
@@ -49,22 +49,42 @@ cross-origin preflight. Requests authenticated with a bearer token or the
Subsonic query parameters carry nothing a browser attaches on its own, so
they aren't checked.
## Subsonic sign-in, and the one password stored in plain text
## Credentials Minstrel has to read back
Some credentials can't be hashed, because Minstrel has to send or compare the
value itself:
- the AcoustID key, and the cover-art and tag provider keys;
- the SMTP password;
- the secret key of the S3 bucket backups go to;
- each user's ListenBrainz token and Subsonic password.
These are encrypted in the database (AES-256-GCM). Each column has its own key,
derived from the stream secret (`MINSTREL_STREAM_SECRET`, or the
`stream_secret` file in the data directory), and each value is bound to its
row. The stream secret is never stored in the database, so a copy of the
database alone doesn't reveal any of them. None of them is ever sent back to a
browser: Settings only shows whether one is set.
**Keep the stream secret with the data directory, and don't change it
casually.** If it changes, every stored credential reads as not set, and each
one has to be entered again in Settings (Subsonic passwords generated again).
Minstrel logs a warning for each one that no longer opens.
## Subsonic sign-in
Classic Subsonic clients sign in with `t` and `s`: the MD5 of the password
followed by a random salt. To check that, the server has to know the password
itself, so supporting this sign-in method means storing a password Minstrel
can read. That is the Subsonic password, and it is the only credential
Minstrel keeps unhashed.
can read: the Subsonic password, encrypted as described above.
- **The recommended way in is the API key.** Clients that support the
OpenSubsonic `apiKey` should use it. The key is stored hashed and can be
replaced at any time in Settings.
- **The Subsonic password is never your login password.** Minstrel generates
it (**Settings → Subsonic password**), shows it once, and lets you replace
or turn it off. Because it is random, a copy of the database exposes access
to this server's Subsonic API and nothing else: it can't be a password you
also use somewhere else.
or turn it off. Because it is random, even someone holding both the database
and the stream secret gains access to this server's Subsonic API and nothing
else: it can't be a password you also use somewhere else.
- **`t`/`s` and `p=` sign-in are off for an account until it has a Subsonic
password.** Plain `p=` sign-in is additionally off server-wide unless
`subsonic.allow_plaintext_password` is enabled.
-245
View File
@@ -1,245 +0,0 @@
# Project Spec: Smart Music Client (companion app)
> **History.** This is the original design spec, kept as written. Where it describes an outside library manager doing search, adds and deletes, Minstrel now does that itself.
## 1. Overview
A mobile music player client built as the intentional companion to the Smart Music Server (see `smart-music-server-spec.md`). This is not a general-purpose Subsonic client — it is the client that knows how to consume the server's extended API and surface its novel features (contextual likes, session-aware radio, Lidarr integration, server-canonical state) as first-class UX.
The thesis driving this project, restated: **state and intelligence belong on the server.** The client's job is to be a great playback surface and input device for the server's decisions, not to reimplement them. Compared to existing Subsonic clients (Symfonium, Tempo, Substreamer), this client is thinner in its "brains" and heavier in its integration with a specific server.
**Scope of this spec:** v1 mobile client. Read the server spec first; this document assumes its terminology and data model.
## 2. Goals and non-goals
### Goals
- Native-feeling mobile app on both iOS and Android from a single codebase.
- Full playback: background audio, lock screen controls, notification controls, Bluetooth/headset button handling, CarPlay/Android Auto *awareness* (not necessarily full integration in v1 — see non-goals).
- Offline cache with explicit user control.
- First-class UX for the dual-like model: clear, fast distinction between "like generally" and "like in this context."
- Real-time session awareness: the client knows what session it's in, shows the user what the server thinks the current context is, and surfaces contextually relevant actions.
- Radio flow that feels like a single gesture (seed → queue → playing) with clear affordances for "keep this vibe," "shift vibe," and "stop."
- Lidarr search and add directly from the player when listening to suggested additions.
- Multi-device consistency: state (likes, play counts, current queue if desired) reflects the canonical server state. Two devices signed in to the same user should see the same world.
### Non-goals (v1)
- CarPlay / Android Auto full integration. v1 should not *break* when these launch (lock screen controls must work, basic media session must be present) but dedicated CarPlay UI is deferred.
- Desktop client. The server's web UI covers desktop for v1.
- Cross-server support. This client talks to the Smart Music Server specifically and uses its extended API. Pointing it at a stock Navidrome is not a goal.
- Chromecast / AirPlay. Nice-to-have, not v1.
- Lyrics display.
- Equalizer / DSP.
- Playlist editing UI beyond basic add/remove (full playlist management lives in the server web UI).
- Social features (sharing, following, comments).
## 3. Technology choices
- **Framework:** Flutter. Rationale in the server spec conversation; the audio ecosystem (`just_audio`, `audio_service`) is the most mature cross-platform option for this use case.
- **Language:** Dart.
- **State management:** Riverpod. Rationale: testable, compile-time safe, well-suited to the amount of server state this app reflects. Avoid Bloc's boilerplate; avoid Provider's looseness.
- **HTTP:** `dio` with a typed client layer generated from the server's OpenAPI spec if the server publishes one; otherwise hand-written.
- **Local storage:**
- `sqflite` or `drift` for structured local data (cached library, offline play event queue).
- `path_provider` + direct filesystem for cached audio files.
- `flutter_secure_storage` for credentials.
- **Audio:** `just_audio` for playback, `just_audio_background` / `audio_service` for lock screen and background.
- **Navigation:** `go_router`.
- **Packaging:** standard Flutter build pipeline, published as APK/AAB for Android and TestFlight build for iOS. App store publication is out of scope for v1 (sideload / personal use).
## 4. Architecture
### Layers
1. **Transport layer** — wraps the server's Subsonic and extended APIs. Handles auth, retries, connectivity changes. Exposes typed methods to higher layers.
2. **Repository layer** — merges local cache and remote data. Owns the decision of "when do I serve cached data vs. fetch fresh." Exposes streams that UI subscribes to.
3. **Playback engine** — wraps `just_audio`. Owns the queue, position, playback state. Emits events consumed by the session reporter.
4. **Session reporter** — background worker that translates playback engine events into server event API calls (play start, skip, seek, complete). Batches and retries when offline.
5. **Offline cache manager** — owns the disk cache of audio files and cover art. Implements eviction policy, explicit user-pinned downloads.
6. **UI layer** — Flutter widgets consuming Riverpod providers that wrap repositories.
### Key architectural decisions
- **Server is source of truth, local is cache.** The client does not hold authoritative state for likes, play counts, or queue membership. All user actions are fire-and-persist-locally, then sync to server. Conflict resolution favors server on write failures (with local retry).
- **Offline mode is first-class.** Every user action — liking, skipping, playing — must work offline and sync later. This means local event queue with retry, and UI that doesn't lie about server state it couldn't confirm.
- **No client-side recommendation logic.** Shuffle, radio, "play similar" all round-trip to the server. If offline, fall back to a simple random-from-cache with a UI indicator that smart features are degraded.
- **Optimistic UI.** Liking a song updates the UI immediately; sync happens in the background. Failed syncs surface as a non-blocking indicator, not a modal.
### Threading model
Flutter's main isolate handles UI. Playback and audio service run on their platform-native background threads (handled by `audio_service`). The session reporter and cache manager run as long-lived providers on the main isolate but do their work in async. Heavy operations (e.g. bulk cache cleanup) use `compute()` to offload to a worker isolate.
## 5. Data flow examples
### Starting a play session
1. User taps a track.
2. UI calls playback engine: load queue, start playback.
3. Playback engine emits "track started" event.
4. Session reporter calls `POST /api/v1/events/play` with start metadata.
5. Server creates or updates session, computes session vector, returns session info.
6. Client updates a "current session" provider; UI can display session context (e.g. "tagged: rock, energetic").
7. As playback progresses, session reporter periodically sends progress; on completion or skip, sends terminal event.
### Liking a song
Two buttons in the player UI: **Like** (general) and **Like this vibe** (contextual). Contextual like is only enabled when there is an active session of sufficient length (per server spec, ≥3 tracks in session).
1. User taps Like this vibe.
2. UI optimistically marks the track as contextually liked in this session; shows a brief toast confirming.
3. Client calls `POST /api/v1/likes/contextual`. The server computes the session vector from its own records (the client does not send it — the server is authoritative).
4. On success, the like is confirmed. On failure, the action is queued for retry; UI shows a subtle indicator.
### Starting radio
1. User long-presses a track or taps a "Radio from here" affordance.
2. UI calls `GET /api/v1/radio?seed_track=<id>`.
3. Server returns a queue and optional "suggested additions" (tracks not in library).
4. Playback engine replaces queue; UI renders the queue with suggested additions grouped separately at the bottom with Lidarr-add buttons.
5. As the queue drains, client requests a refresh at 80% consumption.
### Offline playback
1. User goes offline.
2. Client continues playback from cached files.
3. Play/skip events accumulate in the local event queue with their timestamps.
4. On reconnect, event queue is flushed to server in order. Server is expected to backfill events with their original timestamps, reconstruct sessions correctly even retroactively.
5. If a user liked a track offline, the like is queued the same way.
## 6. UI structure
### Screens
- **Sign-in** — server URL, username, password. Remember server. Option to save multiple servers (for dev/prod, single household use).
- **Home** — suggested radios, recently played, recent likes, continue listening. All served by server endpoints.
- **Library** — artists, albums, tracks, playlists browse. Subsonic-standard.
- **Search** — searches server. Also offers "search Lidarr for this" affordance on empty results.
- **Now playing** — full-screen player. Primary affordances: play/pause/skip/seek, like general, like contextual, radio-from-here, add-to-playlist, queue view, session inspector.
- **Queue** — current queue with drag-to-reorder. Shows suggested additions below the real queue.
- **Session inspector** — shows the server's current session vector in human-readable form (recent tracks, detected tags, detected artists). Useful for debugging and for user trust in the "why is this playing" question. Accessible from the now-playing screen.
- **Downloads** — pinned/cached content, cache size, eviction controls.
- **Settings** — account, offline behavior, audio quality, cache size, server info, log out.
### Now-playing affordances (design constraint)
The now-playing screen is where the novel UX lives. It must make the following feel natural:
- A single-tap way to like this song generally.
- A single-tap way to like this song in this context. Visually distinct from general like.
- Clear indication of whether either or both likes are active for the current track.
- An obvious but not-dominant "radio from here" action.
- When playback is inside a radio queue, a "keep this vibe" action that pins the current context, and a "shift" action that mutates it. (Exact semantics tunable; start with "keep" = re-seed radio from current track with current session vector, "shift" = re-seed ignoring session vector.)
The exact visual design is deferred; the spec requires these *capabilities* be reachable without drilling into menus. Buried features won't get used and the contextual like is the whole point.
### Design constraint: don't lie about server state
If an action hasn't succeeded on the server yet, the UI may show the optimistic result but must not present it as fully confirmed. A subtle pending indicator on the like button, for instance. Errors that affect user perception of their library (e.g. a like that never synced) must be surfaceable, not silently dropped.
## 7. Offline cache
### Two kinds of cached content
1. **Transient cache** — populated automatically during playback. LRU-evicted. Size-capped per user config (default 2 GB).
2. **Pinned downloads** — user-explicit "download this album / playlist." Not evicted automatically. Pinned content can be browsed in the Downloads screen.
### Cache decisions
- Cached files are stored at the audio quality the server was asked to deliver. Quality is chosen per user config (e.g. "always original," "transcode to 192k on cellular").
- Cover art cached separately, smaller budget.
- Cache survives app reinstall if possible (Android: scoped external storage; iOS: app container — accepting that iOS reinstall loses it).
- User-visible cache size accounting must be accurate.
### Offline UI
An offline indicator appears in the top chrome when the client can't reach the server. All server-dependent actions show degraded affordances (e.g. smart shuffle shows "shuffling cached tracks only"). Pinned downloads remain fully usable.
## 8. API usage
### Endpoints consumed
From the server's Subsonic surface: `ping`, `getMusicFolders`, `getIndexes`/`getArtists`, `getArtist`, `getAlbum`, `getAlbumList2`, `search3`, `stream`, `getCoverArt`, `getPlaylists`, `getPlaylist`, `createPlaylist`, `updatePlaylist`, `getRandomSongs`, `star`/`unstar` (for general likes — though the extended API's equivalent is preferred for future-proofing).
From the server's extended API: all of `/api/v1/*` described in the server spec. Specifically depended on:
- `POST /api/v1/events/play` (with all event types the server supports)
- `POST /api/v1/likes/contextual`
- `DELETE /api/v1/likes/contextual/:id`
- `GET /api/v1/session/current`
- `GET /api/v1/radio`
- `POST /api/v1/lidarr/search`
- `POST /api/v1/lidarr/add`
- `POST /api/v1/quarantine/:track_id`
- `GET /api/v1/stats/user`
### Auth
Standard Subsonic auth for Subsonic endpoints (token + salt scheme). Bearer token for extended API. Client holds both; transport layer adds them transparently.
### Versioning
Client sends its version in a header on every extended API request. Server may respond with compatibility warnings. Major server API changes bump a version the client checks on startup.
## 9. Reliability
### Event queue durability
Play/skip/like events are written to local SQL before any network attempt. The sync worker drains the queue FIFO with exponential backoff on failures. Events older than 30 days in the queue without successful sync are logged and dropped (with user visibility — a "some events failed to sync" notification).
### Playback robustness
- Network interruption during streaming: if the track is partially buffered, finish it from buffer; on exhaustion, pause and show offline state.
- Track not found (deleted between queue build and playback): skip forward, log, don't crash.
- Corrupt cache file: purge it, redownload or skip.
### Battery and data
- Don't prefetch aggressively on cellular unless user opts in.
- Audio session must release properly when playback ends; no background drain.
## 10. Testing
- Widget tests for the novel UI components (like buttons, session inspector, radio queue).
- Unit tests for the event queue and sync logic — this is where silent bugs lose user trust.
- Integration tests against a local server instance for the full happy-path flows.
- Manual test matrix documented: playback across lock/unlock, app backgrounded, headphone disconnect, network loss mid-stream, receive call mid-stream.
## 11. Implementation order
The client should not start before server step 4 (usable Subsonic baseline). Once that milestone is reached, client work proceeds in parallel:
1. Project skeleton, Riverpod setup, routing, theme.
2. Auth + sign-in screen. Talk to `ping`. Store credentials securely.
3. Library browse: artists, albums, tracks. Read-only against Subsonic API.
4. Playback engine: `just_audio` integration, queue, background audio, lock screen. **Milestone: can play music from the server.**
5. Event ingestion against server (requires server step 5 complete): play start, complete, skip events wired to server.
6. Like buttons (general) wired to Subsonic `star`.
7. Contextual like button + session inspector (requires server step 8).
8. Radio flow (requires server step 11).
9. Lidarr search/add integration (requires server step 12).
10. Offline cache manager.
11. Pinned downloads.
12. Quarantine action from player.
13. Settings polish, stats screen.
14. Packaging, release pipeline.
Steps 5, 7, 8, 9 gate on server features. Plan accordingly; don't block client work on those, sequence around them.
## 12. Open questions to resolve during implementation
- Whether queue state should itself be server-synced (so starting playback on one device resumes on another). Technically appealing but a significant complication — may defer to v2.
- Whether to offer a "this song is playing because of these contextual likes" explanation affordance. Requires server API to expose the reasoning, and it isn't currently in the server spec. Worth considering adding.
- Exact wording and iconography for general vs. contextual like. This needs user testing (even if the user is just you).
- Whether offline-created contextual likes are a good idea at all — the server is the authority on session vectors, and the client's view of a session may drift offline. Possibly contextual likes require connectivity while general likes do not.
- How aggressive to be about prefetching the radio queue in advance for offline continuation.
## 13. Out of scope reminders
If during development any of the following come up, stop and reconsider scope:
- CarPlay / Android Auto native UI
- Chromecast / AirPlay
- Lyrics
- EQ / DSP
- Cross-server support
- Desktop port
- Social / sharing
-342
View File
@@ -1,342 +0,0 @@
# Project Spec: Smart Music Server (working name)
> **History.** This is the original design spec, kept as written. Where it describes an outside library manager doing search, adds and deletes, Minstrel now does that itself.
## 1. Overview
A self-hosted music server and streaming backend built to close a real gap in the self-hosted music ecosystem: **state and intelligence belong on the server, not the client.** Existing Subsonic-compatible servers (Navidrome, Gonic, Airsonic-Advanced) defer all of the "smart" behavior — shuffle logic, radio, play count semantics, like management — to clients. The result is fragmented experience across devices: a song liked on one client is unknown to another; shuffle quality depends on which app you opened; play counts diverge. This project centralizes those decisions on the server so every client sees the same canonical state.
Primary differentiator: a **dual-like model** (general likes vs. contextual likes tied to the recent listening session) combined with **session-aware weighted shuffle** and **"smart radio" playlist generation** that considers user history, session context, and external similarity data from ListenBrainz/MusicBrainz.
The system also integrates with Lidarr for library management and scrobbles to ListenBrainz.
**Scope of this spec:** the backend server. A companion Flutter mobile client is part of the v1 product and is specified in a separate document (`smart-music-client-spec.md`). The two are co-designed: the extended API in this spec is shaped by what the client needs, and the client spec assumes the server features described here. Implementation proceeds in parallel after the server reaches Subsonic-compatible baseline.
## 2. Goals and non-goals
### Goals
- Self-hosted music server running on Linux (primary target: Docker container on Ubuntu/CachyOS).
- OpenSubsonic API compatibility so existing clients (Symfonium, Tempo, Feishin, etc.) work out of the box.
- Server-side smart shuffle that beats random playback in a measurable way for the user.
- Server-side "radio" feature: seed from a track, artist, or album and generate a contextually coherent queue.
- Dual-like model (contextual and general) with retrievable contextual signal.
- Session tracking with play/skip/seek/complete events persisted as first-class data.
- ListenBrainz scrobbling (outbound) and similarity data pull (inbound).
- Lidarr integration: search and add from the server UI; quarantine-based removal workflow (never auto-delete).
- Web UI sufficient to manage the library, likes, Lidarr integration, and system settings.
### Non-goals (v1)
- Multi-tenant / public-facing deployment. Single-household use assumed; multi-user within household is a goal but not hardened against adversarial users.
- Audio fingerprinting / deduplication beyond what MusicBrainz IDs provide.
- Local ML embedding generation. Use ListenBrainz/MusicBrainz similarity data instead.
- Transcoding profiles beyond what OpenSubsonic expects.
- Podcast support.
- Video support.
- Internet radio streaming.
### Explicit non-goals to push back on later
If during implementation there is pressure to add: local audio feature extraction (Essentia/librosa), neural embeddings, or auto-delete-on-dislike — stop and re-scope. These are v2+ discussions.
## 3. Technology choices
- **Language:** Go. Rationale: single-binary deployment, strong concurrency model for streaming + background workers, mature ecosystem for HTTP services, good fit for home lab containerized deployment.
- **HTTP:** Go standard library `net/http` + `chi` or `echo` router. No heavyweight framework.
- **Database:** PostgreSQL. Rationale: the session-vector similarity queries and event aggregations will benefit from real indexing, window functions, and JSONB. SQLite is tempting for single-user deployments but will bottleneck on the analytics queries central to this project's value.
- **Database access:** `sqlc` for typed queries generated from SQL. Migrations via `goose` or `golang-migrate`.
- **Audio/transcoding:** `ffmpeg` as an external binary invoked per stream. Do not bundle or reimplement.
- **Tag reading:** `go-taglib` bindings or `dhowden/tag` for pure-Go tag parsing.
- **MusicBrainz / ListenBrainz:** direct HTTP clients, no wrapper libraries unless a well-maintained one exists at implementation time.
- **Lidarr:** direct HTTP client against Lidarr's v1 API.
- **Web UI:** server-rendered HTML + HTMX for v1. Rationale: avoids a full SPA build pipeline for what is a minority surface. Reconsider for v2 if the UI grows.
- **Auth:** token-based for API clients (OpenSubsonic uses its own auth scheme — support it). Session cookies for the web UI.
- **Deployment:** Dockerfile producing a scratch or distroless image containing the server binary + ffmpeg. Docker Compose example in the repo.
- **Config:** YAML config file with env var override. Sensible defaults.
- **Logging:** structured logging via `log/slog`. Log levels configurable.
## 4. Architecture
### High-level components
1. **Library scanner** — walks configured music folders, parses tags, writes canonical track/artist/album records, resolves MusicBrainz IDs where available.
2. **Stream server** — OpenSubsonic endpoints for browsing, streaming, transcoding on demand.
3. **Event ingestion** — records play/skip/seek/complete events from clients, groups them into sessions.
4. **Session service** — maintains the notion of a "current session" per user, computes session vectors (the previous-N tracks and their aggregate features), handles session timeouts.
5. **Recommendation engine** — the core value layer. Implements weighted shuffle, radio generation, and contextual-like retrieval. Pure functions operating on data from the DB and similarity service.
6. **Similarity service** — wraps ListenBrainz similarity API calls with aggressive caching. Local DB stores similarity edges.
7. **Scrobble worker** — batches completed plays and forwards to ListenBrainz.
8. **Lidarr integration** — adapter for search, add, quarantine operations.
9. **Web UI** — thin surface over the above.
10. **Extended API** — non-Subsonic endpoints for features Subsonic clients cannot express (contextual likes, session inspection, Lidarr actions).
### Key architectural decisions
- **OpenSubsonic compatibility first, extensions second.** All existing Subsonic features must work with third-party clients. The novel features live in a parallel API namespace (e.g. `/api/v1/`) that the future custom client will use.
- **Events are append-only.** The events table is the source of truth for listening history. All aggregates (play counts, skip ratios, session vectors) are computed from it. This enables retroactive model changes without data loss.
- **Session computation is online but session similarity is precomputed.** When a track is played, its "session vector at time of play" is computed and stored on the play event. This makes contextual-like retrieval a straightforward query rather than a replay of history.
- **Recommendation is a pure function of DB state.** No in-memory state that would be lost on restart. Caches are explicit and rebuildable.
### Request lifecycle (streaming)
Client → auth check → track lookup → (optional) transcode ffmpeg pipeline → byte range response. Play event recorded when client reports progress beyond a threshold (see §6).
### Request lifecycle (smart shuffle / radio)
Client → auth → `getRandomSongs` (Subsonic) or `/api/v1/radio` (extended) → recommendation engine → query composer pulls candidate set → weighting applied → ranked list returned.
## 5. Data model
The schema below is the v1 target. Prefer explicit, descriptive column names over abbreviations. All timestamps are `timestamptz`.
### Core library tables
**`artists`** — id (uuid), name, sort_name, mbid (nullable, unique when present), created_at, updated_at.
**`albums`** — id, title, sort_title, artist_id, release_date, mbid, cover_art_path, created_at, updated_at.
**`tracks`** — id, title, album_id, artist_id, track_number, disc_number, duration_ms, file_path (unique), file_size, file_format, bitrate, mbid, genre (denormalized text for fast filtering), added_at, updated_at.
**`users`** — id, username, password_hash, api_token, is_admin, created_at.
### Event and session tables
**`play_events`** — id, user_id, track_id, started_at, ended_at (nullable until completion reported), duration_played_ms, completion_ratio (computed: duration_played_ms / track.duration_ms), was_skipped (bool), client_id (nullable), session_id, session_vector_at_play (jsonb — see §6), scrobbled_at (nullable).
**`skip_events`** — id, user_id, track_id, skipped_at, position_ms, session_id. (Subset of play_events where was_skipped=true, but kept as a separate index-friendly table for skip analytics.)
**`sessions`** — id, user_id, started_at, ended_at (nullable), last_event_at, track_count, client_id.
### Like tables
**`general_likes`** — user_id, track_id, liked_at. Primary key (user_id, track_id). A single row per user-track pair. Unliking deletes the row.
**`contextual_likes`** — id, user_id, track_id, liked_at, session_vector (jsonb, snapshot at time of like), session_id. Multiple rows per user-track pair are allowed and expected — each represents a like in a specific context.
**`artist_preferences`** — user_id, artist_id, weight (float, -1.0 to 1.0), updated_at. Aggregate signal, computed from likes/skips but directly adjustable by user.
### Similarity tables
**`track_similarity`** — track_a_id, track_b_id, score (float), source (enum: listenbrainz, musicbrainz_tag, user_cooccurrence), fetched_at. Primary key (track_a_id, track_b_id, source).
**`artist_similarity`** — analogous to track_similarity.
### Integration tables
**`lidarr_quarantine`** — id, track_id, requested_by_user_id, reason (enum: wrong_match, low_quality, disliked, other), requested_at, resolved_at (nullable), resolution (enum: deleted, restored, nullable).
**`scrobble_queue`** — id, play_event_id, queued_at, attempts, last_attempt_at, last_error (nullable), submitted_at (nullable).
### Indexes (non-exhaustive)
- `play_events (user_id, started_at DESC)` for session assembly.
- `play_events (user_id, track_id)` for per-track history.
- `contextual_likes USING gin (session_vector)` for vector similarity queries.
- `track_similarity (track_a_id, score DESC)` for fast candidate generation.
## 6. Core algorithms
### Session definition
A session is a contiguous sequence of plays by a single user with no gap longer than **30 minutes** between events. The timeout is configurable. A new play event more than 30 minutes after the last event in a session starts a new session.
### Session vector
At the moment a track begins playing, compute a vector representing the session context. v1 definition:
- Last N = 5 tracks played in the current session (if fewer than 5, use what exists; if session just started, vector is marked `seed` and excluded from contextual retrieval until session has ≥3 tracks).
- For each of those N tracks, collect: artist_id, genre tags, MusicBrainz tags if available, approximate BPM/energy if available (optional, skip if not).
- Aggregate into a JSONB structure:
- `artists`: set of artist_ids
- `tags`: bag-of-tags with counts
- `recent_track_ids`: ordered list of the N track ids
- Store this JSONB on the play event and on any contextual_like created during this track.
### Session similarity
Two session vectors are compared via weighted Jaccard similarity on the `tags` and `artists` fields. The exact weights should be tunable via config (start with: tags 0.7, artists 0.3). This is simple and good enough for v1; upgrade paths include cosine similarity on tag vectors and eventually audio embeddings.
### Play vs. skip classification
A play event is a **skip** if ended before 50% of track duration AND before 30 seconds of playback. Otherwise it's a **play**. A **complete play** is ≥ 90% of duration. Thresholds configurable.
### Weighted shuffle
Given a candidate set (e.g. all tracks, or all tracks in an album/playlist/genre), compute a score per track:
```
score = base_weight
+ (is_general_liked ? LIKE_BOOST : 0)
+ (contextual_match_score * CONTEXT_WEIGHT)
+ (recency_decay(last_played_at) * RECENCY_WEIGHT)
- (skip_ratio * SKIP_PENALTY)
- (recently_played_penalty)
+ small_random_jitter
```
- `contextual_match_score` = max session similarity between the current session vector and any contextual_like session vector for this track, for this user.
- `recency_decay` returns a value that is high when a track hasn't been played recently and low when it has, but not infinite for never-played tracks (cold-start handling).
- `recently_played_penalty` hard-suppresses anything played in the last hour to prevent immediate repeats.
Weights are in config. Ship with reasonable defaults and document how to tune them.
### Radio generation
Given a seed (track, artist, or album):
1. Build a candidate pool from: (a) ListenBrainz similar tracks to the seed, (b) tracks by similar artists, (c) tracks sharing MusicBrainz tags, (d) user's general likes matching those tags.
2. Filter to the user's library (Lidarr-integrated libraries may choose to also propose additions — see §7).
3. Apply weighted shuffle scoring on the pool.
4. Return an ordered queue of configurable length (default 50).
5. Refresh policy: regenerate when the queue is 80% consumed, biased against tracks already played in this radio session.
### Scrobbling
A play event is eligible for scrobbling when:
- completion_ratio ≥ 0.5, OR
- duration_played_ms ≥ 4 minutes
(These are ListenBrainz's recommended thresholds; confirm at implementation time.) Eligible events enter the scrobble_queue and are batched by the scrobble worker. Retries with exponential backoff on network or 5xx errors. Permanent failures (4xx, malformed) are logged and the row is marked failed.
### ListenBrainz similarity ingest
On library scan completion, and periodically thereafter, for tracks with MBIDs:
- Query ListenBrainz similarity endpoints in batches.
- Populate `track_similarity` and `artist_similarity`.
- Respect ListenBrainz rate limits. Cache aggressively; re-fetch no more than weekly per track.
## 7. Lidarr integration
### Search and add
Expose an endpoint on the extended API that proxies Lidarr's search. Users can initiate an add from the web UI. The server calls Lidarr with the user's configured root folder and quality profile. After Lidarr reports the download complete, the next library scan picks up the file.
### Quarantine (never auto-delete)
When a user flags a track as wrong/low-quality/disliked:
1. A `lidarr_quarantine` row is created.
2. The track is hidden from playback for that user (soft-hide; other users in the household still see it).
3. The file is NOT deleted.
4. An admin UI lists quarantined tracks. An admin can choose to delete (via Lidarr's delete endpoint) or restore.
**Rationale:** a one-tap deletion of a 40MB FLAC rip during a user-hostile moment is unacceptable. Quarantine is cheap; deletion is destructive. This is the correct tradeoff even though it adds a UI step.
### Radio with add-suggestions
When generating a radio queue, if the server has similarity data pointing to tracks not in the library AND Lidarr integration is enabled, surface these as "suggested additions" in the queue response (separate field, not interleaved with playable tracks). The user can one-tap add-to-Lidarr from the client.
## 8. API surface
### Subsonic / OpenSubsonic endpoints
Implement the full OpenSubsonic spec as of implementation time. At minimum: `ping`, `getLicense`, `getMusicFolders`, `getIndexes`, `getArtists`, `getArtist`, `getAlbum`, `getAlbumList2`, `getSong`, `search3`, `stream`, `download`, `scrobble`, `star`, `unstar`, `getStarred2`, `getRandomSongs`, `getSimilarSongs2`, `createPlaylist`, `getPlaylists`, `getPlaylist`, `updatePlaylist`, `deletePlaylist`, `getCoverArt`.
Map Subsonic concepts onto the extended model:
- Subsonic `star` → creates a `general_likes` row.
- Subsonic `scrobble` with `submission=true` → creates a play_event.
- Subsonic `scrobble` with `submission=false` → updates now-playing state.
- Subsonic `getRandomSongs` → invokes weighted shuffle.
- Subsonic `getSimilarSongs2` → invokes a simplified radio generation.
### Extended API (`/api/v1/`)
- `POST /api/v1/events/play` — richer play event reporting (includes seek events, client metadata).
- `POST /api/v1/likes/contextual` — create a contextual like. Server computes session vector.
- `DELETE /api/v1/likes/contextual/:id` — remove a specific contextual like.
- `GET /api/v1/session/current` — inspect the caller's current session.
- `GET /api/v1/radio` — generate radio queue with explicit parameters (seed type, pool size, weights override).
- `POST /api/v1/lidarr/search` — proxy search.
- `POST /api/v1/lidarr/add` — request add.
- `POST /api/v1/quarantine/:track_id` — flag a track.
- `POST /api/v1/quarantine/:id/resolve` — admin resolution.
- `GET /api/v1/stats/user` — listening stats for the caller.
All extended endpoints use JSON request/response, not Subsonic's XML/JSON hybrid.
## 9. Web UI
Server-rendered HTML + HTMX. Pages needed:
- Login.
- Library overview (artist/album/track browse, mostly a fallback — real browsing happens in clients).
- Now playing / current session view.
- Likes management (both lists, with ability to see contextual likes grouped by detected "contexts").
- Lidarr search and add.
- Quarantine admin.
- User settings (scrobble target, shuffle weight overrides).
- Server settings (library paths, scan triggers, integration config) — admin only.
- Listening stats.
Design constraint: functional and legible over fancy. The custom client is where UX effort goes.
## 10. Configuration
YAML config at `/etc/smartmusic/config.yaml` by default, overridable with `--config` flag and env vars (prefixed `SMARTMUSIC_`).
Required config sections:
- `server` (listen address, external URL)
- `database` (postgres connection)
- `library` (scan paths, scan schedule)
- `transcoding` (ffmpeg path, default profiles)
- `listenbrainz` (token, enabled)
- `lidarr` (url, api key, enabled, default root folder, default quality profile)
- `shuffle` (weight overrides)
- `session` (timeout minutes, N for session vector)
- `auth` (token lifetime, admin bootstrap)
## 11. Testing
- Unit tests for the recommendation engine with fixed inputs / expected rankings.
- Unit tests for session boundary logic.
- Integration tests for the Subsonic endpoint compatibility using a known-good client's test suite if one exists, otherwise golden-response tests.
- Integration test harness with a Postgres testcontainer.
- Load test for the stream endpoint under concurrent clients.
Target: ≥70% coverage on the recommendation engine and session code specifically. Do not chase coverage on the Subsonic handler code — those tests should be scenario-driven.
## 12. Operational concerns
- **Library scan** should be incremental (by mtime) with a full-rescan option. Large libraries (>100k tracks) should scan in under 10 minutes incremental, under 2 hours full.
- **Streaming** should support byte-range requests correctly for seek support.
- **Transcoding** results should be cacheable on disk with LRU eviction, configurable cache size.
- **Backup** guidance: the Postgres DB is the only stateful component other than the music files themselves. Document pg_dump-based backup in the README.
- **Metrics:** expose `/metrics` in Prometheus format. Key metrics: active streams, scan duration, scrobble queue depth, recommendation latency.
## 13. Implementation order
This is the suggested sequencing for the server. The mobile client is specified separately and its work runs in parallel starting from step 5, once the server has a verifiable Subsonic baseline.
1. Project skeleton, config loading, logging, DB migrations framework.
2. Core schema (library tables, users).
3. Library scanner — walk, tag parse, write records.
4. Basic Subsonic API subset: auth, browse, stream. Verify against a real client (Symfonium or Feishin) end-to-end. **Milestone: usable Subsonic server.**
5. Event ingestion + session service. *(Client work can begin here against a stubbed API.)*
6. Like tables + Subsonic star/unstar wired to general_likes.
7. Recommendation engine v1: weighted shuffle without contextual signal yet.
8. Contextual likes + session vectors + contextual signal in recommendation.
9. ListenBrainz scrobble worker.
10. ListenBrainz similarity ingest.
11. Radio generation.
12. Lidarr integration (search, add, quarantine).
13. Web UI.
14. Metrics, packaging, Docker image, documentation.
Each step should produce a runnable, testable increment. Don't implement step N+1 before step N is verified working. Server API changes discovered during client development should feed back into this spec and be implemented as they come up, rather than batched.
## 14. Out of scope reminders
If during development any of the following come up, stop and reconsider scope:
- Local audio feature extraction
- Neural network anything
- Adversarial multi-user hardening
- Podcast / video / internet radio
- Custom audio format support beyond what ffmpeg handles natively
## 15. Open questions to resolve during implementation
- Exact session vector JSONB schema — finalize after looking at real MusicBrainz tag data.
- Whether to store the `session_vector_at_play` on every play event or only on events that generate contextual likes. Storage cost vs. query simplicity tradeoff.
- Whether `getRandomSongs` from Subsonic should use the full weighted shuffle or a lighter version, since some clients call it on a loop.
- Handling of tracks without MBIDs (a significant fraction of many libraries). They can't participate in similarity-based radio. Decide whether to fall back to artist/genre/tag similarity or exclude them from radio entirely.
- Whether contextual likes should decay over time (old contextual likes become weaker signal).
-180
View File
@@ -1,180 +0,0 @@
package acquire
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/downloader"
"git.fabledsword.com/bvandeusen/minstrel/internal/exchange"
"git.fabledsword.com/bvandeusen/minstrel/internal/indexer"
"git.fabledsword.com/bvandeusen/minstrel/internal/prowlarr"
)
func validUpdate() Update {
return Update{Label: "Prowlarr", BaseURL: "http://prowlarr:9696", TimeoutMs: 30000, LocalPath: "/downloads", SearchesPerHour: 120}
}
func TestUpdateValidate(t *testing.T) {
if err := validUpdate().validate(); err != nil {
t.Fatalf("a valid form: %v", err)
}
for name, tc := range map[string]struct {
edit func(*Update)
field string
}{
"no name": {func(u *Update) { u.Label = "" }, "label"},
"switched on with no address": {func(u *Update) { u.Enabled, u.BaseURL = true, "" }, "base_url"},
"an address with no scheme": {func(u *Update) { u.BaseURL = "prowlarr:9696" }, "base_url"},
"a timeout too short": {func(u *Update) { u.TimeoutMs = 10 }, "timeout_ms"},
"a relative downloads folder": {func(u *Update) { u.LocalPath = "downloads" }, "local_path"},
"a relative client folder": {func(u *Update) { u.RemotePath = "data" }, "remote_path"},
"too many searches": {func(u *Update) { u.SearchesPerHour = 4000 }, "searches_per_hour"},
} {
u := validUpdate()
tc.edit(&u)
var invalid *InvalidError
if err := u.validate(); !errors.As(err, &invalid) || invalid.Field != tc.field {
t.Errorf("%s: err = %v, want an InvalidError on %s", name, err, tc.field)
}
}
// Switched off, an empty address is a row still being set up.
u := validUpdate()
u.BaseURL = ""
if err := u.validate(); err != nil {
t.Errorf("switched off with no address: %v", err)
}
}
func TestSourceFor_BuildsTheClientTheProtocolNames(t *testing.T) {
for protocol, check := range map[string]func(Source) bool{
ProtocolProwlarr: func(s Source) bool { _, ok := s.Search.(*prowlarr.Client); return ok && s.Fetch != nil },
ProtocolTorznab: func(s Source) bool { _, ok := s.Search.(*indexer.Torznab); return ok && s.Fetch != nil },
// Exchange's results are all magnets: nothing to fetch through it.
ProtocolExchange: func(s Source) bool { _, ok := s.Search.(*exchange.Client); return ok && s.Fetch == nil },
} {
src := SourceFor(dbq.AcquisitionService{Code: protocol, Protocol: protocol, SearchesPerHour: 7})
if !check(src) || src.Code != protocol || src.PerHour != 7 {
t.Errorf("%s: source %+v", protocol, src)
}
}
}
func TestJobs_AnExchangeDoesWhatItsSwitchesAllow(t *testing.T) {
ex := dbq.AcquisitionService{Kind: KindDownload, Protocol: ProtocolExchange, ServesSearch: true}
if !Searches(ex) || Fetches(ex) {
t.Error("an exchange with only search on should search and not fetch")
}
// A qBittorrent's switches mean nothing: it fetches, whatever they say.
qb := dbq.AcquisitionService{Kind: KindDownload, Protocol: ProtocolQBittorrent, ServesSearch: true}
if Searches(qb) || !Fetches(qb) {
t.Error("a qBittorrent fetches and never searches")
}
}
func TestTest_NoAddressIsNothingToReach(t *testing.T) {
r := Test(context.Background(), dbq.AcquisitionService{Protocol: ProtocolProwlarr, Kind: KindSearch})
if r.OK || !strings.Contains(r.Detail, "No address") {
t.Fatalf("result = %+v", r)
}
}
func TestTest_SearchReportsResultsAndARefusedKey(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Api-Key") != "good" {
w.WriteHeader(http.StatusUnauthorized)
return
}
_, _ = w.Write([]byte(`[{"title": "Radiohead - OK Computer"}]`))
}))
defer srv.Close()
row := dbq.AcquisitionService{Kind: KindSearch, Protocol: ProtocolProwlarr, BaseUrl: srv.URL, ApiKey: "good", TimeoutMs: 5000}
if r := Test(context.Background(), row); !r.OK || !strings.Contains(r.Detail, "1 results") {
t.Errorf("a working key: %+v", r)
}
row.ApiKey = "bad"
if r := Test(context.Background(), row); r.OK || !strings.Contains(r.Detail, "refused") {
t.Errorf("a refused key: %+v", r)
}
}
// fakeExchange answers the three native APIs.
func fakeExchange(t *testing.T) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/downloads":
_, _ = w.Write([]byte(`{"enabled": true, "running": true, "inbound_conns": 3, "downloads": []}`))
case r.URL.Path == "/api/search":
_, _ = w.Write([]byte(`{"total": 0, "results": []}`))
case strings.HasPrefix(r.URL.Path, "/api/torrents/"):
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error": "unknown torrent"}`))
default:
w.WriteHeader(http.StatusNotFound)
}
}))
t.Cleanup(srv.Close)
return srv
}
func TestTest_AnExchangeReportsEachJobSwitchedOn(t *testing.T) {
srv := fakeExchange(t)
row := dbq.AcquisitionService{
Kind: KindDownload, Protocol: ProtocolExchange, BaseUrl: srv.URL, TimeoutMs: 5000,
ServesDownloads: true, ServesSearch: true, ServesEnrichment: true, LocalPath: t.TempDir(),
}
r := Test(context.Background(), row)
if !r.OK {
t.Fatalf("all three jobs: %+v", r)
}
for _, job := range []string{"Downloads:", "Search:", "Release details:"} {
if !strings.Contains(r.Detail, job) {
t.Errorf("detail %q does not report %s", r.Detail, job)
}
}
row.ServesDownloads, row.ServesEnrichment = false, false
if r := Test(context.Background(), row); strings.Contains(r.Detail, "Downloads:") || !strings.Contains(r.Detail, "Search:") {
t.Errorf("only search on: %+v", r)
}
row.ServesSearch = false
if r := Test(context.Background(), row); r.OK || !strings.Contains(r.Detail, "switched off") {
t.Errorf("every job off: %+v", r)
}
}
func TestTest_ADownloadClientNeedsAFolderMinstrelCanSee(t *testing.T) {
srv := fakeExchange(t)
row := dbq.AcquisitionService{
Kind: KindDownload, Protocol: ProtocolExchange, BaseUrl: srv.URL, TimeoutMs: 5000,
ServesDownloads: true, Category: DefaultCategory,
LocalPath: filepath.Join(t.TempDir(), "not-mounted"),
}
r := Test(context.Background(), row)
if r.OK || !strings.Contains(r.Detail, "cannot see its downloads folder") {
t.Fatalf("a missing folder: %+v", r)
}
row.LocalPath = t.TempDir()
if r := Test(context.Background(), row); !r.OK || !strings.Contains(r.Detail, `"minstrel" category`) {
t.Errorf("a visible, writable folder: %+v", r)
}
}
func TestDownloadClient_WrapsThePathMapping(t *testing.T) {
d, err := DownloadClient(dbq.AcquisitionService{Protocol: ProtocolQBittorrent, LocalPath: "/downloads", RemotePath: "/data"})
if err != nil {
t.Fatal(err)
}
if _, plain := d.(*downloader.Client); plain {
t.Error("a row naming two folders should come back wrapped in its mapping")
}
if _, err := DownloadClient(dbq.AcquisitionService{Protocol: ProtocolProwlarr}); err == nil {
t.Error("a search protocol is not a download client")
}
}
-45
View File
@@ -1,45 +0,0 @@
package acquire
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/release"
)
// Build makes a Service from the settings as they stand: every enabled
// search source behind one paced Fanout, the first enabled download client,
// and the quality profile. Built afresh for each pass and each request, so a
// changed setting takes effect on the next one.
func Build(ctx context.Context, pool *pgxpool.Pool) (*Service, dbq.AcquisitionSetting, error) {
q := dbq.New(pool)
settings, err := q.GetAcquisitionSettings(ctx)
if err != nil {
return nil, settings, fmt.Errorf("acquire: read settings: %w", err)
}
sources, err := Sources(ctx, pool)
if err != nil {
return nil, settings, fmt.Errorf("acquire: read search sources: %w", err)
}
clients, err := q.ListUsableAcquisitionServices(ctx, JobDownload)
if err != nil {
return nil, settings, fmt.Errorf("acquire: read download clients: %w", err)
}
s := &Service{Profile: release.NewProfile(settings.AllowedQualities), Memory: NewMemory(pool)}
fan := &Fanout{Sources: sources, Pace: SearchPace}
if len(sources) > 0 {
s.Search = fan
}
if len(clients) > 0 {
row := clients[0]
client, err := DownloadClient(row)
if err != nil {
return nil, settings, fmt.Errorf("acquire: download client %s: %w", row.Code, err)
}
s.Grabber = &Downloader{Client: client, Code: row.Code, Landing: row.LocalPath, Fetch: fan}
}
return s, settings, nil
}
-164
View File
@@ -1,164 +0,0 @@
package acquire
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"git.fabledsword.com/bvandeusen/minstrel/internal/indexer"
)
// Searching every source at once. A source that is down narrows a search rather
// than failing it: the results come back with the list of who did not answer.
// SourceFailure is one source that could not be reached.
type SourceFailure struct {
Code string
Label string
Err error
}
// PartialError is a search that reached some sources and not others. It is
// returned alongside the results, not instead of them.
type PartialError struct {
Failures []SourceFailure
// Answered is how many sources did answer. Zero means the search failed.
Answered int
}
func (e *PartialError) Error() string {
if e == nil || len(e.Failures) == 0 {
return "some sources did not answer"
}
parts := make([]string, 0, len(e.Failures))
for _, f := range e.Failures {
parts = append(parts, fmt.Sprintf("%s: %s", f.Label, indexer.FirstLine(f.Err.Error())))
}
return "some sources did not answer — " + strings.Join(parts, "; ")
}
// Unwrap lets errors.Is find indexer.ErrUnreachable through a partial failure.
func (e *PartialError) Unwrap() []error {
if e == nil {
return nil
}
out := make([]error, 0, len(e.Failures))
for _, f := range e.Failures {
out = append(out, f.Err)
}
return out
}
// Fanout searches every source and merges what comes back. It is both the
// Searcher and the Fetcher, routing a .torrent fetch to the source that
// offered the result.
type Fanout struct {
// Sources in code order: the fold keeps a duplicate's first arrival, so
// the order decides which source a grab is fetched through.
Sources []Source
// Pace spaces each source's searches. Nil paces nothing.
Pace *Pacer
}
// Search asks every source concurrently. Each client bounds its own call by
// its configured timeout, so there is no shared deadline here.
func (f *Fanout) Search(ctx context.Context, query indexer.Query) ([]indexer.Result, error) {
if f == nil || len(f.Sources) == 0 {
return nil, indexer.ErrUnconfigured
}
found := make([][]indexer.Result, len(f.Sources))
errs := make([]error, len(f.Sources))
var wg sync.WaitGroup
for i, src := range f.Sources {
if src.Search == nil {
continue
}
f.Pace.spend(src)
wg.Add(1)
go func(i int, src Source) {
defer wg.Done()
found[i], errs[i] = src.Search.Search(ctx, query)
}(i, src)
}
wg.Wait()
out := make([]indexer.Result, 0, 32)
var failures []SourceFailure
answered, unconfigured := 0, 0
for i, src := range f.Sources {
if src.Search == nil {
continue
}
if errors.Is(errs[i], indexer.ErrUnconfigured) {
unconfigured++
continue
}
if rl, ok := indexer.AsRateLimited(errs[i]); ok {
f.Pace.hold(src.Code, rl)
}
if errs[i] != nil {
failures = append(failures, SourceFailure{Code: src.Code, Label: src.Label, Err: errs[i]})
continue
}
answered++
for j := range found[i] {
if found[i][j].Source == "" {
found[i][j].Source = src.Code
}
}
out = append(out, found[i]...)
}
switch {
case answered == 0 && len(failures) > 0:
return nil, &PartialError{Failures: failures}
case len(failures) > 0:
return out, &PartialError{Failures: failures, Answered: answered}
case answered == 0 && unconfigured > 0:
return nil, indexer.ErrUnconfigured
}
return out, nil
}
// Download fetches a result's .torrent from the source that offered it: a
// Prowlarr link carries Prowlarr's key and only Prowlarr can redeem it.
func (f *Fanout) Download(ctx context.Context, r indexer.Result) ([]byte, error) {
if f == nil {
return nil, indexer.ErrUnconfigured
}
for _, src := range f.Sources {
if src.Code != r.Source {
continue
}
if src.Fetch == nil {
return nil, fmt.Errorf("%w: %s cannot fetch torrent files", indexer.ErrUnconfigured, src.Label)
}
return src.Fetch.Download(ctx, r)
}
if r.Source == "" {
return nil, fmt.Errorf("%w: this result does not say which source it came from", indexer.ErrUnconfigured)
}
return nil, fmt.Errorf("%w: %q is no longer a configured source", indexer.ErrUnconfigured, r.Source)
}
// Narrowing is one source that did not answer, as a page shows it.
type Narrowing struct {
Source string `json:"source"`
Label string `json:"label"`
Reason string `json:"reason"`
}
// narrowings reads a PartialError out of err, and whether any source
// answered. Nil when err is not a partial failure.
func narrowings(err error) ([]Narrowing, bool) {
var partial *PartialError
if !errors.As(err, &partial) || len(partial.Failures) == 0 {
return nil, false
}
out := make([]Narrowing, 0, len(partial.Failures))
for _, f := range partial.Failures {
out = append(out, Narrowing{Source: f.Code, Label: f.Label, Reason: indexer.FirstLine(f.Err.Error())})
}
return out, partial.Answered > 0
}
-338
View File
@@ -1,338 +0,0 @@
package acquire
import (
"context"
"errors"
"path"
"strings"
"sync"
"time"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/downloader"
"git.fabledsword.com/bvandeusen/minstrel/internal/indexer"
"git.fabledsword.com/bvandeusen/minstrel/internal/release"
)
// Taking a release. One live grab per want: a second is tie-broken against
// the download already running.
// Tag goes on every torrent Minstrel adds, so they can be told apart from
// anything else in the client.
const Tag = "minstrel"
// MissingClient is Taken.Missing when no download client is set up.
const MissingClient = "download_client"
// nearlyDone is how far along a running download stays whatever would
// replace it.
const nearlyDone = 0.9
// Downloader is the grab half of a Service.
type Downloader struct {
Client downloader.Driver
// Code is the client's acquisition_services row.
Code string
// Landing is the client's downloads folder as Minstrel sees it; each
// grab lands in a folder of its own under it.
Landing string
// Fetch gets a result's .torrent from the source that offered it.
Fetch Fetcher
}
// Origin says who took a release.
type Origin struct {
By string // OriginSchedule or OriginOperator
User pgtype.UUID
}
// Contest is how a grab fared against the download already running.
type Contest struct {
// Kept: the running one stays and this grab was not made. Replaced:
// this grab took its place.
Kept, Replaced bool
Reason string
Rival dbq.Grab
}
// Taken is what came of a grab.
type Taken struct {
Chosen *Candidate
// Added is the only field that means a download started.
Added bool
SavePath string
Grab dbq.Grab
// Gone: the search no longer offers the release.
Gone bool
// Refused: not taken; the reason is on Chosen.
Refused bool
// Unconfigured: Missing names what is not set up ("" for search).
Unconfigured bool
Missing string
Contest *Contest
Error string
}
// Take searches again and grabs the candidate named by key: a person's
// grab. Searching again keeps the indexer's download link (which can carry
// its key) on the server, and finds a release gone since it was shown.
// force takes what the verdict would not.
func (s *Service) Take(ctx context.Context, want Want, key string, force bool, origin Origin) Taken {
if s.Grabber == nil {
return Taken{Unconfigured: true, Missing: MissingClient}
}
found := s.For(ctx, want)
switch {
case found.Unconfigured:
return Taken{Unconfigured: true}
case found.Error != "":
return Taken{Error: found.Error}
}
chosen := pick(found.Candidates, key)
if chosen == nil {
return Taken{Gone: true}
}
return s.Grab(ctx, want, chosen, found.Candidates, force, origin)
}
// Grab hands a judged candidate to the download client. The schedule calls
// it with the candidate it has just judged; Take calls it after searching
// again.
func (s *Service) Grab(ctx context.Context, want Want, chosen *Candidate, all []Candidate, force bool, origin Origin) Taken {
out := Taken{Chosen: chosen}
if s.Grabber == nil || s.Grabber.Client == nil {
out.Unconfigured, out.Missing = true, MissingClient
return out
}
if chosen.Verdict == Blocked || (chosen.Verdict != Grab && !force) {
out.Refused = true
return out
}
unlock := lockWant(want.ID)
defer unlock()
contest := s.contest(ctx, want, chosen, all, origin)
if contest != nil && contest.Kept {
out.Contest = contest
return out
}
add := downloader.Add{Magnet: chosen.Source.Magnet, Tags: []string{Tag}}
hash := chosen.InfoHash
if add.Magnet == "" {
if s.Grabber.Fetch == nil {
out.Error = "This release is a .torrent link, and nothing is set up to fetch it."
return out
}
body, err := s.Grabber.Fetch.Download(ctx, chosen.Source)
if magnet, ok := indexer.AsMagnet(err); ok {
add.Magnet, err = magnet, nil
}
if err != nil {
out.Error = indexer.FirstLine(err.Error())
return out
}
if add.Magnet == "" {
add.Torrent = body
if meta, err := release.ParseTorrent(body); err == nil {
if hash == "" {
hash = meta.InfoHash
}
if refused := s.judgeFiles(ctx, want, chosen, hash, meta.Files, force); refused {
out.Refused = true
return out
}
}
}
}
if hash == "" && add.Magnet != "" {
hash = indexer.MagnetHash(add.Magnet)
}
add.SavePath = landingFor(s.Grabber.Landing, hash, chosen.Name)
err := s.Grabber.Client.AddTorrent(ctx, add)
if errors.Is(err, downloader.ErrDuplicate) && s.heldElsewhere(ctx, hash) {
why := "Already in the download client outside Minstrel's category, where Minstrel cannot follow it (" +
strings.TrimPrefix(indexer.FirstLine(err.Error()), downloader.ErrDuplicate.Error()+": ") + ")"
if force {
out.Error = why + "."
return out
}
set(chosen, Blocked, Hard, CodeBlocked, why+".")
if s.Memory != nil && hash != "" {
_ = s.Memory.Block(ctx, dbq.BlockReleaseParams{
InfoHash: hash, Name: chosen.Name, Reason: BlockGone, Detail: why + ".", WantID: want.ID,
ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(GoneBlock), Valid: true},
})
}
out.Refused = true
return out
}
if err != nil && !errors.Is(err, downloader.ErrDuplicate) {
if errors.Is(err, downloader.ErrUnconfigured) {
out.Unconfigured, out.Missing = true, MissingClient
} else {
out.Error = indexer.FirstLine(err.Error())
}
return out
}
out.Added, out.SavePath = true, add.SavePath
if s.Memory == nil {
return out
}
var replaced pgtype.UUID
why := ""
if contest != nil && contest.Replaced {
out.Contest = contest
replaced, why = contest.Rival.ID, "Replaced by "+chosen.Name+": "+contest.Reason+"."
}
g, err := s.Memory.Grabbed(ctx, dbq.InsertGrabParams{
WantID: want.ID, InfoHash: hash, Name: chosen.Name, Key: Key(*chosen), Indexer: chosen.Indexer,
Source: chosen.Source.Source, Client: s.Grabber.Code, SavePath: add.SavePath,
Quality: string(chosen.Tier), Origin: origin.By, Forced: force, GrabbedBy: origin.User,
}, replaced, why)
if err != nil {
out.Error = "The download started, but could not be recorded: " + indexer.FirstLine(err.Error())
return out
}
out.Grab = g
// Removed only after the new download was added and recorded, so a
// failure never leaves the want with nothing running.
if replaced.Valid && contest.Rival.InfoHash != "" {
if err := s.Grabber.Client.Delete(ctx, true, contest.Rival.InfoHash); err != nil {
contest.Reason += ". The download it replaced could not be removed from the client: " + indexer.FirstLine(err.Error())
}
}
return out
}
// heldElsewhere reports whether a release the client says it already holds is
// one it does not list for Minstrel: held under another category. Recorded
// as a grab, it would read as gone half an hour later and be taken again,
// every pass. A client that
// cannot answer now is given the benefit of the doubt, as the add was.
func (s *Service) heldElsewhere(ctx context.Context, hash string) bool {
if hash == "" {
return false
}
listed, err := s.Grabber.Client.Torrents(ctx, indexer.NormalizeHash(hash))
return err == nil && len(listed) == 0
}
// judgeFiles judges a chosen release again on its .torrent's file list, and
// sets it aside when the files say it is not the album, so no later search
// offers it again. force still takes it.
func (s *Service) judgeFiles(ctx context.Context, want Want, chosen *Candidate, hash string, files []release.File, force bool) bool {
chosen.Files = files
if chosen.FilesCount == 0 {
chosen.FilesCount = len(files)
}
veto, reason, _ := release.JudgeFiles(want.Want, files)
if veto == "" || force {
return false
}
set(chosen, Rejected, Hard, veto, reason)
if s.Memory != nil && hash != "" {
_ = s.Memory.Block(ctx, dbq.BlockReleaseParams{
InfoHash: hash, Name: chosen.Name, Reason: BlockFiles, Detail: reason, WantID: want.ID,
})
}
return true
}
var wantLocks sync.Map // want id → *sync.Mutex
// lockWant settles two grabs for one want one after the other. The
// one-live-grab index is the backstop for anything outside this process.
func lockWant(id pgtype.UUID) func() {
if !id.Valid {
return func() {}
}
m, _ := wantLocks.LoadOrStore(id.Bytes, &sync.Mutex{})
mu := m.(*sync.Mutex)
mu.Lock()
return mu.Unlock
}
// contest settles a grab against the download running for its want: a
// person's grab beats the schedule's; between two of a kind the better
// candidate wins; a tie, a download nearly done, or one that cannot be
// removed stays. Nil when nothing is running.
func (s *Service) contest(ctx context.Context, want Want, chosen *Candidate, all []Candidate, origin Origin) *Contest {
if s.Memory == nil || !want.ID.Valid {
return nil
}
running, ok, err := s.Memory.LiveGrab(ctx, want.ID)
if err != nil || !ok {
return nil
}
c := &Contest{Rival: running}
if running.InfoHash != "" && running.InfoHash == chosen.InfoHash {
c.Kept, c.Reason = true, "That release is already downloading for this album."
return c
}
switch {
case origin.By == OriginOperator && running.Origin == OriginSchedule:
c.Reason = "you chose it over the one the schedule started"
case origin.By == OriginSchedule && running.Origin == OriginOperator:
c.Kept, c.Reason = true, "A download you started for this album is already running."
return c
default:
var theirs *Candidate
for i := range all {
if (running.InfoHash != "" && all[i].InfoHash == running.InfoHash) || Key(all[i]) == running.Key {
theirs = &all[i]
break
}
}
if theirs == nil || !better(*chosen, *theirs) {
c.Kept, c.Reason = true, "A download for this album is already running, and this release is no better."
return c
}
c.Reason = "it ranks above the one that was running"
}
if running.InfoHash == "" {
c.Kept, c.Reason = true, "A download for this album is already running, and it cannot be identified to replace it."
return c
}
if ts, err := s.Grabber.Client.Torrents(ctx, running.InfoHash); err == nil && len(ts) > 0 && ts[0].Progress >= nearlyDone {
c.Kept, c.Reason = true, "A download for this album is already running and nearly done."
return c
}
c.Replaced = true
return c
}
// landingFor is the folder a download lands in: one per torrent, named by
// its infohash, so two grabs never unpack into the same place.
func landingFor(root, hash, name string) string {
dir := hash
if dir == "" {
dir = slug(name)
}
if dir == "" {
dir = "unnamed"
}
return path.Join(root, dir)
}
// slug keeps a folder name to characters every filesystem in the chain
// takes.
func slug(s string) string {
var b strings.Builder
for _, r := range strings.ToLower(strings.TrimSpace(s)) {
if b.Len() >= 80 {
break
}
switch {
case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
b.WriteRune(r)
case r == '-', r == '_', r == ' ', r == '.':
b.WriteRune('-')
}
}
return strings.Trim(b.String(), "-")
}
-199
View File
@@ -1,199 +0,0 @@
package acquire
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/indexer"
"git.fabledsword.com/bvandeusen/minstrel/internal/release"
)
// Block reasons, matching release_blocks_reason_check.
const (
BlockOperator = "operator"
BlockFiles = "files"
// BlockImport: the import found its files were not the album.
BlockImport = "import"
// BlockStalled: given up on because it would not finish; held
// back until the block's expires_at.
BlockStalled = "stalled"
// BlockGone: its download client would not let Minstrel follow it, held
// outside Minstrel's category or leaving the client twice; held
// back for GoneBlock.
BlockGone = "gone"
)
// GoneBlock is how long a release its client lost track of is held back:
// long enough that a release which keeps vanishing is tried once a day rather
// than on every pass, short enough that it is taken once the client lets go.
const GoneBlock = 24 * time.Hour
// Grab origins, matching grabs_origin_check.
const (
OriginSchedule = "schedule"
OriginOperator = "operator"
)
// Memory is what searches and grabs leave behind: every candidate of a
// want's last search, the grabs, and the releases set aside.
type Memory struct {
pool *pgxpool.Pool
}
// NewMemory returns a Memory over pool.
func NewMemory(pool *pgxpool.Pool) *Memory { return &Memory{pool: pool} }
// Keep replaces a want's candidates with this search's, in order.
func (m *Memory) Keep(ctx context.Context, wantID pgtype.UUID, cands []Candidate) error {
return pgx.BeginFunc(ctx, m.pool, func(tx pgx.Tx) error {
q := dbq.New(tx)
if err := q.DeleteWantCandidates(ctx, wantID); err != nil {
return err
}
for i, c := range cands {
reasons, err := json.Marshal(c.Reasons)
if err != nil {
return err
}
if c.Reasons == nil {
reasons = []byte("[]")
}
folded := c.FoldedFrom
if folded == nil {
folded = []string{}
}
if err := q.InsertWantCandidate(ctx, dbq.InsertWantCandidateParams{
WantID: wantID, Key: Key(c), Name: c.Name, InfoHash: c.InfoHash, Indexer: c.Indexer,
Source: c.Source.Source, SizeBytes: c.SizeBytes, Seeders: int32(c.Seeders),
FilesCount: int32(c.FilesCount), Format: release.Describe(c.Release), Quality: string(c.Tier),
Year: int32(c.Year), Verdict: string(c.Verdict), Reason: c.Reason, Reasons: reasons,
FoldedFrom: folded, Rank: int32(i),
}); err != nil {
return err
}
}
return nil
})
}
// blocked is every release set aside, by infohash, with the sentence a
// candidate shows. A failed read blocks nothing: offering a release set
// aside costs one grab a person can undo, while blocking everything on a
// database blip would hide every result.
func (m *Memory) blocked(ctx context.Context) map[string]string {
if m == nil {
return nil
}
rows, err := dbq.New(m.pool).ListReleaseBlocks(ctx)
if err != nil {
return nil
}
out := make(map[string]string, len(rows))
for _, r := range rows {
out[indexer.NormalizeHash(r.InfoHash)] = BlockSentence(r.Reason, r.Detail)
}
return out
}
// BlockSentence is what a blocked candidate says.
func BlockSentence(reason, detail string) string {
switch reason {
case BlockFiles:
if detail != "" {
return "Set aside for what its files hold: " + detail
}
return "Set aside for what its files hold."
case BlockImport:
if detail != "" {
return "Refused on import: " + detail
}
return "Refused on import: its files were not the album."
case BlockGone:
if detail != "" {
return "Held back for now: " + detail
}
return "Held back for now: its download client lost track of it."
case BlockStalled:
if detail != "" {
return "Given up on for now: " + detail
}
return "Given up on for now: it would not finish."
}
return "You set this release aside."
}
// Block sets a release aside and marks every kept candidate of it blocked.
func (m *Memory) Block(ctx context.Context, p dbq.BlockReleaseParams) error {
p.InfoHash = indexer.NormalizeHash(p.InfoHash)
if p.InfoHash == "" {
return errors.New("a release without an infohash cannot be set aside")
}
return pgx.BeginFunc(ctx, m.pool, func(tx pgx.Tx) error {
q := dbq.New(tx)
if err := q.BlockRelease(ctx, p); err != nil {
return err
}
return q.MarkCandidatesBlocked(ctx, dbq.MarkCandidatesBlockedParams{
InfoHash: p.InfoHash, Reason: BlockSentence(p.Reason, p.Detail),
})
})
}
// Unblock lets a release be taken again. Its kept candidates wait for a
// person until the next search judges them afresh.
func (m *Memory) Unblock(ctx context.Context, hash string) (bool, error) {
hash = indexer.NormalizeHash(hash)
var n int64
err := pgx.BeginFunc(ctx, m.pool, func(tx pgx.Tx) error {
q := dbq.New(tx)
var err error
if n, err = q.UnblockRelease(ctx, hash); err != nil {
return err
}
return q.MarkCandidatesUnblocked(ctx, dbq.MarkCandidatesUnblockedParams{
InfoHash: hash, Reason: "Allowed again. The next search judges it afresh.",
})
})
return n > 0, err
}
// LiveGrab is the download running for a want, if there is one.
func (m *Memory) LiveGrab(ctx context.Context, wantID pgtype.UUID) (dbq.Grab, bool, error) {
g, err := dbq.New(m.pool).GetLiveGrab(ctx, wantID)
if errors.Is(err, pgx.ErrNoRows) {
return g, false, nil
}
if err != nil {
return g, false, err
}
return g, true, nil
}
// Grabbed records a download started, ending the grab it replaced first so
// the one-live-grab index holds.
func (m *Memory) Grabbed(ctx context.Context, p dbq.InsertGrabParams, replaced pgtype.UUID, why string) (dbq.Grab, error) {
var g dbq.Grab
err := pgx.BeginFunc(ctx, m.pool, func(tx pgx.Tx) error {
q := dbq.New(tx)
if replaced.Valid {
if err := q.EndGrab(ctx, dbq.EndGrabParams{ID: replaced, EndReason: "superseded", EndDetail: why}); err != nil {
return err
}
}
var err error
g, err = q.InsertGrab(ctx, p)
return err
})
if err != nil {
return g, fmt.Errorf("record grab: %w", err)
}
return g, nil
}
-145
View File
@@ -1,145 +0,0 @@
package acquire
import (
"context"
"sync"
"time"
"git.fabledsword.com/bvandeusen/minstrel/internal/indexer"
)
// SearchPace is the one Pacer every search shares. Process-wide because a
// Fanout is built fresh for each search; a Pacer per Fanout would start empty
// and pace nothing.
var SearchPace = &Pacer{}
// holdWithoutRetryAfter is how long a source that answered 429 without saying
// for how long is left alone: one schedule tick.
const holdWithoutRetryAfter = 10 * time.Minute
// Pacer spaces the searches sent to each source by its searches_per_hour: a
// spacing, not a burst bucket, because Prowlarr answers 429 to a few requests
// in quick succession. Every search spends, the schedule's and a
// person's alike; only the schedule waits.
type Pacer struct {
// Now and Sleep are the clock, replaceable in tests.
Now func() time.Time
Sleep func(context.Context, time.Duration) error
mu sync.Mutex
next map[string]time.Time
}
func (p *Pacer) now() time.Time {
if p.Now != nil {
return p.Now()
}
return time.Now()
}
func (p *Pacer) sleep(ctx context.Context, d time.Duration) error {
if p.Sleep != nil {
return p.Sleep(ctx, d)
}
t := time.NewTimer(d)
defer t.Stop()
select {
case <-t.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// gap is the spacing a source's number asks for; zero is unpaced.
func gap(perHour int) time.Duration {
if perHour <= 0 {
return 0
}
return time.Hour / time.Duration(perHour)
}
// readyAt is when every source may next be asked.
func (p *Pacer) readyAt(sources []Source) time.Time {
p.mu.Lock()
defer p.mu.Unlock()
var at time.Time
for _, s := range sources {
if s.Search == nil {
continue
}
if n := p.next[s.Code]; n.After(at) {
at = n
}
}
return at
}
// Wait holds until every source may be asked, and answers false, without
// waiting, when that is after the deadline or ctx ends first. All of them,
// not any: a search while one is held back would be narrowed, and the want
// recorded as looked for.
func (p *Pacer) Wait(ctx context.Context, sources []Source, deadline time.Time) bool {
if p == nil {
return true
}
at := p.readyAt(sources)
if !deadline.IsZero() && at.After(deadline) {
return false
}
if d := at.Sub(p.now()); d > 0 {
return p.sleep(ctx, d) == nil
}
return ctx.Err() == nil
}
// spend takes one search's slot from a source.
func (p *Pacer) spend(s Source) {
g := gap(s.PerHour)
if p == nil || g == 0 {
return
}
p.mu.Lock()
defer p.mu.Unlock()
if p.next == nil {
p.next = map[string]time.Time{}
}
at := p.next[s.Code]
if t := p.now(); at.Before(t) {
at = t
}
p.next[s.Code] = at.Add(g)
}
// hold leaves a source alone after it answered 429, for as long as it asked,
// whatever its searches_per_hour says.
func (p *Pacer) hold(code string, rl *indexer.RateLimited) {
if p == nil {
return
}
d := rl.RetryAfter
if d <= 0 {
d = holdWithoutRetryAfter
}
p.mu.Lock()
defer p.mu.Unlock()
if p.next == nil {
p.next = map[string]time.Time{}
}
if until := p.now().Add(d); until.After(p.next[code]) {
p.next[code] = until
}
}
// Ready holds until every source this service searches may be asked again,
// and answers false when that is past the deadline. The schedule calls it
// before each want; a person's search never does.
func (s *Service) Ready(ctx context.Context, deadline time.Time) bool {
if s == nil {
return ctx.Err() == nil
}
if f, ok := s.Search.(*Fanout); ok && f != nil {
return f.Pace.Wait(ctx, f.Sources, deadline)
}
return ctx.Err() == nil
}
-408
View File
@@ -1,408 +0,0 @@
package acquire
import (
"context"
"errors"
"sort"
"strings"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/indexer"
"git.fabledsword.com/bvandeusen/minstrel/internal/release"
)
// One search for one want, and what could be done about each result.
// internal/release
// says whether a name is the album and what quality it is; this package
// asks in the right order and says why in words a person can act on.
// Verdict is what can be done about one result.
type Verdict string
const (
// Grab: the album, in a quality the profile takes.
Grab Verdict = "grab"
// Review: maybe the album; a person decides.
Review Verdict = "review"
// Refused: the album, in a quality the profile does not take. The only
// verdict that names a setting.
Refused Verdict = "refused"
// Rejected: not the album.
Rejected Verdict = "rejected"
// Blocked: a release set aside, by a person or by its files.
Blocked Verdict = "blocked"
)
// order sorts verdicts: what can be taken first, what was given up on last.
var order = map[Verdict]int{Grab: 0, Review: 1, Refused: 2, Rejected: 3, Blocked: 4}
// Reason kinds: a hard reason is a fact about the bytes, a soft one about the
// moment or a setting.
const (
Hard = "hard"
Soft = "soft"
)
// Reason codes beyond internal/release's vetoes.
const (
CodeBlocked = "blocked"
CodeProfile = "profile"
CodeNoSeeders = "no_seeders"
CodeDoubt = "doubt"
// CodeNotBetter: the album, but no better than the copy the library
// holds, for a want that is an upgrade.
CodeNotBetter = "not_better"
)
// Reason is one thing a verdict rests on.
type Reason struct {
Kind string `json:"kind"`
Code string `json:"code"`
Text string `json:"text"`
}
// Want is the album searched for: its wants row and how the catalogue
// describes it.
type Want struct {
ID pgtype.UUID
release.Want
// Floor is the tier of the copy the library holds, for an album wanted
// for a better one: a release must rank above it. "" for an
// album not held, and for a video rip, which any clean copy beats.
Floor release.Tier
// Held says the floor in words: "MP3, about 192 kbps".
Held string
}
// Candidate is one result with everything decided about it.
type Candidate struct {
release.Release
// Source is the indexer's own result. It never leaves the server: its
// DownloadURL can carry the indexer's key.
Source indexer.Result
InfoHash string
Indexer string
SizeBytes int64
Seeders int
SwarmKnown bool
Category int
FilesCount int
// Files is the torrent's file list once its .torrent has been read.
Files []release.File
FoldedFrom []string
Tier release.Tier
YearAgrees bool
Verdict Verdict
Reason string
Reasons []Reason
}
// Key is how a candidate is named across a search and a grab: its infohash,
// or its name when the source gave none.
func Key(c Candidate) string {
if c.InfoHash != "" {
return c.InfoHash
}
return c.Name
}
// Result is one search.
type Result struct {
Query string
// Unconfigured: no search source is set up.
Unconfigured bool
// Error is a search that failed outright.
Error string
// Narrowed names sources that did not answer on a search that otherwise
// did.
Narrowed []Narrowing
Considered int
Folded int
// Looked is how many .torrent files were read for their file lists.
Looked int
Candidates []Candidate
// KeepError: the candidates could not be stored.
KeepError string
}
// Grabbable is what may be taken, best first.
func (r Result) Grabbable() []Candidate {
var out []Candidate
for _, c := range r.Candidates {
if c.Verdict == Grab {
out = append(out, c)
}
}
return out
}
// ForAPerson says whether anything found is worth a person's look: a
// release that may be the album, whatever its quality.
func (r Result) ForAPerson() bool {
for _, c := range r.Candidates {
if c.Verdict == Grab || c.Verdict == Review || c.Verdict == Refused {
return true
}
}
return false
}
// Service searches and grabs.
type Service struct {
// Search is nil when no source is configured.
Search Searcher
// Grabber is nil when no download client is configured.
Grabber *Downloader
Profile release.Profile
// Memory stores candidates, grabs and blocks. Nil keeps nothing.
Memory *Memory
}
// Query is the text sent to the indexers: the artist and the title, without
// a trailing bracketed part the release names usually leave off.
func Query(w release.Want) string {
title := w.Title
if i := strings.IndexAny(title, "(["); i > 0 {
title = title[:i]
}
return strings.Join(strings.Fields(strings.TrimSpace(w.Artist)+" "+strings.TrimSpace(title)), " ")
}
// For searches for one want and judges everything that comes back. It never
// returns an error: a search that could not be made is a Result saying so.
func (s *Service) For(ctx context.Context, want Want) Result {
r := Result{Query: Query(want.Want)}
if s == nil || s.Search == nil {
r.Unconfigured = true
return r
}
found, err := s.Search.Search(ctx, indexer.Query{Text: r.Query, Categories: indexer.MusicCategories})
// A partial search arrives as results and an error together.
if narrowed, answered := narrowings(err); narrowed != nil && answered {
r.Narrowed, err = narrowed, nil
}
switch {
case errors.Is(err, indexer.ErrUnconfigured):
r.Unconfigured = true
return r
case err != nil:
r.Error = indexer.FirstLine(err.Error())
return r
}
r.Considered = len(found)
cands, folded := fold(found)
r.Folded = folded
blocked := s.Memory.blocked(ctx)
for i := range cands {
decide(&cands[i], want, s.Profile, blocked)
}
sortCandidates(cands)
for _, i := range s.peek(ctx, cands) {
decide(&cands[i], want, s.Profile, blocked)
r.Looked++
}
sortCandidates(cands)
r.Candidates = cands
if s.Memory != nil && want.ID.Valid {
if err := s.Memory.Keep(ctx, want.ID, cands); err != nil {
r.KeepError = indexer.FirstLine(err.Error())
}
}
return r
}
// decide works out one candidate's verdict, in order: given up on, then
// whether it is the album, then whether the profile takes its quality, then
// whether anything leaves it to a person. A quality refusal said about the
// wrong album would be noise, so identity comes first.
func decide(c *Candidate, want Want, profile release.Profile, blocked map[string]string) {
w := want.Want
c.Verdict, c.Reason, c.Reasons = "", "", nil
if why, ok := blocked[c.InfoHash]; ok && c.InfoHash != "" {
set(c, Blocked, Hard, CodeBlocked, why)
return
}
m := release.Judge(w, c.Release)
c.YearAgrees = m.YearAgrees
if m.Veto != "" {
set(c, Rejected, Hard, m.Veto, m.Reason)
return
}
doubt := m.Doubt
if len(c.Files) > 0 {
if in := release.Inspect(c.Files); in.Format != "" {
c.Format = in.Format
}
veto, reason, fileDoubt := release.JudgeFiles(w, c.Files)
if veto != "" {
set(c, Rejected, Hard, veto, reason)
return
}
if doubt == "" {
doubt = fileDoubt
}
}
c.Tier = release.TierOf(c.Release, c.Category)
if !profile.Allows(c.Tier) {
set(c, Refused, Soft, CodeProfile, "Your quality settings don’t take "+strings.ToLower(release.Label(c.Tier))+".")
return
}
if want.Floor != "" && release.Rank(c.Tier) <= release.Rank(want.Floor) {
held := want.Held
if held == "" {
held = strings.ToLower(release.Label(want.Floor))
}
set(c, Refused, Soft, CodeNotBetter, "No better than the copy you have ("+held+").")
return
}
if doubt != "" {
set(c, Review, Soft, CodeDoubt, doubt)
return
}
if c.Seeders == 0 {
set(c, Review, Soft, CodeNoSeeders, "Nobody is sharing it right now.")
return
}
c.Verdict = Grab
c.Reason = "The album, " + strings.ToLower(release.Label(c.Tier)) + "."
if d := release.Describe(c.Release); d != "" {
c.Reason = "The album, " + d + "."
}
}
func set(c *Candidate, v Verdict, kind, code, text string) {
c.Verdict, c.Reason = v, text
c.Reasons = append(c.Reasons, Reason{Kind: kind, Code: code, Text: text})
}
// sortCandidates puts the best first, stably so the same search proposes the
// same grab twice.
func sortCandidates(cands []Candidate) {
sort.SliceStable(cands, func(a, b int) bool { return better(cands[a], cands[b]) })
}
// better says whether x ranks above y: verdict, then quality, then how many
// share it, then whether its year agrees.
func better(x, y Candidate) bool {
if order[x.Verdict] != order[y.Verdict] {
return order[x.Verdict] < order[y.Verdict]
}
if rx, ry := release.Rank(x.Tier), release.Rank(y.Tier); rx != ry {
return rx > ry
}
if x.Seeders != y.Seeders {
return x.Seeders > y.Seeders
}
return x.YearAgrees && !y.YearAgrees
}
// fold merges results that are the same torrent, by infohash. Prowlarr
// aggregates, so one release arrives once per tracker that lists it. A
// result without a hash is never folded: an absent hash is not a shared one.
func fold(found []indexer.Result) ([]Candidate, int) {
out := make([]Candidate, 0, len(found))
at := make(map[string]int, len(found))
folded := 0
for _, f := range found {
if strings.TrimSpace(f.Title) == "" {
continue
}
hash := indexer.NormalizeHash(f.InfoHash)
if hash == "" && f.Magnet != "" {
hash = indexer.MagnetHash(f.Magnet)
}
if hash != "" {
if i, seen := at[hash]; seen {
folded++
if f.Indexer != "" {
out[i].FoldedFrom = append(out[i].FoldedFrom, f.Indexer)
}
// A measured swarm beats a reported one; among like, the
// highest count.
switch {
case f.SwarmKnown && !out[i].SwarmKnown:
out[i].Seeders, out[i].SwarmKnown = f.Seeders, true
case f.SwarmKnown == out[i].SwarmKnown && f.Seeders > out[i].Seeders:
out[i].Seeders = f.Seeders
}
if f.FilesCount > 0 && out[i].FilesCount == 0 {
out[i].FilesCount = f.FilesCount
}
continue
}
at[hash] = len(out)
}
out = append(out, Candidate{
Release: release.Parse(f.Title), Source: f, InfoHash: hash, Indexer: f.Indexer,
SizeBytes: f.SizeBytes, Seeders: f.Seeders, SwarmKnown: f.SwarmKnown,
Category: f.Category, FilesCount: f.FilesCount,
})
}
return out, folded
}
// maxPeeks is how many .torrent files one search reads. Few: each goes
// through Prowlarr to a tracker, and Prowlarr answers 429 to a burst.
const maxPeeks = 3
// peek reads the .torrent of candidates that are the album but whose name
// states no format, so their files can say what they are; it returns which
// now carry a file list. A failed fetch leaves the candidate as it was.
func (s *Service) peek(ctx context.Context, cands []Candidate) []int {
f, ok := s.Search.(Fetcher)
if !ok {
return nil
}
var looked []int
for i := range cands {
if len(looked) >= maxPeeks || ctx.Err() != nil {
break
}
c := &cands[i]
if c.Tier != release.TierUnknown || (c.Verdict != Grab && c.Verdict != Refused) ||
c.Files != nil || c.Source.DownloadURL == "" || c.Source.Magnet != "" {
continue
}
body, err := f.Download(ctx, c.Source)
if err != nil {
continue
}
meta, err := release.ParseTorrent(body)
if err != nil {
continue
}
c.Files = meta.Files
if c.InfoHash == "" {
c.InfoHash = meta.InfoHash
}
if c.FilesCount == 0 {
c.FilesCount = len(meta.Files)
}
looked = append(looked, i)
}
return looked
}
// pick finds a candidate by key: the infohash first, the exact name for a
// result that has none.
func pick(cands []Candidate, key string) *Candidate {
key = strings.TrimSpace(key)
if key == "" {
return nil
}
hash := indexer.NormalizeHash(key)
for i := range cands {
if cands[i].InfoHash != "" && cands[i].InfoHash == hash {
return &cands[i]
}
}
for i := range cands {
if cands[i].InfoHash == "" && cands[i].Name == key {
return &cands[i]
}
}
return nil
}
-291
View File
@@ -1,291 +0,0 @@
package acquire
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
"git.fabledsword.com/bvandeusen/minstrel/internal/downloader"
"git.fabledsword.com/bvandeusen/minstrel/internal/indexer"
"git.fabledsword.com/bvandeusen/minstrel/internal/release"
)
type fakeSearch struct {
results []indexer.Result
err error
asked []indexer.Query
}
func (f *fakeSearch) Search(_ context.Context, q indexer.Query) ([]indexer.Result, error) {
f.asked = append(f.asked, q)
return f.results, f.err
}
var ram = Want{Want: release.Want{
Artist: "Daft Punk", Title: "Random Access Memories", Year: 2013, PrimaryType: "Album",
MinTracks: 13, MaxTracks: 15,
}}
var anyQuality = release.NewProfile([]string{
"lossless_hires", "lossless", "lossy_high", "lossy_standard", "lossy_low", "lossy_poor", "lossy_trash",
})
func result(title, hash string, seeders int) indexer.Result {
return indexer.Result{Title: title, InfoHash: hash, Seeders: seeders, Indexer: "Knaben", Source: "prowlarr",
Magnet: "magnet:?xt=urn:btih:" + hash}
}
func TestFor_JudgesSortsAndFolds(t *testing.T) {
search := &fakeSearch{results: []indexer.Result{
result("Daft Punk - Random Access Memories (2013) [MP3 320]", "aaaa", 40),
result("Daft Punk Random Access Memories (Drumless Edition 2023) [Flac 24-88]", "bbbb", 90),
result("Daft Punk - Random Access Memories (2013) [FLAC]", "cccc", 12),
result("Daft Punk - Random Access Memories (2013) [FLAC]", "CCCC", 30), // the same torrent from another tracker
result("Daft Punk - Discovery (2001) [FLAC]", "dddd", 50),
}}
s := &Service{Search: search, Profile: anyQuality}
r := s.For(context.Background(), ram)
if len(search.asked) != 1 || search.asked[0].Text != "Daft Punk Random Access Memories" {
t.Fatalf("asked %+v", search.asked)
}
if r.Considered != 5 || r.Folded != 1 || len(r.Candidates) != 4 {
t.Fatalf("considered %d folded %d candidates %d", r.Considered, r.Folded, len(r.Candidates))
}
// Lossless before high-quality lossy among what can be taken; the
// folded copy keeps the higher seeder count.
first, second := r.Candidates[0], r.Candidates[1]
if first.InfoHash != "cccc" || first.Verdict != Grab || first.Seeders != 30 || first.Tier != release.TierLossless {
t.Errorf("first = %s %s %d %s", first.Name, first.Verdict, first.Seeders, first.Tier)
}
if second.InfoHash != "aaaa" || second.Verdict != Grab {
t.Errorf("second = %s %s", second.Name, second.Verdict)
}
for _, c := range r.Candidates[2:] {
if c.Verdict != Rejected || len(c.Reasons) != 1 || c.Reasons[0].Kind != Hard {
t.Errorf("%s: %s %+v", c.Name, c.Verdict, c.Reasons)
}
}
if len(r.Grabbable()) != 2 || !r.ForAPerson() {
t.Errorf("grabbable %d", len(r.Grabbable()))
}
}
func TestFor_ProfileSeedersAndDoubt(t *testing.T) {
search := &fakeSearch{results: []indexer.Result{
result("Daft Punk - Random Access Memories [MP3 128]", "aaaa", 5),
result("Daft Punk - Random Access Memories [FLAC]", "bbbb", 0),
result("Daft Punk - Random Access Memories", "cccc", 9),
}}
s := &Service{Search: search, Profile: release.NewProfile([]string{"lossless", "lossy_high"})}
r := s.For(context.Background(), ram)
verdicts := map[string]Verdict{}
for _, c := range r.Candidates {
verdicts[c.InfoHash] = c.Verdict
}
if verdicts["aaaa"] != Refused || verdicts["bbbb"] != Review || verdicts["cccc"] != Refused {
t.Errorf("verdicts = %v", verdicts)
}
if len(r.Grabbable()) != 0 || !r.ForAPerson() {
t.Error("nothing grabbable, but something for a person")
}
}
func TestFor_BlockedReleasesAreSetAside(t *testing.T) {
c := Candidate{Release: release.Parse("Daft Punk - Random Access Memories [FLAC]"), InfoHash: "aaaa", Seeders: 3}
decide(&c, ram, anyQuality, map[string]string{"aaaa": "You set this release aside."})
if c.Verdict != Blocked || c.Reason != "You set this release aside." {
t.Errorf("verdict %s %q", c.Verdict, c.Reason)
}
}
func TestFor_UnconfiguredAndFailedSearches(t *testing.T) {
if r := (&Service{}).For(context.Background(), ram); !r.Unconfigured {
t.Error("no source is unconfigured")
}
r := (&Service{Search: &fakeSearch{err: indexer.ErrUnconfigured}}).For(context.Background(), ram)
if !r.Unconfigured {
t.Error("ErrUnconfigured is unconfigured")
}
r = (&Service{Search: &fakeSearch{err: errors.New("dial tcp: refused")}}).For(context.Background(), ram)
if r.Error == "" {
t.Error("a failed search says so")
}
}
func TestFanout_ANarrowedSearchKeepsWhatAnswered(t *testing.T) {
up := &fakeSearch{results: []indexer.Result{result("Daft Punk - Random Access Memories [FLAC]", "aaaa", 3)}}
down := &fakeSearch{err: indexer.ErrUnreachable}
f := &Fanout{Sources: []Source{{Code: "prowlarr", Label: "Prowlarr", Search: up}, {Code: "torznab", Label: "Feed", Search: down}}}
r := (&Service{Search: f, Profile: anyQuality}).For(context.Background(), ram)
if r.Error != "" || len(r.Candidates) != 1 || len(r.Narrowed) != 1 || r.Narrowed[0].Source != "torznab" {
t.Errorf("narrowed search: error %q, %d candidates, narrowed %+v", r.Error, len(r.Candidates), r.Narrowed)
}
f.Sources = f.Sources[1:]
if r := (&Service{Search: f}).For(context.Background(), ram); r.Error == "" {
t.Error("every source down is a failed search")
}
}
func TestPacer_SpacesSearchesAndHoldsAfterA429(t *testing.T) {
now := time.Unix(0, 0)
var slept time.Duration
p := &Pacer{Now: func() time.Time { return now }, Sleep: func(_ context.Context, d time.Duration) error { slept += d; return nil }}
src := []Source{{Code: "prowlarr", PerHour: 120, Search: &fakeSearch{}}}
p.spend(src[0])
if !p.Wait(context.Background(), src, now.Add(time.Hour)) || slept != 30*time.Second {
t.Errorf("slept %s, want 30s", slept)
}
if p.Wait(context.Background(), src, now.Add(time.Second)) {
t.Error("waited past the deadline")
}
p.hold("prowlarr", &indexer.RateLimited{RetryAfter: 5 * time.Minute})
if at := p.readyAt(src); at.Sub(now) != 5*time.Minute {
t.Errorf("held until %s", at.Sub(now))
}
}
type fakeClient struct {
downloader.Driver
added []downloader.Add
addErr error
deleted []string
progress float64
// elsewhere: the client holds it but does not list it for Minstrel.
elsewhere bool
}
func (c *fakeClient) AddTorrent(_ context.Context, a downloader.Add) error {
c.added = append(c.added, a)
return c.addErr
}
func (c *fakeClient) Torrents(_ context.Context, hashes ...string) ([]downloader.Torrent, error) {
if c.elsewhere {
return nil, nil
}
return []downloader.Torrent{{Hash: hashes[0], Progress: c.progress}}, nil
}
func (c *fakeClient) Delete(_ context.Context, _ bool, hashes ...string) error {
c.deleted = append(c.deleted, hashes...)
return nil
}
func TestGrab_AddsAMagnetToItsOwnFolder(t *testing.T) {
client := &fakeClient{}
s := &Service{Search: &fakeSearch{results: []indexer.Result{
result("Daft Punk - Random Access Memories (2013) [FLAC]", "ABCD", 8),
}}, Profile: anyQuality, Grabber: &Downloader{Client: client, Code: "qbittorrent", Landing: "/downloads"}}
r := s.For(context.Background(), ram)
took := s.Grab(context.Background(), ram, &r.Candidates[0], r.Candidates, false, Origin{By: OriginSchedule})
if !took.Added || took.SavePath != "/downloads/abcd" {
t.Fatalf("took %+v", took)
}
if len(client.added) != 1 || !strings.Contains(strings.ToLower(client.added[0].Magnet), "abcd") || client.added[0].Tags[0] != Tag {
t.Errorf("added %+v", client.added)
}
}
func TestGrab_RefusesWhatTheVerdictWouldNotTake(t *testing.T) {
client := &fakeClient{}
s := &Service{Grabber: &Downloader{Client: client, Landing: "/downloads"}}
review := Candidate{Verdict: Review, InfoHash: "aaaa", Source: indexer.Result{Magnet: "magnet:?xt=urn:btih:aaaa"}}
if took := s.Grab(context.Background(), ram, &review, nil, false, Origin{By: OriginSchedule}); !took.Refused {
t.Error("a review was taken unforced")
}
if took := s.Grab(context.Background(), ram, &review, nil, true, Origin{By: OriginOperator}); !took.Added {
t.Errorf("a forced review was not taken: %+v", took)
}
blocked := Candidate{Verdict: Blocked, InfoHash: "bbbb"}
if took := s.Grab(context.Background(), ram, &blocked, nil, true, Origin{By: OriginOperator}); !took.Refused {
t.Error("forcing took a release set aside")
}
if took := (&Service{}).Grab(context.Background(), ram, &review, nil, true, Origin{}); !took.Unconfigured || took.Missing != MissingClient {
t.Errorf("no client: %+v", took)
}
}
func TestGrab_AClientThatAlreadyHasItCounts(t *testing.T) {
client := &fakeClient{addErr: downloader.ErrDuplicate}
s := &Service{Grabber: &Downloader{Client: client, Landing: "/downloads"}}
c := Candidate{Verdict: Grab, InfoHash: "aaaa", Source: indexer.Result{Magnet: "magnet:?xt=urn:btih:aaaa"}}
if took := s.Grab(context.Background(), ram, &c, nil, false, Origin{By: OriginSchedule}); !took.Added {
t.Errorf("a duplicate: %+v", took)
}
}
// A duplicate the client does not list for Minstrel sits under another
// category, where it would read as gone half an hour later. It is set
// aside rather than taken; forced, it is refused with the client's reason.
func TestGrab_ADuplicateHeldOutsideMinstrelIsNotTaken(t *testing.T) {
client := &fakeClient{addErr: fmt.Errorf("%w: already downloading Ohio Players (lidarr)", downloader.ErrDuplicate), elsewhere: true}
s := &Service{Grabber: &Downloader{Client: client, Landing: "/downloads"}}
c := Candidate{Verdict: Grab, InfoHash: "aaaa", Source: indexer.Result{Magnet: "magnet:?xt=urn:btih:aaaa"}}
took := s.Grab(context.Background(), ram, &c, nil, false, Origin{By: OriginSchedule})
if took.Added || !took.Refused {
t.Fatalf("took %+v", took)
}
if c.Verdict != Blocked || !strings.Contains(c.Reason, "(already downloading Ohio Players (lidarr))") {
t.Errorf("candidate %s: %q", c.Verdict, c.Reason)
}
forced := Candidate{Verdict: Grab, InfoHash: "aaaa", Source: indexer.Result{Magnet: "magnet:?xt=urn:btih:aaaa"}}
took = s.Grab(context.Background(), ram, &forced, nil, true, Origin{By: OriginOperator})
if took.Added || !strings.Contains(took.Error, "outside Minstrel's category") {
t.Errorf("forced: %+v", took)
}
}
func TestBetter_QualityThenSeedersThenYear(t *testing.T) {
flac := Candidate{Verdict: Grab, Tier: release.TierLossless, Seeders: 2}
mp3 := Candidate{Verdict: Grab, Tier: release.TierLossyHigh, Seeders: 90}
if !better(flac, mp3) || better(mp3, flac) {
t.Error("quality first among grabs")
}
busy := Candidate{Verdict: Grab, Tier: release.TierLossless, Seeders: 20}
if !better(busy, flac) {
t.Error("then seeders")
}
dated := Candidate{Verdict: Grab, Tier: release.TierLossless, Seeders: 2, YearAgrees: true}
if !better(dated, flac) {
t.Error("then the year")
}
if better(Candidate{Verdict: Review}, flac) || !better(flac, Candidate{Verdict: Review}) {
t.Error("a grab ranks above a review")
}
}
func TestLandingFor_OneFolderPerTorrent(t *testing.T) {
if got := landingFor("/downloads", "abcd", "x"); got != "/downloads/abcd" {
t.Error(got)
}
if got := landingFor("/downloads", "", "Daft Punk: R.A.M. [FLAC]"); got != "/downloads/daft-punk-r-a-m--flac" {
t.Error(got)
}
}
func TestDecide_AnUpgradeTakesOnlyABetterCopy(t *testing.T) {
up := ram
up.Floor, up.Held = release.TierLossyLow, "MP3, about 192 kbps"
same := Candidate{Release: release.Parse("Daft Punk - Random Access Memories [MP3 192]"), InfoHash: "aaaa", Seeders: 3}
decide(&same, up, anyQuality, nil)
if same.Verdict != Refused || same.Reasons[0].Code != CodeNotBetter ||
same.Reason != "No better than the copy you have (MP3, about 192 kbps)." {
t.Errorf("same quality: %s %q", same.Verdict, same.Reason)
}
flac := Candidate{Release: release.Parse("Daft Punk - Random Access Memories [FLAC]"), InfoHash: "bbbb", Seeders: 3}
decide(&flac, up, anyQuality, nil)
if flac.Verdict != Grab {
t.Errorf("a FLAC over a 192 MP3: %s %q", flac.Verdict, flac.Reason)
}
// A video rip has no floor: any clean copy is better.
rip := ram
decide(&same, rip, anyQuality, nil)
if same.Verdict != Grab {
t.Errorf("no floor: %s %q", same.Verdict, same.Reason)
}
}
-185
View File
@@ -1,185 +0,0 @@
// Package acquire turns the configured indexers and download clients into
// working clients.
//
// ONE BUILDER PER KIND. SourceFor makes a search source from a row and
// DownloadClient makes a download client, path mapping included. The grab,
// the importer, the stall watchdog and the settings page's Test all build
// through them, so a Test that passes vouches for the path real traffic takes.
// Clients are rebuilt from the row on every use, so a changed address or a new
// key takes effect on the next call.
package acquire
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/downloader"
"git.fabledsword.com/bvandeusen/minstrel/internal/exchange"
"git.fabledsword.com/bvandeusen/minstrel/internal/indexer"
"git.fabledsword.com/bvandeusen/minstrel/internal/prowlarr"
)
// Kinds: which list a row appears in.
const (
KindSearch = "search"
KindDownload = "download"
)
// Jobs a row can do. An exchange row does each its switch allows; every
// other row does the one its kind names.
const (
JobSearch = "search"
JobDownload = "download"
JobEnrichment = "enrichment"
)
// Protocols: which client a row builds.
const (
ProtocolProwlarr = "prowlarr"
ProtocolTorznab = "torznab"
ProtocolQBittorrent = "qbittorrent"
ProtocolExchange = "exchange"
)
// DefaultCategory files everything Minstrel adds to a download client.
const DefaultCategory = "minstrel"
// addable is what a new row of a protocol starts as.
type addable struct {
kind string
label string
category string
timeoutMs int32
perHour int32
}
// catalogue is every protocol an admin can add. Exchange starts unpaced
// (it searches its own database); the others at 120 searches an hour, which
// keeps a Prowlarr's indexers under the rate most trackers allow.
var catalogue = map[string]addable{
ProtocolProwlarr: {kind: KindSearch, label: "Prowlarr", timeoutMs: 60000, perHour: 120},
ProtocolTorznab: {kind: KindSearch, label: "Torznab feed", timeoutMs: 30000, perHour: 120},
ProtocolQBittorrent: {kind: KindDownload, label: "qBittorrent", category: DefaultCategory, timeoutMs: 15000, perHour: 0},
ProtocolExchange: {kind: KindDownload, label: "FabledExchange", category: DefaultCategory, timeoutMs: 30000, perHour: 0},
}
// Addable says whether protocol is one an admin can add.
func Addable(protocol string) bool {
_, ok := catalogue[protocol]
return ok
}
// Searches says whether a row is a search source.
func Searches(row dbq.AcquisitionService) bool {
if row.Protocol == ProtocolExchange {
return row.ServesSearch
}
return row.Kind == KindSearch
}
// Fetches says whether a row is a download client.
func Fetches(row dbq.AcquisitionService) bool {
if row.Protocol == ProtocolExchange {
return row.ServesDownloads
}
return row.Kind == KindDownload
}
// Searcher is a search source.
type Searcher interface {
Search(ctx context.Context, q indexer.Query) ([]indexer.Result, error)
}
// Fetcher fetches a result's .torrent through the source that offered it.
type Fetcher interface {
Download(ctx context.Context, r indexer.Result) ([]byte, error)
}
// Source is one configured search source.
type Source struct {
Code string
Label string
// PerHour is the most searches the schedule sends it an hour; 0 = unpaced.
PerHour int
Search Searcher
// Fetch is nil for a source whose results are all magnets.
Fetch Fetcher
}
// SourceFor builds the search source a row describes.
func SourceFor(row dbq.AcquisitionService) Source {
src := Source{Code: row.Code, Label: row.Label, PerHour: int(row.SearchesPerHour)}
timeout := msDuration(row.TimeoutMs)
switch row.Protocol {
case ProtocolProwlarr:
c := &prowlarr.Client{Config: prowlarr.Config{
Code: row.Code, BaseURL: row.BaseUrl, APIKey: row.ApiKey, Timeout: timeout,
}}
src.Search, src.Fetch = c, c
case ProtocolExchange:
src.Search = ExchangeFor(row)
default:
c := &indexer.Torznab{Config: indexer.TorznabConfig{
Code: row.Code, FeedURL: row.BaseUrl, APIKey: row.ApiKey, Timeout: timeout,
}}
src.Search, src.Fetch = c, c
}
return src
}
// ExchangeFor builds the search and enrichment client for an exchange row.
func ExchangeFor(row dbq.AcquisitionService) *exchange.Client {
return &exchange.Client{
Code: row.Code,
Config: exchange.Config{
BaseURL: row.BaseUrl, APIKey: row.ApiKey, Timeout: msDuration(row.TimeoutMs),
},
}
}
// DownloadClient builds the download client a row describes, wrapped in its
// path mapping.
func DownloadClient(row dbq.AcquisitionService) (downloader.Driver, error) {
d, err := downloader.For(row.Protocol, downloader.Config{
BaseURL: row.BaseUrl, Username: row.Username, Password: row.Password,
APIKey: row.ApiKey, Category: row.Category, Timeout: msDuration(row.TimeoutMs),
})
if err != nil {
return nil, err
}
return downloader.Mapped(d, downloader.PathMap{Local: row.LocalPath, Remote: row.RemotePath}), nil
}
// DownloadClientFor builds the download client a grab went to, by the code
// of its acquisition_services row.
func DownloadClientFor(ctx context.Context, pool *pgxpool.Pool, code string) (downloader.Driver, error) {
row, err := dbq.New(pool).GetAcquisitionService(ctx, code)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, fmt.Errorf("the download client %q is no longer set up", code)
}
return nil, err
}
return DownloadClient(row)
}
// Sources builds every enabled search source.
func Sources(ctx context.Context, pool *pgxpool.Pool) ([]Source, error) {
rows, err := dbq.New(pool).ListUsableAcquisitionServices(ctx, JobSearch)
if err != nil {
return nil, err
}
out := make([]Source, len(rows))
for i, r := range rows {
out[i] = SourceFor(r)
}
return out, nil
}
func msDuration(ms int32) time.Duration { return time.Duration(ms) * time.Millisecond }
-191
View File
@@ -1,191 +0,0 @@
package acquire
import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// ErrNotFound is a code with no row.
var ErrNotFound = errors.New("no such service")
// ErrTooMany is a twenty-first row of one protocol.
var ErrTooMany = errors.New("there are already twenty of these")
// InvalidError is a setting an admin has to change, in words for the
// settings card.
type InvalidError struct {
Field string
Message string
}
func (e *InvalidError) Error() string { return e.Message }
func invalid(field, msg string) error { return &InvalidError{Field: field, Message: msg} }
// maxPerProtocol bounds the codes tried for a new row. Nobody runs twenty
// Prowlarrs; the bound keeps a loop over a full table finite.
const maxPerProtocol = 20
// Store reads and writes acquisition_services.
type Store struct {
pool *pgxpool.Pool
}
// NewStore returns a Store over pool.
func NewStore(pool *pgxpool.Pool) *Store { return &Store{pool: pool} }
// List returns every row without its secrets.
func (s *Store) List(ctx context.Context) ([]dbq.ListAcquisitionServicesRow, error) {
return dbq.New(s.pool).ListAcquisitionServices(ctx)
}
// Get returns one row, secrets included: for building a client only.
func (s *Store) Get(ctx context.Context, code string) (dbq.AcquisitionService, error) {
row, err := dbq.New(s.pool).GetAcquisitionService(ctx, code)
if errors.Is(err, pgx.ErrNoRows) {
return row, ErrNotFound
}
return row, err
}
// Create adds a row of protocol, switched off and with no address. Its code
// is the protocol for the first, then protocol-2, protocol-3.
func (s *Store) Create(ctx context.Context, protocol string) (dbq.AcquisitionService, error) {
a, ok := catalogue[protocol]
if !ok {
return dbq.AcquisitionService{}, invalid("protocol", "One of prowlarr, torznab, qbittorrent, exchange.")
}
q := dbq.New(s.pool)
for n := 1; n <= maxPerProtocol; n++ {
code, label := protocol, a.label
if n > 1 {
code, label = fmt.Sprintf("%s-%d", protocol, n), fmt.Sprintf("%s %d", a.label, n)
}
row, err := q.CreateAcquisitionService(ctx, dbq.CreateAcquisitionServiceParams{
Code: code, Kind: a.kind, Protocol: protocol, Label: label,
Category: a.category, TimeoutMs: a.timeoutMs, SearchesPerHour: a.perHour,
})
if errors.Is(err, pgx.ErrNoRows) {
continue
}
return row, err
}
return dbq.AcquisitionService{}, ErrTooMany
}
// Update is everything on the settings form except the credentials.
type Update struct {
Label string
Enabled bool
BaseURL string
Username string
Category string
TimeoutMs int32
ServesSearch bool
ServesDownloads bool
ServesEnrichment bool
LocalPath string
RemotePath string
SearchesPerHour int32
}
// Save validates u and writes it to code's row.
func (s *Store) Save(ctx context.Context, code string, u Update) (dbq.AcquisitionService, error) {
u.Label = strings.TrimSpace(u.Label)
u.BaseURL = strings.TrimSpace(u.BaseURL)
u.Username = strings.TrimSpace(u.Username)
u.Category = strings.TrimSpace(u.Category)
u.LocalPath = strings.TrimSpace(u.LocalPath)
u.RemotePath = strings.TrimSpace(u.RemotePath)
if err := u.validate(); err != nil {
return dbq.AcquisitionService{}, err
}
row, err := dbq.New(s.pool).UpdateAcquisitionService(ctx, dbq.UpdateAcquisitionServiceParams{
Code: code, Label: u.Label, Enabled: u.Enabled, BaseUrl: u.BaseURL,
Username: u.Username, Category: u.Category, TimeoutMs: u.TimeoutMs,
ServesSearch: u.ServesSearch, ServesDownloads: u.ServesDownloads,
ServesEnrichment: u.ServesEnrichment, LocalPath: u.LocalPath,
RemotePath: u.RemotePath, SearchesPerHour: u.SearchesPerHour,
})
if errors.Is(err, pgx.ErrNoRows) {
return row, ErrNotFound
}
return row, err
}
// validate mirrors the table's CHECKs, so a bad value is named in the card's
// own terms before Postgres refuses it.
func (u Update) validate() error {
if u.Label == "" {
return invalid("label", "Name: give it a name.")
}
if u.Enabled && u.BaseURL == "" {
return invalid("base_url", "Address: give the address before switching this on.")
}
if u.BaseURL != "" {
parsed, err := url.Parse(u.BaseURL)
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
return invalid("base_url", "Address: start with http:// or https://.")
}
}
if u.TimeoutMs < 1000 || u.TimeoutMs > 300000 {
return invalid("timeout_ms", "Give up after: between 1000 and 300000 milliseconds.")
}
if !strings.HasPrefix(u.LocalPath, "/") {
return invalid("local_path", "Downloads folder as Minstrel sees it: a full path, starting with /.")
}
if u.RemotePath != "" && !strings.HasPrefix(u.RemotePath, "/") {
return invalid("remote_path", "Downloads folder as the client sees it: a full path starting with /, or empty when it is the same path.")
}
if u.SearchesPerHour < 0 || u.SearchesPerHour > 3600 {
return invalid("searches_per_hour", "Searches per hour: between 0 and 3600. 0 means no limit.")
}
return nil
}
// Delete removes code's row.
func (s *Store) Delete(ctx context.Context, code string) error {
n, err := dbq.New(s.pool).DeleteAcquisitionService(ctx, code)
if err != nil {
return err
}
if n == 0 {
return ErrNotFound
}
return nil
}
// SetAPIKey stores a key, trimmed; empty clears it.
func (s *Store) SetAPIKey(ctx context.Context, code, key string) error {
n, err := dbq.New(s.pool).SetAcquisitionServiceAPIKey(ctx, dbq.SetAcquisitionServiceAPIKeyParams{
Code: code, ApiKey: strings.TrimSpace(key),
})
return affected(n, err)
}
// SetPassword stores a password as typed (spaces are part of a password);
// empty clears it.
func (s *Store) SetPassword(ctx context.Context, code, password string) error {
n, err := dbq.New(s.pool).SetAcquisitionServicePassword(ctx, dbq.SetAcquisitionServicePasswordParams{
Code: code, Password: password,
})
return affected(n, err)
}
func affected(n int64, err error) error {
if err != nil {
return err
}
if n == 0 {
return ErrNotFound
}
return nil
}
-108
View File
@@ -1,108 +0,0 @@
package acquire
import (
"context"
"errors"
"io"
"log/slog"
"os"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
"git.fabledsword.com/bvandeusen/minstrel/internal/dbtest"
)
func newPool(t *testing.T) *pgxpool.Pool {
t.Helper()
if testing.Short() {
t.Skip("skipping integration test in -short mode")
}
dsn := os.Getenv("MINSTREL_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
if err := db.Migrate(dsn, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil {
t.Fatalf("migrate: %v", err)
}
pool, err := pgxpool.New(context.Background(), dsn)
if err != nil {
t.Fatalf("pool: %v", err)
}
t.Cleanup(pool.Close)
dbtest.ResetDB(t, pool)
return pool
}
func TestStore_AddsConfiguresAndRemoves_Integration(t *testing.T) {
ctx := context.Background()
s := NewStore(newPool(t))
first, err := s.Create(ctx, ProtocolExchange)
if err != nil {
t.Fatalf("create: %v", err)
}
second, err := s.Create(ctx, ProtocolExchange)
if err != nil {
t.Fatalf("create a second: %v", err)
}
if first.Code != "exchange" || second.Code != "exchange-2" || second.Label != "FabledExchange 2" {
t.Errorf("codes = %q, %q (%q); want exchange, exchange-2", first.Code, second.Code, second.Label)
}
// A new exchange is off, does every job, files under minstrel and is
// unpaced.
if first.Enabled || first.Kind != KindDownload || !first.ServesSearch || !first.ServesDownloads ||
!first.ServesEnrichment || first.Category != DefaultCategory || first.SearchesPerHour != 0 || first.LocalPath != "/downloads" {
t.Errorf("a new exchange = %+v", first)
}
if _, err := s.Create(ctx, "transmission"); !errors.As(err, new(*InvalidError)) {
t.Errorf("an unknown protocol: err = %v", err)
}
u := Update{
Label: "Exchange", Enabled: true, BaseURL: "http://exchange:8080", Category: "minstrel",
TimeoutMs: 20000, ServesSearch: true, LocalPath: "/downloads", RemotePath: "/data/torrents",
}
saved, err := s.Save(ctx, first.Code, u)
if err != nil {
t.Fatalf("save: %v", err)
}
if !saved.Enabled || saved.ServesDownloads || saved.RemotePath != "/data/torrents" {
t.Errorf("saved = %+v", saved)
}
if _, err := s.Save(ctx, "nope", u); !errors.Is(err, ErrNotFound) {
t.Errorf("saving a missing row: err = %v", err)
}
// Secrets are write-only: the list says whether one is set, never what.
if err := s.SetAPIKey(ctx, first.Code, " key "); err != nil {
t.Fatalf("set key: %v", err)
}
full, err := s.Get(ctx, first.Code)
if err != nil || full.ApiKey != "key" {
t.Errorf("stored key = %q (err %v), want it trimmed", full.ApiKey, err)
}
rows, err := s.List(ctx)
if err != nil || len(rows) != 2 {
t.Fatalf("list: %d rows, err %v", len(rows), err)
}
for _, r := range rows {
if r.Code == first.Code && !r.HasApiKey {
t.Error("the list should say a key is set")
}
}
// Only the exchange with search switched on is a search source.
srcs, err := Sources(ctx, s.pool)
if err != nil || len(srcs) != 1 || srcs[0].Code != first.Code {
t.Errorf("sources = %+v, err %v; want only the enabled exchange", srcs, err)
}
if err := s.Delete(ctx, second.Code); err != nil {
t.Fatalf("delete: %v", err)
}
if err := s.Delete(ctx, second.Code); !errors.Is(err, ErrNotFound) {
t.Errorf("deleting twice: err = %v", err)
}
}
-134
View File
@@ -1,134 +0,0 @@
package acquire
import (
"context"
"errors"
"fmt"
"os"
"strings"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/exchange"
"git.fabledsword.com/bvandeusen/minstrel/internal/indexer"
)
// TestResult is what the settings card says after Test.
type TestResult struct {
OK bool `json:"ok"`
Detail string `json:"detail"`
}
// testQuery is a search every music indexer should answer.
const testQuery = "Radiohead"
// Test reaches the service a row describes, through the same builders real
// traffic uses. It runs whether or not the row is switched on: paste the
// address, test it, then switch it on.
func Test(ctx context.Context, row dbq.AcquisitionService) TestResult {
if strings.TrimSpace(row.BaseUrl) == "" {
return TestResult{Detail: "No address is set, so there is nothing to reach yet."}
}
if row.Protocol == ProtocolExchange {
return testExchange(ctx, row)
}
if row.Kind == KindSearch {
return testSearch(ctx, row)
}
return testDownload(ctx, row)
}
// testExchange runs each job the row has switched on and reports them all.
func testExchange(ctx context.Context, row dbq.AcquisitionService) TestResult {
var parts []string
ok := true
run := func(name string, on bool, test func() TestResult) {
if !on {
return
}
r := test()
ok = ok && r.OK
parts = append(parts, name+": "+r.Detail)
}
run("Downloads", row.ServesDownloads, func() TestResult { return testDownload(ctx, row) })
run("Search", row.ServesSearch, func() TestResult { return testSearch(ctx, row) })
run("Release details", row.ServesEnrichment, func() TestResult { return testEnrichment(ctx, row) })
if len(parts) == 0 {
return TestResult{Detail: "Every job of this FabledExchange is switched off, so there is nothing to test."}
}
return TestResult{OK: ok, Detail: strings.Join(parts, " ")}
}
// testSearch runs a real search.
func testSearch(ctx context.Context, row dbq.AcquisitionService) TestResult {
src := SourceFor(row)
results, err := src.Search.Search(ctx, indexer.Query{Text: testQuery, Categories: indexer.MusicCategories})
switch {
case errors.Is(err, indexer.ErrUnconfigured):
return TestResult{Detail: "Add this service's address, and the API key it shows on its own settings page."}
case errors.Is(err, indexer.ErrAuth):
return TestResult{Detail: indexer.FirstLine(err.Error()) + ". Check it on the service's own settings page."}
case err != nil:
return TestResult{Detail: indexer.FirstLine(err.Error())}
case len(results) == 0:
return TestResult{OK: true, Detail: "Connected, but a test search for music found nothing. Check that it has an indexer with music categories."}
}
return TestResult{OK: true, Detail: fmt.Sprintf("Connected. %d results for a test search.", len(results))}
}
// testDownload lists the client's torrents, which proves the session and not
// only the login, then checks the downloads folder from Minstrel's side.
func testDownload(ctx context.Context, row dbq.AcquisitionService) TestResult {
c, err := DownloadClient(row)
if err != nil {
return TestResult{Detail: err.Error()}
}
ts, err := c.Torrents(ctx)
if err != nil {
return TestResult{Detail: indexer.FirstLine(err.Error())}
}
detail := fmt.Sprintf("Connected. %d torrents.", len(ts))
if row.Category != "" {
detail = fmt.Sprintf("Connected. %d torrents in the %q category.", len(ts), row.Category)
}
if up, err := c.Connected(ctx); err == nil && !up {
detail += " The client reports it is not connected to any peers, so downloads will stall."
}
if problem := landingProblem(row.LocalPath); problem != "" {
return TestResult{Detail: detail + " " + problem}
}
return TestResult{OK: true, Detail: detail}
}
// landingProblem checks Minstrel can see and write the downloads folder: it
// moves finished downloads out of it. Only the local path can be checked;
// the client's own name for it cannot be seen from here.
func landingProblem(dir string) string {
info, err := os.Stat(dir)
switch {
case err != nil:
return fmt.Sprintf("But Minstrel cannot see its downloads folder at %s. Mount the download client's downloads folder there, or change where Minstrel looks for it.", dir)
case !info.IsDir():
return fmt.Sprintf("But %s is a file, not the downloads folder.", dir)
}
probe, err := os.CreateTemp(dir, ".minstrel-probe-*")
if err != nil {
return fmt.Sprintf("But Minstrel cannot write to %s, so it could not move a finished download out of it. Check the mount is not read-only and Minstrel's user can write there.", dir)
}
name := probe.Name()
_ = probe.Close()
_ = os.Remove(name)
return ""
}
// testEnrichment asks about a hash no torrent has. A JSON "not crawled" is a
// healthy answer; a 404 from something that is not Exchange is not.
func testEnrichment(ctx context.Context, row dbq.AcquisitionService) TestResult {
_, err := ExchangeFor(row).Torrent(ctx, strings.Repeat("0", 40))
switch {
case err == nil, errors.Is(err, exchange.ErrUnknown):
return TestResult{OK: true, Detail: "Connected. The index answered."}
case errors.Is(err, exchange.ErrUnconfigured):
return TestResult{Detail: "No address is set, so there is nothing to reach yet."}
}
return TestResult{Detail: indexer.FirstLine(err.Error())}
}
-210
View File
@@ -1,210 +0,0 @@
package api
import (
"encoding/json"
"errors"
"io"
"net/http"
"github.com/go-chi/chi/v5"
"git.fabledsword.com/bvandeusen/minstrel/internal/acquire"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// Indexers and download clients, admin side. Rows an admin
// adds and configures; nothing is seeded. Secrets are write-only: no response
// carries one, only whether it is set.
// acquisitionBodyLimit caps a settings body. The largest is a full form of
// short strings.
const acquisitionBodyLimit = 64 << 10
type acquisitionServiceResp struct {
Code string `json:"code"`
Kind string `json:"kind"`
Protocol string `json:"protocol"`
Label string `json:"label"`
Enabled bool `json:"enabled"`
BaseURL string `json:"base_url"`
HasAPIKey bool `json:"has_api_key"`
HasPassword bool `json:"has_password"`
Username string `json:"username"`
Category string `json:"category"`
TimeoutMs int32 `json:"timeout_ms"`
ServesSearch bool `json:"serves_search"`
ServesDownloads bool `json:"serves_downloads"`
ServesEnrichment bool `json:"serves_enrichment"`
LocalPath string `json:"local_path"`
RemotePath string `json:"remote_path"`
SearchesPerHour int32 `json:"searches_per_hour"`
// Usable is switched on and addressed: the state the jobs read.
Usable bool `json:"usable"`
}
func acquisitionRespOf(r dbq.AcquisitionService) acquisitionServiceResp {
return acquisitionServiceResp{
Code: r.Code, Kind: r.Kind, Protocol: r.Protocol, Label: r.Label,
Enabled: r.Enabled, BaseURL: r.BaseUrl,
HasAPIKey: r.ApiKey != "", HasPassword: r.Password != "",
Username: r.Username, Category: r.Category, TimeoutMs: r.TimeoutMs,
ServesSearch: r.ServesSearch, ServesDownloads: r.ServesDownloads,
ServesEnrichment: r.ServesEnrichment,
LocalPath: r.LocalPath, RemotePath: r.RemotePath,
SearchesPerHour: r.SearchesPerHour,
Usable: r.Enabled && r.BaseUrl != "",
}
}
// handleListAcquisitionServices implements GET /api/admin/acquisition/services.
func (h *handlers) handleListAcquisitionServices(w http.ResponseWriter, r *http.Request) {
rows, err := h.acquisition.List(r.Context())
if err != nil {
writeErrWithLog(w, h.logger, "admin: list acquisition services", apierror.Internal(err))
return
}
out := make([]acquisitionServiceResp, len(rows))
for i, row := range rows {
out[i] = acquisitionRespOf(dbq.AcquisitionService{
Code: row.Code, Kind: row.Kind, Protocol: row.Protocol, Label: row.Label,
Enabled: row.Enabled, BaseUrl: row.BaseUrl, Username: row.Username,
Category: row.Category, TimeoutMs: row.TimeoutMs,
ServesSearch: row.ServesSearch, ServesDownloads: row.ServesDownloads,
ServesEnrichment: row.ServesEnrichment, LocalPath: row.LocalPath,
RemotePath: row.RemotePath, SearchesPerHour: row.SearchesPerHour,
})
out[i].HasAPIKey, out[i].HasPassword = row.HasApiKey, row.HasPassword
}
writeJSON(w, http.StatusOK, map[string]any{"services": out})
}
// handleCreateAcquisitionService implements POST
// /api/admin/acquisition/services with {"protocol":
// "prowlarr"|"torznab"|"qbittorrent"|"exchange"}. The row starts switched off,
// with no address.
func (h *handlers) handleCreateAcquisitionService(w http.ResponseWriter, r *http.Request) {
var body struct {
Protocol string `json:"protocol"`
}
if !decodeAcquisitionBody(w, r, &body) {
return
}
row, err := h.acquisition.Create(r.Context(), body.Protocol)
if err != nil {
h.writeAcquisitionErr(w, "admin: create acquisition service", err)
return
}
writeJSON(w, http.StatusCreated, acquisitionRespOf(row))
}
type updateAcquisitionBody struct {
Label string `json:"label"`
Enabled bool `json:"enabled"`
BaseURL string `json:"base_url"`
Username string `json:"username"`
Category string `json:"category"`
TimeoutMs int32 `json:"timeout_ms"`
ServesSearch bool `json:"serves_search"`
ServesDownloads bool `json:"serves_downloads"`
ServesEnrichment bool `json:"serves_enrichment"`
LocalPath string `json:"local_path"`
RemotePath string `json:"remote_path"`
SearchesPerHour int32 `json:"searches_per_hour"`
}
// handleUpdateAcquisitionService implements PUT
// /api/admin/acquisition/services/{code}: the whole form except credentials.
func (h *handlers) handleUpdateAcquisitionService(w http.ResponseWriter, r *http.Request) {
var body updateAcquisitionBody
if !decodeAcquisitionBody(w, r, &body) {
return
}
row, err := h.acquisition.Save(r.Context(), chi.URLParam(r, "code"), acquire.Update(body))
if err != nil {
h.writeAcquisitionErr(w, "admin: update acquisition service", err)
return
}
writeJSON(w, http.StatusOK, acquisitionRespOf(row))
}
// handleDeleteAcquisitionService implements DELETE
// /api/admin/acquisition/services/{code}.
func (h *handlers) handleDeleteAcquisitionService(w http.ResponseWriter, r *http.Request) {
if err := h.acquisition.Delete(r.Context(), chi.URLParam(r, "code")); err != nil {
h.writeAcquisitionErr(w, "admin: delete acquisition service", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// handleTestAcquisitionService implements POST
// /api/admin/acquisition/services/{code}/test. POST because it reaches
// another machine, which a prefetch must not trigger. Always 200 with
// {ok, detail}: a failed connection is the answer, not an error.
func (h *handlers) handleTestAcquisitionService(w http.ResponseWriter, r *http.Request) {
row, err := h.acquisition.Get(r.Context(), chi.URLParam(r, "code"))
if err != nil {
h.writeAcquisitionErr(w, "admin: test acquisition service", err)
return
}
writeJSON(w, http.StatusOK, acquire.Test(r.Context(), row))
}
// handleSetAcquisitionSecret implements PUT and DELETE on
// /api/admin/acquisition/services/{code}/api-key and .../password. PUT takes
// {"value": "..."}; DELETE clears it. 204 with no body either way: echoing
// anything here is how a secret ends up in a response.
func (h *handlers) handleSetAcquisitionSecret(field string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
value := ""
if r.Method == http.MethodPut {
var body struct {
Value string `json:"value"`
}
if !decodeAcquisitionBody(w, r, &body) {
return
}
if body.Value == "" {
writeErr(w, apierror.BadRequest("invalid_setting", "Paste a value, or use Remove to clear the one that is set."))
return
}
value = body.Value
}
code := chi.URLParam(r, "code")
var err error
if field == "password" {
err = h.acquisition.SetPassword(r.Context(), code, value)
} else {
err = h.acquisition.SetAPIKey(r.Context(), code, value)
}
if err != nil {
h.writeAcquisitionErr(w, "admin: set acquisition "+field, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
}
func decodeAcquisitionBody(w http.ResponseWriter, r *http.Request, into any) bool {
err := json.NewDecoder(http.MaxBytesReader(w, r.Body, acquisitionBodyLimit)).Decode(into)
if err != nil && !errors.Is(err, io.EOF) {
writeErr(w, apierror.BadRequest("invalid_body", "malformed JSON"))
return false
}
return true
}
func (h *handlers) writeAcquisitionErr(w http.ResponseWriter, msg string, err error) {
var invalid *acquire.InvalidError
switch {
case errors.As(err, &invalid):
writeErr(w, apierror.BadRequest("invalid_setting", invalid.Message))
case errors.Is(err, acquire.ErrNotFound):
writeErr(w, apierror.NotFound("service"))
case errors.Is(err, acquire.ErrTooMany):
writeErr(w, apierror.Conflict("too_many_services", "There are already twenty of these. Remove one you no longer use first."))
default:
writeErrWithLog(w, h.logger, msg, apierror.Internal(err))
}
}
+94
View File
@@ -0,0 +1,94 @@
package api
import (
"encoding/json"
"errors"
"net/http"
"strings"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/backup"
)
// GET /api/admin/backups — the backup's verdict, settings and recent runs.
func (h *handlers) handleGetBackups(w http.ResponseWriter, r *http.Request) {
st, err := h.backups.Status(r.Context())
if err != nil {
writeErrWithLog(w, h.logger, "admin backups: status", apierror.Internal(err))
return
}
writeJSON(w, http.StatusOK, st)
}
func decodeBackupUpdate(w http.ResponseWriter, r *http.Request) (backup.Update, bool) {
var u backup.Update
if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
writeErr(w, apierror.BadRequest("invalid_body", ""))
return u, false
}
return u, true
}
// fieldErr writes a setting that can't be kept as a 400 whose message says
// which setting and why, and reports whether err was one.
func fieldErr(w http.ResponseWriter, err error) bool {
var fe *backup.FieldError
if !errors.As(err, &fe) {
return false
}
writeErr(w, apierror.BadRequest("invalid_backup_setting", fe.Message))
return true
}
// PUT /api/admin/backups — save the settings. An empty secret_key keeps the
// stored one. Returns the new status.
func (h *handlers) handleUpdateBackups(w http.ResponseWriter, r *http.Request) {
u, ok := decodeBackupUpdate(w, r)
if !ok {
return
}
if err := h.backups.Save(r.Context(), u); err != nil {
if !fieldErr(w, err) {
writeErrWithLog(w, h.logger, "admin backups: save", apierror.Internal(err))
}
return
}
h.handleGetBackups(w, r)
}
// POST /api/admin/backups/test — check the destination in the body without
// saving it, by listing the backups already there. Nothing is written.
func (h *handlers) handleTestBackups(w http.ResponseWriter, r *http.Request) {
u, ok := decodeBackupUpdate(w, r)
if !ok {
return
}
res, err := h.backups.Test(r.Context(), u)
if err != nil {
if fieldErr(w, err) {
return
}
msg := strings.TrimPrefix(err.Error(), "backup: ")
writeErr(w, &apierror.Error{Status: http.StatusBadGateway, Code: "destination_failed", Message: msg})
return
}
writeJSON(w, http.StatusOK, res)
}
// POST /api/admin/backups/run — start a backup now. 202 once it has started;
// 409 while one runs or before the destination is set up.
func (h *handlers) handleRunBackup(w http.ResponseWriter, r *http.Request) {
err := h.backups.Start(r.Context(), backup.TriggerManual)
switch {
case err == nil:
w.WriteHeader(http.StatusAccepted)
case errors.Is(err, backup.ErrRunning):
writeErr(w, apierror.Conflict("backup_running", "A backup is already running."))
case errors.Is(err, backup.ErrNotReady):
writeErr(w, apierror.Conflict("backup_not_ready", "Set up where backups go first."))
case errors.Is(err, backup.ErrClosed):
writeErr(w, apierror.Conflict("shutting_down", "The server is shutting down."))
default:
writeErrWithLog(w, h.logger, "admin backups: start", apierror.Internal(err))
}
}
+5 -10
View File
@@ -459,21 +459,19 @@ type refetchDuplicateRequest struct {
KeepTrackID string `json:"keep_track_id"`
}
// refetchDuplicateResponse reports what went. Blocked names the releases set
// aside; empty when the album came from before Minstrel downloaded anything.
// refetchDuplicateResponse reports what went.
type refetchDuplicateResponse struct {
KeptTrackID *string `json:"kept_track_id"`
RemovedPaths []string `json:"removed_paths"`
Blocked []string `json:"blocked"`
}
// handleRefetchDuplicateGroup implements POST
// /api/admin/library/duplicates/{id}/refetch: settle a group of one
// recording in several slots of an album the way the resolver would, with an
// admin's answer. The copies in slots that are not the recording's are
// removed and marked missing, the release they came from is set aside, and the
// album is wanted again. Merge is the wrong action there: it keeps one title
// whether or not it is the audio's, and fetches nothing.
// removed and marked missing, so the slot shows as missing until a good copy
// arrives in the library. Merge is the wrong action there: it keeps one title
// whether or not it is the audio's.
//
// Errors:
// - 409 library_not_writable / 500 file_delete_failed when a file could not be
@@ -525,10 +523,7 @@ func (h *handlers) handleRefetchDuplicateGroup(w http.ResponseWriter, r *http.Re
return
}
resp := refetchDuplicateResponse{RemovedPaths: make([]string, 0, len(res.Removed)), Blocked: res.Blocked}
if resp.Blocked == nil {
resp.Blocked = []string{}
}
resp := refetchDuplicateResponse{RemovedPaths: make([]string, 0, len(res.Removed))}
if res.Kept != nil {
id := uuidToString(res.Kept.TrackID)
resp.KeptTrackID = &id
-285
View File
@@ -1,285 +0,0 @@
package api
import (
"encoding/json"
"errors"
"net/http"
"github.com/jackc/pgx/v5"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/importer"
"git.fabledsword.com/bvandeusen/minstrel/internal/lifecycle"
)
// Downloads and their imports: the Wanted view's Activity tab,
// a person's "import anyway", "refuse" and "retry", and the Blocked tab.
// downloadView is one grab and what its import made of it.
type downloadView struct {
ID string `json:"id"`
WantID *string `json:"want_id"`
WantTitle string `json:"want_title"`
WantArtist string `json:"want_artist"`
Name string `json:"name"`
Indexer string `json:"indexer"`
Client string `json:"client"`
Quality string `json:"quality"`
Origin string `json:"origin"`
GrabbedAt string `json:"grabbed_at"`
EndedAt *string `json:"ended_at"`
EndReason string `json:"end_reason"`
Progress float32 `json:"progress"`
ImportState string `json:"import_state"`
ImportReason string `json:"import_reason"`
ImportedAt *string `json:"imported_at"`
ImportedFiles int32 `json:"imported_files"`
Destination string `json:"destination"`
Edition string `json:"edition,omitempty"`
Evidence *importer.Evidence `json:"evidence,omitempty"`
Files []string `json:"files"`
Skipped int `json:"skipped"`
RehomedFrom string `json:"rehomed_from,omitempty"`
// EndDetail says why an ended download ended.
EndDetail string `json:"end_detail"`
// Seeding: imported and still sharing; Ratio its share ratio as last
// read; SeedReleasedAt when it was removed once it had shared enough.
Seeding bool `json:"seeding"`
Ratio float32 `json:"ratio"`
SeedReleasedAt *string `json:"seed_released_at"`
// Condition is what is wrong with it now, if anything.
Condition *conditionView `json:"condition"`
}
// conditionView is an open row of the intervention ledger: what was seen,
// since when, and how many times it was retried.
type conditionView struct {
Trigger string `json:"trigger"`
Detail string `json:"detail"`
Retries int32 `json:"retries"`
Since string `json:"since"`
}
func downloadFrom(g dbq.ListGrabsRow) downloadView {
v := downloadView{
ID: uuidToString(g.ID), Name: g.Name, Indexer: g.Indexer, Client: g.Client, Quality: g.Quality,
Origin: g.Origin, GrabbedAt: formatTimestamp(g.GrabbedAt), EndReason: g.EndReason,
Progress: g.Progress, ImportState: g.ImportState, ImportReason: g.ImportReason,
ImportedFiles: g.ImportedFiles, Destination: g.Destination, Files: []string{},
EndDetail: g.EndDetail, Seeding: g.Seeding, Ratio: g.Ratio,
}
if g.SeedReleasedAt.Valid {
at := formatTimestamp(g.SeedReleasedAt)
v.SeedReleasedAt = &at
}
if g.Condition != nil {
v.Condition = &conditionView{Trigger: *g.Condition, Detail: deref(g.ConditionDetail),
Since: formatTimestamp(g.ConditionSince)}
if g.ConditionRetries != nil {
v.Condition.Retries = *g.ConditionRetries
}
}
if g.WantID.Valid {
id := uuidToString(g.WantID)
v.WantID = &id
}
if g.WantTitle != nil {
v.WantTitle = *g.WantTitle
}
if g.WantArtist != nil {
v.WantArtist = *g.WantArtist
}
if g.EndedAt.Valid {
at := formatTimestamp(g.EndedAt)
v.EndedAt = &at
}
if g.ImportedAt.Valid {
at := formatTimestamp(g.ImportedAt)
v.ImportedAt = &at
}
var det importer.Detail
if len(g.ImportDetail) > 0 && json.Unmarshal(g.ImportDetail, &det) == nil && det.Verdict.Outcome != "" {
ev := det.Verdict.Evidence
v.Evidence, v.Edition, v.Skipped, v.RehomedFrom = &ev, det.Edition, det.Skipped, det.RehomedFrom
if det.Files != nil {
v.Files = det.Files
}
}
return v
}
type downloadsPage struct {
Items []downloadView `json:"items"`
Limit int `json:"limit"`
Offset int `json:"offset"`
// ClientsDown are the download clients not answering now.
ClientsDown []clientDownView `json:"clients_down"`
}
type clientDownView struct {
Client string `json:"client"`
Detail string `json:"detail"`
Since string `json:"since"`
}
// handleListDownloads implements GET /api/admin/downloads?offset=: running
// downloads first, then the rest newest first.
func (h *handlers) handleListDownloads(w http.ResponseWriter, r *http.Request) {
limit, offset, err := parsePaging(r.URL.Query())
if err != nil {
writeErr(w, apierror.BadRequest("invalid_paging", "limit and offset must be numbers"))
return
}
rows, err := dbq.New(h.pool).ListGrabs(r.Context(), dbq.ListGrabsParams{MaxRows: int32(limit), Skip: int32(offset)})
if err != nil {
writeErrWithLog(w, h.logger, "admin downloads: list", apierror.Internal(err))
return
}
down, err := dbq.New(h.pool).ListClientsDown(r.Context())
if err != nil {
writeErrWithLog(w, h.logger, "admin downloads: clients down", apierror.Internal(err))
return
}
out := downloadsPage{Items: make([]downloadView, 0, len(rows)), Limit: limit, Offset: offset,
ClientsDown: make([]clientDownView, 0, len(down))}
for _, g := range rows {
out.Items = append(out.Items, downloadFrom(g))
}
for _, c := range down {
out.ClientsDown = append(out.ClientsDown, clientDownView{Client: c.Client, Detail: c.Detail,
Since: formatTimestamp(c.FirstSeen)})
}
writeJSON(w, http.StatusOK, out)
}
// handleAbandonDownload implements POST /api/admin/downloads/{id}/abandon: a
// running download is given up, its release set aside, the download removed
// and the album searched again.
func (h *handlers) handleAbandonDownload(w http.ResponseWriter, r *http.Request) {
admin, ok := requireUser(w, r)
if !ok {
return
}
id, ok := requireURLUUID(w, r, "id")
if !ok {
return
}
if _, err := h.lifecycle.Abandon(r.Context(), id, admin.ID); err != nil {
switch {
case errors.Is(err, pgx.ErrNoRows), errors.Is(err, lifecycle.ErrNotAbandonable):
writeErr(w, apierror.Conflict("not_running", "that download is no longer running"))
default:
writeErrWithLog(w, h.logger, "admin downloads: abandon", apierror.Internal(err))
}
return
}
w.WriteHeader(http.StatusNoContent)
}
// handleImportAnyway implements POST /api/admin/downloads/{id}/import: a
// download the check held for a person (or one that failed) is imported on
// the next pass whatever the check says.
func (h *handlers) handleImportAnyway(w http.ResponseWriter, r *http.Request) {
id, ok := requireURLUUID(w, r, "id")
if !ok {
return
}
if _, err := dbq.New(h.pool).ForceGrabImport(r.Context(), id); err != nil {
h.writeImportErr(w, "import anyway", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// handleRetryImport implements POST /api/admin/downloads/{id}/retry.
func (h *handlers) handleRetryImport(w http.ResponseWriter, r *http.Request) {
id, ok := requireURLUUID(w, r, "id")
if !ok {
return
}
if _, err := dbq.New(h.pool).RetryGrabImport(r.Context(), id); err != nil {
h.writeImportErr(w, "retry", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// handleRefuseDownload implements POST /api/admin/downloads/{id}/refuse: the
// release is blocked, the download removed and the album searched again.
func (h *handlers) handleRefuseDownload(w http.ResponseWriter, r *http.Request) {
admin, ok := requireUser(w, r)
if !ok {
return
}
id, ok := requireURLUUID(w, r, "id")
if !ok {
return
}
if _, err := h.importer.Refuse(r.Context(), id, admin.ID); err != nil {
h.writeImportErr(w, "refuse", err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *handlers) writeImportErr(w http.ResponseWriter, what string, err error) {
switch {
case errors.Is(err, pgx.ErrNoRows), errors.Is(err, importer.ErrNotDecidable):
writeErr(w, apierror.Conflict("not_decidable", "that download is not waiting on a decision"))
default:
writeErrWithLog(w, h.logger, "admin downloads: "+what, apierror.Internal(err))
}
}
type releaseBlockView struct {
InfoHash string `json:"info_hash"`
Name string `json:"name"`
Reason string `json:"reason"`
Detail string `json:"detail"`
BlockedAt string `json:"blocked_at"`
// ExpiresAt is when a release given up on may be taken again; null is
// for good.
ExpiresAt *string `json:"expires_at"`
WantTitle string `json:"want_title"`
WantArtist string `json:"want_artist"`
}
type releaseBlocksPage struct {
Items []releaseBlockView `json:"items"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
// handleListReleaseBlocks implements GET /api/admin/release-blocks?offset=:
// every release set aside, by a person or by a check, newest first.
func (h *handlers) handleListReleaseBlocks(w http.ResponseWriter, r *http.Request) {
limit, offset, err := parsePaging(r.URL.Query())
if err != nil {
writeErr(w, apierror.BadRequest("invalid_paging", "limit and offset must be numbers"))
return
}
rows, err := dbq.New(h.pool).ListReleaseBlocksPage(r.Context(), dbq.ListReleaseBlocksPageParams{
MaxRows: int32(limit), Skip: int32(offset)})
if err != nil {
writeErrWithLog(w, h.logger, "admin release blocks: list", apierror.Internal(err))
return
}
out := releaseBlocksPage{Items: make([]releaseBlockView, 0, len(rows)), Limit: limit, Offset: offset}
for _, b := range rows {
v := releaseBlockView{InfoHash: b.InfoHash, Name: b.Name, Reason: b.Reason, Detail: b.Detail,
BlockedAt: formatTimestamp(b.BlockedAt)}
if b.ExpiresAt.Valid {
at := formatTimestamp(b.ExpiresAt)
v.ExpiresAt = &at
}
if b.WantTitle != nil {
v.WantTitle = *b.WantTitle
}
if b.WantArtist != nil {
v.WantArtist = *b.WantArtist
}
out.Items = append(out.Items, v)
}
writeJSON(w, http.StatusOK, out)
}
+1 -127
View File
@@ -2,9 +2,6 @@ package api
import (
"net/http"
"time"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
@@ -15,7 +12,7 @@ import (
// the point: the recording is still a known thing with a title, an artist and
// a play history — only its bytes are absent. LastPlayedAt is nullable because
// plenty of missing files were never played, and that is exactly the signal an
// operator wants when deciding whether to bother re-acquiring one.
// operator wants when deciding whether a lost file is worth replacing.
type missingTrackView struct {
TrackID string `json:"track_id"`
Title string `json:"title"`
@@ -29,18 +26,6 @@ type missingTrackView struct {
LastPlayedAt *string `json:"last_played_at"`
}
// reacquisitionStateView is what the wanted list says about one album: when
// it was wanted back, and when the library
// held it again. A missing album with no want yet is still inside the grace
// window, or MusicBrainz cannot name it. Want is that want as the wanted list
// sends it, so the Missing page can show its search and download and act on
// it.
type reacquisitionStateView struct {
WantedAt *string `json:"wanted_at"`
HeldAt *string `json:"held_at"`
Want *wantView `json:"want"`
}
// missingGroupView is a directory's worth of missing tracks.
//
// Grouping is the whole ergonomic argument for this surface: a reorganised
@@ -52,10 +37,6 @@ type missingGroupView struct {
Directory string `json:"directory"`
MissingSince string `json:"missing_since"`
Tracks []missingTrackView `json:"tracks"`
// Nil when nothing has been attempted for this group's album — the
// common case for a folder that just went missing, and distinct from
// an attempts:0 record, which cannot occur.
Reacquisition *reacquisitionStateView `json:"reacquisition"`
}
// adminMissingResponse is the paged envelope. Total counts TRACKS, not
@@ -99,7 +80,6 @@ func (h *handlers) handleListMissingTracks(w http.ResponseWriter, r *http.Reques
}
groups := groupMissingByDirectory(rows)
h.attachReacquisitionState(r, q, rows, groups)
out := adminMissingResponse{
Total: total,
@@ -154,109 +134,3 @@ func groupMissingByDirectory(rows []dbq.ListMissingTracksRow) []missingGroupView
}
return groups
}
// attachReacquisitionState decorates each group with its album's want.
//
// Best-effort: this is context on a list whose primary job is showing what is
// missing, so a failure here leaves the groups bare rather than failing the
// page. One batched query for the whole page, not one per group.
//
// A group is keyed by directory while a want is keyed by album, and those
// line up in practice (an album's files live in one folder) but are not
// guaranteed to — a directory holding two albums takes the first album's
// state, which is the same album its first track belongs to.
func (h *handlers) attachReacquisitionState(
r *http.Request,
q *dbq.Queries,
rows []dbq.ListMissingTracksRow,
groups []missingGroupView,
) {
if len(groups) == 0 {
return
}
// Directory -> the album its first row belongs to, matching the order
// groupMissingByDirectory folded them in.
dirAlbum := make(map[string]pgtype.UUID, len(groups))
ids := make([]pgtype.UUID, 0, len(groups))
// The latest loss in each folder: a want held before it is the album
// as it was before its files went, not the library holding it again.
dirLost := make(map[string]time.Time, len(groups))
for _, row := range rows {
if row.MissingSince.Valid && row.MissingSince.Time.After(dirLost[row.Directory]) {
dirLost[row.Directory] = row.MissingSince.Time
}
if _, seen := dirAlbum[row.Directory]; seen {
continue
}
dirAlbum[row.Directory] = row.AlbumID
ids = append(ids, row.AlbumID)
}
wants, err := q.GetWantsForAlbums(r.Context(), ids)
if err != nil {
h.logger.Warn("admin missing: want lookup failed", "err", err)
return
}
// Newest want first, so the first seen per album is its current one.
byAlbum := make(map[string]dbq.GetWantsForAlbumsRow, len(wants))
for _, w := range wants {
if _, seen := byAlbum[uuidToString(w.AlbumID)]; !seen {
byAlbum[uuidToString(w.AlbumID)] = w
}
}
full := h.wantViewsByID(r, q, byAlbum)
for i := range groups {
albumID, ok := dirAlbum[groups[i].Directory]
if !ok {
continue
}
w, ok := byAlbum[uuidToString(albumID)]
if !ok {
continue
}
// Held before its files went (every library album is on the list,
// held): not wanted back yet, which the sweep does once
// the grace window has passed.
if w.FulfilledAt.Valid && !w.FulfilledAt.Time.After(dirLost[groups[i].Directory]) {
continue
}
view := &reacquisitionStateView{}
wantedAt := formatTimestamp(w.WantedAt)
view.WantedAt = &wantedAt
if w.FulfilledAt.Valid {
heldAt := formatTimestamp(w.FulfilledAt)
view.HeldAt = &heldAt
}
if v, ok := full[uuidToString(w.WantID)]; ok {
view.Want = &v
}
groups[i].Reacquisition = view
}
}
// wantViewsByID reads each album's current want in full, keyed by want id.
// Best-effort like the state it decorates: a failure leaves the groups with
// their dates and no want.
func (h *handlers) wantViewsByID(
r *http.Request,
q *dbq.Queries,
byAlbum map[string]dbq.GetWantsForAlbumsRow,
) map[string]wantView {
ids := make([]pgtype.UUID, 0, len(byAlbum))
for _, w := range byAlbum {
ids = append(ids, w.WantID)
}
out := make(map[string]wantView, len(ids))
if len(ids) == 0 {
return out
}
rows, err := q.ListWants(r.Context(), dbq.ListWantsParams{State: "all", WantIds: ids, MaxRows: int32(len(ids))})
if err != nil {
h.logger.Warn("admin missing: want detail lookup failed", "err", err)
return out
}
for _, row := range rows {
out[uuidToString(row.ID)] = wantViewOf(row)
}
return out
}
@@ -1,84 +0,0 @@
package api
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/jackc/pgx/v5/pgtype"
)
// seedMissingWant marks a track's file missing for two days and puts its
// album on the wanted list, held at heldDaysAgo (0 for an open want) and
// last searched with nothing found.
func seedMissingWant(t *testing.T, h *handlers, trackID, albumID pgtype.UUID, group string, heldDaysAgo int) string {
t.Helper()
ctx := context.Background()
if _, err := h.pool.Exec(ctx,
`UPDATE tracks SET missing_since = now() - interval '2 days' WHERE id = $1`, trackID); err != nil {
t.Fatalf("mark missing: %v", err)
}
if _, err := h.pool.Exec(ctx, `DELETE FROM wants WHERE release_group_mbid = $1`, group); err != nil {
t.Fatalf("clear want: %v", err)
}
var id pgtype.UUID
if err := h.pool.QueryRow(ctx,
`INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, reason, album_id,
wanted_at, fulfilled_at, searched_at, search_outcome)
VALUES ($1, 'artist-'||$1, 'Artist', 'Album '||$1, 'library', $2,
now() - interval '30 days',
CASE WHEN $3::int > 0 THEN now() - make_interval(days => $3::int) END,
now() - interval '1 hour', 'nothing')
RETURNING id`, group, albumID, heldDaysAgo).Scan(&id); err != nil {
t.Fatalf("insert want: %v", err)
}
return uuidToString(id)
}
// A folder's album that was held before its files went is not wanted back
// yet (every library album is on the list, held); an open want comes with
// its search, so the Missing page can show it and act on it.
func TestListMissingTracks_WantState(t *testing.T) {
h, pool := testHandlers(t)
truncateLibrary(t, pool)
admin := seedUser(t, pool, "admin", "pw", true)
heldTrack, _ := seedTrackOnDisk(t, h, "missheld")
openTrack, _ := seedTrackOnDisk(t, h, "missopen")
seedMissingWant(t, h, heldTrack.ID, heldTrack.AlbumID, "rg-missing-held", 10)
openID := seedMissingWant(t, h, openTrack.ID, openTrack.AlbumID, "rg-missing-open", 0)
req := withUser(httptest.NewRequest(http.MethodGet, "/api/admin/library/missing", nil), admin)
w := httptest.NewRecorder()
h.handleListMissingTracks(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status %d: %s", w.Code, w.Body.String())
}
var resp adminMissingResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
if len(resp.Groups) != 2 {
t.Fatalf("groups = %d, want 2", len(resp.Groups))
}
byTitle := map[string]missingGroupView{}
for _, g := range resp.Groups {
byTitle[g.Tracks[0].Title] = g
}
if r := byTitle["AdmQ Track missheld"].Reacquisition; r != nil {
t.Errorf("held before the loss: reacquisition = %+v, want none", r)
}
r := byTitle["AdmQ Track missopen"].Reacquisition
if r == nil || r.WantedAt == nil || r.HeldAt != nil {
t.Fatalf("open want: reacquisition = %+v, want wanted and not held", r)
}
if r.Want == nil || r.Want.ID != openID {
t.Fatalf("open want: want = %+v, want id %s", r.Want, openID)
}
if r.Want.Search == nil || r.Want.Search.Outcome != "nothing" {
t.Errorf("open want: search = %+v, want outcome nothing", r.Want.Search)
}
}
-78
View File
@@ -1,78 +0,0 @@
package api
import (
"encoding/json"
"errors"
"net/http"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/reacquisition"
)
// reacquisitionSettingsResp is the admin card's payload.
//
// Carries more than the stored settings: [UnnameableAlbums] is the count of
// albums with missing files that can never be wanted automatically because
// neither they nor their artist has an MBID. The card states that number
// rather than leaving an admin to wonder why some rows never get wanted —
// a feature that silently does nothing for part of its input reads as broken.
type reacquisitionSettingsResp struct {
Enabled bool `json:"enabled"`
GraceHours int32 `json:"grace_hours"`
MaxPerPass int32 `json:"max_per_pass"`
UnnameableAlbums int64 `json:"unnameable_albums"`
}
// handleGetReacquisitionSettings implements GET
// /api/admin/library/reacquisition.
func (h *handlers) handleGetReacquisitionSettings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, h.reacquisitionPayload(r))
}
// handleUpdateReacquisitionSettings implements PUT
// /api/admin/library/reacquisition.
func (h *handlers) handleUpdateReacquisitionSettings(w http.ResponseWriter, r *http.Request) {
var req reacquisitionSettingsResp
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, apierror.BadRequest("invalid_body", "malformed JSON"))
return
}
_, err := h.reacqSettings.Set(r.Context(), reacquisition.Settings{
Enabled: req.Enabled,
GraceHours: req.GraceHours,
MaxPerPass: req.MaxPerPass,
})
if err != nil {
// The Go-side validation mirrors migration 0056's CHECKs so the
// operator gets a readable message naming the field, rather than a
// constraint-violation string leaking through as a 500.
if errors.Is(err, reacquisition.ErrOutOfRange) {
writeErr(w, apierror.BadRequest("invalid_setting", err.Error()))
return
}
writeErrWithLog(w, h.logger, "admin reacquisition: update failed", apierror.Internal(err))
return
}
// Echo the payload recomputed under the new values so the card reflects
// what it just did without a reload.
writeJSON(w, http.StatusOK, h.reacquisitionPayload(r))
}
func (h *handlers) reacquisitionPayload(r *http.Request) reacquisitionSettingsResp {
cur := h.reacqSettings.Get()
out := reacquisitionSettingsResp{
Enabled: cur.Enabled,
GraceHours: cur.GraceHours,
MaxPerPass: cur.MaxPerPass,
}
// Best-effort: the settings are the point of this endpoint, and failing
// the whole card because a count query hiccuped would be the wrong trade.
if n, err := dbq.New(h.pool).CountAlbumsMissingWithoutMbid(r.Context()); err == nil {
out.UnnameableAlbums = n
} else {
h.logger.Warn("admin reacquisition: unnameable count failed", "err", err)
}
return out
}
@@ -67,30 +67,15 @@ func tasteRespFrom(t recsettings.TasteTuning) tasteTuningResp {
}
}
// discoverTuningResp is the Discover scope on the wire.
type discoverTuningResp struct {
TagOverlapWeight float64 `json:"tag_overlap_weight"`
SnoozeDays float64 `json:"snooze_days"`
}
func discoverRespFrom(d recsettings.DiscoverTuning) discoverTuningResp {
return discoverTuningResp{
TagOverlapWeight: d.TagOverlapWeight,
SnoozeDays: d.SnoozeDays,
}
}
// tuningSnapshot is both the GET response and the post-mutation echo:
// current values alongside shipped defaults so the card can mark
// which knobs deviate.
type tuningSnapshot struct {
Profiles map[string]weightsResp `json:"profiles"`
Taste tasteTuningResp `json:"taste"`
Discover discoverTuningResp `json:"discover"`
Shipped struct {
Profiles map[string]weightsResp `json:"profiles"`
Taste tasteTuningResp `json:"taste"`
Discover discoverTuningResp `json:"discover"`
} `json:"shipped"`
}
@@ -102,14 +87,12 @@ func (h *handlers) tuningSnapshot() tuningSnapshot {
recsettings.ScopeSongsLike: weightsRespFrom(h.recSettings.Weights(recsettings.ScopeSongsLike)),
}
out.Taste = tasteRespFrom(h.recSettings.Taste())
out.Discover = discoverRespFrom(h.recSettings.Discover())
out.Shipped.Profiles = map[string]weightsResp{
recsettings.ScopeRadio: weightsRespFrom(recsettings.ShippedRadioWeights()),
recsettings.ScopeDailyMix: weightsRespFrom(recsettings.ShippedDailyMixWeights()),
recsettings.ScopeSongsLike: weightsRespFrom(recsettings.ShippedSongsLikeWeights()),
}
out.Shipped.Taste = tasteRespFrom(recsettings.ShippedTasteTuning())
out.Shipped.Discover = discoverRespFrom(recsettings.ShippedDiscoverTuning())
return out
}
@@ -143,8 +126,6 @@ func (h *handlers) handlePatchRecommendationTuning(w http.ResponseWriter, r *htt
switch scope {
case recsettings.ScopeTaste:
err = h.recSettings.UpdateTaste(r.Context(), body.Values)
case recsettings.ScopeDiscover:
err = h.recSettings.UpdateDiscover(r.Context(), body.Values)
default:
err = h.recSettings.UpdateProfile(r.Context(), scope, body.Values)
}
-190
View File
@@ -1,190 +0,0 @@
package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/notifications"
"git.fabledsword.com/bvandeusen/minstrel/internal/requests"
"git.fabledsword.com/bvandeusen/minstrel/internal/wanted"
)
// validRequestStatuses is the set of allowed values for the ?status= param.
var validRequestStatuses = map[string]bool{
"pending": true,
"approved": true,
"rejected": true,
"completed": true,
"failed": true,
}
// handleListAdminRequests implements GET /api/admin/requests.
// ?status= defaults to "pending"; ?limit= defaults to 50, max 200.
func (h *handlers) handleListAdminRequests(w http.ResponseWriter, r *http.Request) {
status := r.URL.Query().Get("status")
if status == "" {
status = "pending"
}
if !validRequestStatuses[status] {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_status")
return
}
limitStr := r.URL.Query().Get("limit")
limit := 50
if limitStr != "" {
v, err := strconv.Atoi(limitStr)
if err != nil || v <= 0 {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_limit")
return
}
if v > 200 {
v = 200
}
limit = v
}
rows, err := h.requests.ListByStatus(r.Context(), status, int32(limit))
if err != nil {
h.logger.Error("admin: list requests", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
return
}
q := dbq.New(h.pool)
names := requesterNames(r.Context(), q, rows)
out := make([]requestView, 0, len(rows))
for _, row := range rows {
v := requestViewFrom(row)
v.Username = names[row.UserID]
fillProgress(r.Context(), q, row, &v)
out = append(out, v)
}
writeJSON(w, http.StatusOK, out)
}
// requesterNames maps each request's user id to that user's username, in one
// query for the whole page. Like fillProgress, a failed lookup is swallowed:
// the names are a reporting nicety, and the page falls back to the id.
func requesterNames(ctx context.Context, q *dbq.Queries, rows []dbq.Request) map[pgtype.UUID]string {
ids := make([]pgtype.UUID, 0, len(rows))
for _, row := range rows {
ids = append(ids, row.UserID)
}
names := make(map[pgtype.UUID]string, len(rows))
users, err := q.ListUsernamesByIDs(ctx, ids)
if err != nil {
return names
}
for _, u := range users {
names[u.ID] = u.Username
}
return names
}
// approveRequestBody is the optional JSON body for POST
// /api/admin/requests/:id/approve. profile_id picks the release-type profile an
// artist request is followed on; omitted, the default profile.
type approveRequestBody struct {
ProfileID string `json:"profile_id"`
}
// handleApproveRequest implements POST /api/admin/requests/:id/approve. The
// request goes on the wanted list: an album or track request
// wants its album, an artist request follows the artist.
func (h *handlers) handleApproveRequest(w http.ResponseWriter, r *http.Request) {
admin, ok := auth.UserFromContext(r.Context())
if !ok {
writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized")
return
}
id, ok := parseUUID(chi.URLParam(r, "id"))
if !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
return
}
var body approveRequestBody
// Body is entirely optional; ignore decode errors.
_ = json.NewDecoder(r.Body).Decode(&body)
var profile pgtype.UUID
if body.ProfileID != "" {
if profile, ok = parseUUID(body.ProfileID); !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_profile")
return
}
}
row, err := h.requests.Approve(r.Context(), id, admin.ID, profile)
if err != nil {
switch {
case errors.Is(err, requests.ErrNotFound):
writeAdminJSONErr(w, http.StatusNotFound, "request_not_found")
case errors.Is(err, requests.ErrNotPending):
writeAdminJSONErr(w, http.StatusConflict, "request_not_pending")
case errors.Is(err, wanted.ErrProfileNotFound):
writeAdminJSONErr(w, http.StatusBadRequest, "profile_not_found")
case errors.Is(err, wanted.ErrNotFollowable):
writeAdminJSONErr(w, http.StatusBadRequest, "not_followable")
default:
h.logger.Error("admin: approve request", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
}
return
}
h.notifyRequestDecided(r.Context(), notifications.KindRequestApproved, admin, row, "")
h.publishRequestStatusChanged(row)
writeJSON(w, http.StatusOK, requestViewFrom(row))
}
// rejectRequestBody is the optional JSON body for POST
// /api/admin/requests/:id/reject.
type rejectRequestBody struct {
Notes string `json:"notes"`
}
// handleRejectRequest implements POST /api/admin/requests/:id/reject.
func (h *handlers) handleRejectRequest(w http.ResponseWriter, r *http.Request) {
admin, ok := auth.UserFromContext(r.Context())
if !ok {
writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized")
return
}
id, ok := parseUUID(chi.URLParam(r, "id"))
if !ok {
writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id")
return
}
var body rejectRequestBody
_ = json.NewDecoder(r.Body).Decode(&body)
row, err := h.requests.Reject(r.Context(), id, admin.ID, body.Notes)
if err != nil {
switch {
case errors.Is(err, requests.ErrNotFound):
writeAdminJSONErr(w, http.StatusNotFound, "request_not_found")
case errors.Is(err, requests.ErrNotPending):
writeAdminJSONErr(w, http.StatusConflict, "request_not_pending")
default:
h.logger.Error("admin: reject request", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
}
return
}
h.notifyRequestDecided(r.Context(), notifications.KindRequestRejected, admin, row, body.Notes)
h.publishRequestStatusChanged(row)
writeJSON(w, http.StatusOK, requestViewFrom(row))
}
-335
View File
@@ -1,335 +0,0 @@
package api
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/go-chi/chi/v5"
"git.fabledsword.com/bvandeusen/minstrel/internal/auth"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// newAdminRequestsRouter builds a test chi router with the three admin/requests
// endpoints. RequireAdmin middleware is applied. Tests inject a user into
// context directly (skipping RequireUser).
func newAdminRequestsRouter(h *handlers) chi.Router {
r := chi.NewRouter()
r.Route("/api/admin", func(admin chi.Router) {
admin.Use(auth.RequireAdmin())
admin.Get("/requests", h.handleListAdminRequests)
admin.Post("/requests/{id}/approve", h.handleApproveRequest)
admin.Post("/requests/{id}/reject", h.handleRejectRequest)
})
return r
}
// doAdminRequestReq fires an HTTP request at the admin requests router with
// the given user injected into context (bypassing RequireUser).
func doAdminRequestReq(t *testing.T, h *handlers, method, path string, body []byte, user dbq.User) *httptest.ResponseRecorder {
t.Helper()
var reqBody *bytes.Buffer
if body != nil {
reqBody = bytes.NewBuffer(body)
} else {
reqBody = bytes.NewBuffer(nil)
}
req := httptest.NewRequest(method, path, reqBody)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req = withUser(req, user)
w := httptest.NewRecorder()
newAdminRequestsRouter(h).ServeHTTP(w, req)
return w
}
// seedPendingArtistRequest creates a pending artist-kind request row
// for the given user and returns its parsed requestView.
func seedPendingArtistRequest(t *testing.T, h *handlers, user dbq.User, artistMBID, artistName string) requestView {
t.Helper()
return createArtistRequest(t, h, user, artistMBID, artistName)
}
// TestHandleListAdminRequests_DefaultStatus_Pending seeds 2 pending + 1
// rejected and verifies that GET without ?status returns only the 2 pending
// rows.
func TestHandleListAdminRequests_DefaultStatus_Pending(t *testing.T) {
h, _ := testHandlers(t)
resetRequests(t, h)
alice := seedUser(t, h.pool, "alice", "pw", false)
admin := seedUser(t, h.pool, "admin", "pw", true)
createArtistRequest(t, h, alice, "mbid-pending-1", "Pending Artist 1")
createArtistRequest(t, h, alice, "mbid-pending-2", "Pending Artist 2")
// Reject one request directly via service.
rv3 := createArtistRequest(t, h, alice, "mbid-reject-1", "Reject Me")
_, err := h.requests.Reject(context.Background(), rv3.ID, admin.ID, "test")
if err != nil {
t.Fatalf("reject seed: %v", err)
}
w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests", nil, admin)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
}
var results []requestView
if err := json.Unmarshal(w.Body.Bytes(), &results); err != nil {
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
}
if len(results) != 2 {
t.Fatalf("len(results) = %d, want 2 (pending only)", len(results))
}
for _, rv := range results {
if rv.Status != "pending" {
t.Errorf("result status = %q, want pending", rv.Status)
}
if rv.Username != alice.Username {
t.Errorf("result username = %q, want %q (the requester)", rv.Username, alice.Username)
}
}
}
// TestHandleListAdminRequests_StatusFilter verifies GET ?status=rejected
// returns only rejected rows.
func TestHandleListAdminRequests_StatusFilter(t *testing.T) {
h, _ := testHandlers(t)
resetRequests(t, h)
alice := seedUser(t, h.pool, "alice", "pw", false)
admin := seedUser(t, h.pool, "admin", "pw", true)
createArtistRequest(t, h, alice, "mbid-pending-f1", "Pending Filter 1")
rv2 := createArtistRequest(t, h, alice, "mbid-rejected-f1", "Rejected Filter 1")
_, err := h.requests.Reject(context.Background(), rv2.ID, admin.ID, "")
if err != nil {
t.Fatalf("reject seed: %v", err)
}
w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests?status=rejected", nil, admin)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
}
var results []requestView
if err := json.Unmarshal(w.Body.Bytes(), &results); err != nil {
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
}
if len(results) != 1 {
t.Fatalf("len(results) = %d, want 1 rejected row", len(results))
}
if results[0].Status != "rejected" {
t.Errorf("status = %q, want rejected", results[0].Status)
}
}
// TestHandleListAdminRequests_BadStatus_400 verifies GET with an invalid
// ?status returns 400.
func TestHandleListAdminRequests_BadStatus_400(t *testing.T) {
h, _ := testHandlers(t)
resetRequests(t, h)
admin := seedUser(t, h.pool, "admin", "pw", true)
w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests?status=garbage", nil, admin)
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String())
}
var resp map[string]string
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
}
if resp["error"] != "invalid_status" {
t.Errorf("error = %q, want invalid_status", resp["error"])
}
}
// TestHandleApproveRequest_NotPending_409 pre-rejects a row and verifies
// POST /approve → 409 request_not_pending.
func TestHandleApproveRequest_NotPending_409(t *testing.T) {
h, _ := testHandlers(t)
resetRequests(t, h)
alice := seedUser(t, h.pool, "alice", "pw", false)
admin := seedUser(t, h.pool, "admin", "pw", true)
rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-notpending", "Not Pending")
// Pre-reject the row.
_, err := h.requests.Reject(context.Background(), rv.ID, admin.ID, "pre-rejected")
if err != nil {
t.Fatalf("pre-reject: %v", err)
}
w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", nil, admin)
if w.Code != http.StatusConflict {
t.Fatalf("status = %d, want 409; body = %s", w.Code, w.Body.String())
}
var resp map[string]string
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
}
if resp["error"] != "request_not_pending" {
t.Errorf("error = %q, want request_not_pending", resp["error"])
}
}
// TestHandleRejectRequest_HappyPath verifies POST /reject with notes returns
// 200 and the row transitions to rejected with notes saved.
func TestHandleRejectRequest_HappyPath(t *testing.T) {
h, _ := testHandlers(t)
resetRequests(t, h)
alice := seedUser(t, h.pool, "alice", "pw", false)
admin := seedUser(t, h.pool, "admin", "pw", true)
rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-reject", "Reject Me")
body := []byte(`{"notes":"low-quality release; will look for the remaster"}`)
w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/reject", body, admin)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
}
var got requestView
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
}
if got.Status != "rejected" {
t.Errorf("status = %q, want rejected", got.Status)
}
if got.Notes == nil || *got.Notes != "low-quality release; will look for the remaster" {
t.Errorf("notes = %v, want expected string", got.Notes)
}
}
// TestHandleRejectRequest_NoNotes_OK verifies POST /reject with empty body
// returns 200 (notes are optional).
func TestHandleRejectRequest_NoNotes_OK(t *testing.T) {
h, _ := testHandlers(t)
resetRequests(t, h)
alice := seedUser(t, h.pool, "alice", "pw", false)
admin := seedUser(t, h.pool, "admin", "pw", true)
rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-reject-nonotes", "Reject No Notes")
w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/reject", nil, admin)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())
}
var got requestView
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
}
if got.Status != "rejected" {
t.Errorf("status = %q, want rejected", got.Status)
}
}
// TestAdminRequestsEndpoints_NonAdmin403 is a table-driven test verifying that
// all 3 admin request endpoints reject non-admin users with 403.
func TestAdminRequestsEndpoints_NonAdmin403(t *testing.T) {
h, _ := testHandlers(t)
resetRequests(t, h)
nonAdmin := seedUser(t, h.pool, "regular", "pw", false)
// Use a placeholder UUID for the ID endpoints.
fakeID := "00000000-0000-0000-0000-000000000001"
cases := []struct {
method string
path string
body []byte
}{
{http.MethodGet, "/api/admin/requests", nil},
{http.MethodPost, "/api/admin/requests/" + fakeID + "/approve", nil},
{http.MethodPost, "/api/admin/requests/" + fakeID + "/reject", nil},
}
for _, tc := range cases {
tc := tc
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
w := doAdminRequestReq(t, h, tc.method, tc.path, tc.body, nonAdmin)
if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String())
}
var resp map[string]string
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
}
if resp["error"] != "not_authorized" {
t.Errorf("error = %q, want not_authorized", resp["error"])
}
})
}
}
// TestHandleApproveRequest_AlbumBecomesAWant: approving an album request puts
// its release group on the wanted list, as the requester's.
func TestHandleApproveRequest_AlbumBecomesAWant(t *testing.T) {
h, _ := testHandlers(t)
resetRequests(t, h)
alice := seedUser(t, h.pool, "alice", "pw", false)
admin := seedUser(t, h.pool, "admin", "pw", true)
w := doCreateRequest(h, alice, `{"kind":"album","artist_mbid":"artist-x","artist_name":"Gorillaz","album_mbid":"group-x","album_title":"Demon Days"}`)
if w.Code != http.StatusCreated {
t.Fatalf("create: %d %s", w.Code, w.Body.String())
}
var rv requestView
_ = json.Unmarshal(w.Body.Bytes(), &rv)
resp := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", nil, admin)
if resp.Code != http.StatusOK {
t.Fatalf("approve: %d %s", resp.Code, resp.Body.String())
}
want, err := dbq.New(h.pool).GetWantByReleaseGroup(context.Background(), "group-x")
if err != nil {
t.Fatalf("no want recorded: %v", err)
}
if want.Title != "Demon Days" || want.CreatedBy != alice.ID || want.Reason != "request" {
t.Errorf("want = %+v", want)
}
}
// TestHandleApproveRequest_ArtistOnTheChosenProfile: an artist request is
// followed on the profile the admin picked; an unknown profile is a 400.
func TestHandleApproveRequest_ArtistOnTheChosenProfile(t *testing.T) {
h, _ := testHandlers(t)
resetRequests(t, h)
alice := seedUser(t, h.pool, "alice", "pw", false)
admin := seedUser(t, h.pool, "admin", "pw", true)
ctx := context.Background()
profile, err := dbq.New(h.pool).CreateReleaseTypeProfile(ctx, dbq.CreateReleaseTypeProfileParams{
Name: "Albums only", PrimaryTypes: []string{"Album"}, SecondaryTypes: []string{},
})
if err != nil {
t.Fatal(err)
}
rv := seedPendingArtistRequest(t, h, alice, "artist-profiled", "Profiled")
path := "/api/admin/requests/" + uuidToString(rv.ID) + "/approve"
if resp := doAdminRequestReq(t, h, http.MethodPost, path, []byte(`{"profile_id":"00000000-0000-4000-8000-000000000000"}`), admin); resp.Code != http.StatusBadRequest {
t.Fatalf("unknown profile: %d %s", resp.Code, resp.Body.String())
}
body := []byte(`{"profile_id":"` + uuidToString(profile.ID) + `"}`)
if resp := doAdminRequestReq(t, h, http.MethodPost, path, body, admin); resp.Code != http.StatusOK {
t.Fatalf("approve: %d %s", resp.Code, resp.Body.String())
}
f, err := dbq.New(h.pool).GetFollow(ctx, "artist-profiled")
if err != nil || f.ProfileID != profile.ID || !f.WantExisting {
t.Errorf("follow = %+v, %v: on Albums only, wanting what exists", f, err)
}
}
-340
View File
@@ -1,340 +0,0 @@
package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"slices"
"time"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"git.fabledsword.com/bvandeusen/minstrel/internal/acquire"
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/release"
"git.fabledsword.com/bvandeusen/minstrel/internal/wanted"
)
// Searching for wants and grabbing releases: the schedule's
// settings, each want's candidates, and a person's Search, Grab and "never
// this one".
// searchTimeout bounds a search a person waits on: a Prowlarr fanning out to
// many trackers can take most of a minute.
const searchTimeout = 2 * time.Minute
type searchSettingsView struct {
AutoGrab bool `json:"auto_grab"`
SearchIntervalHours int32 `json:"search_interval_hours"`
AllowedQualities []string `json:"allowed_qualities"`
Tiers []release.TierInfo `json:"tiers"`
LastPassAt *string `json:"last_pass_at"`
LastPass json.RawMessage `json:"last_pass"`
// ImportRoot is the library folder new music is filed into; ""
// is the first of ScanPaths, the library's folders.
ImportRoot string `json:"import_root"`
ScanPaths []string `json:"scan_paths"`
// The download lifecycle: seed an imported download to this
// ratio or for this many days; give up on one nobody shares after this
// many hours. 0 is: remove once imported, no time limit, never.
SeedRatio float32 `json:"seed_ratio"`
SeedDays int32 `json:"seed_days"`
StallHours int32 `json:"stall_hours"`
// UpgradeUntil is the tier a held album is upgraded to; "" is
// no quality upgrades.
UpgradeUntil string `json:"upgrade_until"`
}
func searchSettings(s dbq.AcquisitionSetting, roots []string) searchSettingsView {
v := searchSettingsView{
AutoGrab: s.AutoGrab, SearchIntervalHours: s.SearchIntervalHours,
AllowedQualities: s.AllowedQualities, Tiers: release.Tiers, LastPass: s.LastPass,
ImportRoot: s.ImportRoot, ScanPaths: roots,
SeedRatio: s.SeedRatio, SeedDays: s.SeedDays, StallHours: s.StallHours,
UpgradeUntil: s.UpgradeUntil,
}
if v.ScanPaths == nil {
v.ScanPaths = []string{}
}
if v.AllowedQualities == nil {
v.AllowedQualities = []string{}
}
if len(v.LastPass) == 0 {
v.LastPass = json.RawMessage("{}")
}
if s.LastPassAt.Valid {
at := formatTimestamp(s.LastPassAt)
v.LastPassAt = &at
}
return v
}
// handleGetSearchSettings implements GET /api/admin/acquisition/settings.
func (h *handlers) handleGetSearchSettings(w http.ResponseWriter, r *http.Request) {
s, err := dbq.New(h.pool).GetAcquisitionSettings(r.Context())
if err != nil {
writeErrWithLog(w, h.logger, "admin search settings: get", apierror.Internal(err))
return
}
writeJSON(w, http.StatusOK, searchSettings(s, h.importer.Roots()))
}
type putSearchSettingsBody struct {
AutoGrab bool `json:"auto_grab"`
SearchIntervalHours int32 `json:"search_interval_hours"`
AllowedQualities []string `json:"allowed_qualities"`
ImportRoot string `json:"import_root"`
SeedRatio float32 `json:"seed_ratio"`
SeedDays int32 `json:"seed_days"`
StallHours int32 `json:"stall_hours"`
UpgradeUntil string `json:"upgrade_until"`
}
// handlePutSearchSettings implements PUT /api/admin/acquisition/settings.
func (h *handlers) handlePutSearchSettings(w http.ResponseWriter, r *http.Request) {
var body putSearchSettingsBody
if !decodeBody(w, r, &body) {
return
}
if body.SearchIntervalHours < 0 || body.SearchIntervalHours > 720 {
writeErr(w, apierror.BadRequest("bad_interval", "search_interval_hours must be between 0 and 720"))
return
}
if len(body.AllowedQualities) == 0 {
writeErr(w, apierror.BadRequest("bad_quality", "allow at least one quality"))
return
}
for _, t := range body.AllowedQualities {
if !release.KnownTier(t) {
writeErr(w, apierror.BadRequest("bad_quality", "unknown quality "+t))
return
}
}
if body.UpgradeUntil != "" && !release.KnownTier(body.UpgradeUntil) {
writeErr(w, apierror.BadRequest("bad_upgrade_until", "unknown quality "+body.UpgradeUntil))
return
}
if body.ImportRoot != "" && !slices.Contains(h.importer.Roots(), body.ImportRoot) {
writeErr(w, apierror.BadRequest("bad_import_root", "file new music into one of the library's folders"))
return
}
if body.SeedRatio < 0 || body.SeedRatio > 100 || body.SeedDays < 0 || body.SeedDays > 365 ||
body.StallHours < 0 || body.StallHours > 720 {
writeErr(w, apierror.BadRequest("bad_lifecycle",
"seed ratio must be 0 to 100, seed days 0 to 365 and stall hours 0 to 720"))
return
}
s, err := dbq.New(h.pool).UpdateAcquisitionSettings(r.Context(), dbq.UpdateAcquisitionSettingsParams{
AutoGrab: body.AutoGrab, SearchIntervalHours: body.SearchIntervalHours, AllowedQualities: body.AllowedQualities,
ImportRoot: body.ImportRoot, SeedRatio: body.SeedRatio, SeedDays: body.SeedDays, StallHours: body.StallHours,
UpgradeUntil: body.UpgradeUntil,
})
if err != nil {
writeErrWithLog(w, h.logger, "admin search settings: put", apierror.Internal(err))
return
}
writeJSON(w, http.StatusOK, searchSettings(s, h.importer.Roots()))
}
// candidateView is one release a want's last search found.
type candidateView struct {
Key string `json:"key"`
Name string `json:"name"`
InfoHash string `json:"info_hash"`
Indexer string `json:"indexer"`
SizeBytes int64 `json:"size_bytes"`
Seeders int32 `json:"seeders"`
FilesCount int32 `json:"files_count"`
Format string `json:"format"`
Quality string `json:"quality"`
Year int32 `json:"year"`
Verdict string `json:"verdict"`
Reason string `json:"reason"`
Reasons json.RawMessage `json:"reasons"`
FoldedFrom []string `json:"folded_from"`
SearchedAt string `json:"searched_at"`
Downloading bool `json:"downloading"`
}
// handleListCandidates implements GET /api/admin/wanted/{id}/candidates.
func (h *handlers) handleListCandidates(w http.ResponseWriter, r *http.Request) {
id, ok := requireURLUUID(w, r, "id")
if !ok {
return
}
q := dbq.New(h.pool)
rows, err := q.ListWantCandidates(r.Context(), id)
if err != nil {
writeErrWithLog(w, h.logger, "admin wanted: candidates", apierror.Internal(err))
return
}
live, err := q.GetLiveGrab(r.Context(), id)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
writeErrWithLog(w, h.logger, "admin wanted: live grab", apierror.Internal(err))
return
}
out := make([]candidateView, 0, len(rows))
for _, c := range rows {
v := candidateView{
Key: c.Key, Name: c.Name, InfoHash: c.InfoHash, Indexer: c.Indexer, SizeBytes: c.SizeBytes,
Seeders: c.Seeders, FilesCount: c.FilesCount, Format: c.Format, Quality: c.Quality, Year: c.Year,
Verdict: c.Verdict, Reason: c.Reason, Reasons: c.Reasons, FoldedFrom: c.FoldedFrom,
SearchedAt: formatTimestamp(c.SearchedAt),
Downloading: live.ID.Valid && live.Key == c.Key,
}
if v.FoldedFrom == nil {
v.FoldedFrom = []string{}
}
if len(v.Reasons) == 0 {
v.Reasons = json.RawMessage("[]")
}
out = append(out, v)
}
writeJSON(w, http.StatusOK, map[string]any{"items": out})
}
// handleSearchWant implements POST /api/admin/wanted/{id}/search: search
// now, as the schedule would, taking the best release when auto-grab is on.
func (h *handlers) handleSearchWant(w http.ResponseWriter, r *http.Request) {
id, ok := requireURLUUID(w, r, "id")
if !ok {
return
}
ctx, cancel := context.WithTimeout(r.Context(), searchTimeout)
defer cancel()
res, err := h.searcher.SearchNow(ctx, id)
if h.writeSearchErr(w, err) {
return
}
writeJSON(w, http.StatusOK, res)
}
type grabBody struct {
Key string `json:"key"`
Force bool `json:"force"`
}
// grabView is what came of a person's grab.
type grabView struct {
Added bool `json:"added"`
Refused bool `json:"refused"`
Gone bool `json:"gone"`
Unconfigured bool `json:"unconfigured"`
Missing string `json:"missing,omitempty"`
Kept bool `json:"kept"`
Replaced bool `json:"replaced"`
Verdict string `json:"verdict,omitempty"`
Reason string `json:"reason,omitempty"`
Error string `json:"error,omitempty"`
}
// handleGrabCandidate implements POST /api/admin/wanted/{id}/grab: take the
// release named by key. The search runs again first, so the indexer's link
// never leaves the server; force takes what the verdict would not.
func (h *handlers) handleGrabCandidate(w http.ResponseWriter, r *http.Request) {
admin, ok := requireUser(w, r)
if !ok {
return
}
id, ok := requireURLUUID(w, r, "id")
if !ok {
return
}
var body grabBody
if !decodeBody(w, r, &body) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), searchTimeout)
defer cancel()
took, err := h.searcher.Take(ctx, id, body.Key, body.Force, admin.ID)
if h.writeSearchErr(w, err) {
return
}
v := grabView{
Added: took.Added, Refused: took.Refused, Gone: took.Gone, Unconfigured: took.Unconfigured,
Missing: took.Missing, Error: took.Error,
}
if took.Chosen != nil {
v.Verdict, v.Reason = string(took.Chosen.Verdict), took.Chosen.Reason
}
if took.Contest != nil {
v.Kept, v.Replaced = took.Contest.Kept, took.Contest.Replaced
if took.Contest.Kept {
v.Reason = took.Contest.Reason
}
}
writeJSON(w, http.StatusOK, v)
}
type blockBody struct {
Key string `json:"key"`
}
// handleBlockCandidate implements POST /api/admin/wanted/{id}/block: never
// take this release again, for any want.
func (h *handlers) handleBlockCandidate(w http.ResponseWriter, r *http.Request) {
admin, ok := requireUser(w, r)
if !ok {
return
}
id, ok := requireURLUUID(w, r, "id")
if !ok {
return
}
var body blockBody
if !decodeBody(w, r, &body) {
return
}
c, err := dbq.New(h.pool).GetWantCandidate(r.Context(), dbq.GetWantCandidateParams{WantID: id, Key: body.Key})
if errors.Is(err, pgx.ErrNoRows) {
writeErr(w, apierror.NotFound("candidate"))
return
}
if err != nil {
writeErrWithLog(w, h.logger, "admin wanted: block", apierror.Internal(err))
return
}
if c.InfoHash == "" {
writeErr(w, apierror.BadRequest("no_infohash", "this release has no infohash to set aside by"))
return
}
if err := acquire.NewMemory(h.pool).Block(r.Context(), dbq.BlockReleaseParams{
InfoHash: c.InfoHash, Name: c.Name, Reason: acquire.BlockOperator, WantID: id, BlockedBy: admin.ID,
}); err != nil {
writeErrWithLog(w, h.logger, "admin wanted: block", apierror.Internal(err))
return
}
w.WriteHeader(http.StatusNoContent)
}
// handleUnblockRelease implements DELETE /api/admin/release-blocks/{hash}.
func (h *handlers) handleUnblockRelease(w http.ResponseWriter, r *http.Request) {
removed, err := acquire.NewMemory(h.pool).Unblock(r.Context(), chi.URLParam(r, "hash"))
if err != nil {
writeErrWithLog(w, h.logger, "admin wanted: unblock", apierror.Internal(err))
return
}
if !removed {
writeErr(w, apierror.NotFound("block"))
return
}
w.WriteHeader(http.StatusNoContent)
}
// writeSearchErr answers a Searcher error, and says whether there was one.
func (h *handlers) writeSearchErr(w http.ResponseWriter, err error) bool {
switch {
case err == nil:
return false
case errors.Is(err, pgx.ErrNoRows):
writeErr(w, apierror.NotFound("want"))
case errors.Is(err, wanted.ErrWantHeld):
writeErr(w, apierror.Conflict("want_held", "the library already holds this album, and it isn't wanted for a better copy"))
default:
writeErrWithLog(w, h.logger, "admin wanted: search", apierror.Internal(err))
}
return true
}
+10 -5
View File
@@ -10,6 +10,7 @@ import (
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/minstrel/internal/mailer"
"git.fabledsword.com/bvandeusen/minstrel/internal/secret"
)
type smtpConfigResp struct {
@@ -76,11 +77,15 @@ func (h *handlers) handleUpdateSMTPConfig(w http.ResponseWriter, r *http.Request
writeErrWithLog(w, h.logger, "admin smtp: get failed", apierror.Internal(err))
return
}
// Preserve existing password when the request sends "" (so the
// admin doesn't have to re-enter it on every save).
password := req.Password
if password == "" {
password = current.Password
// Preserve the stored (sealed) password when the request sends "", so
// the admin doesn't have to re-enter it on every save.
password := current.Password
if req.Password != "" {
password, err = secret.Seal(secret.SMTPPassword.Purpose(), "", req.Password)
if err != nil {
writeErrWithLog(w, h.logger, "admin smtp: seal password", apierror.Internal(err))
return
}
}
if err := q.UpdateSMTPConfig(r.Context(), dbq.UpdateSMTPConfigParams{
Enabled: req.Enabled,
+3 -58
View File
@@ -11,7 +11,7 @@ import (
)
// The admin Overview's status sections: after the verdict, who is
// listening, what is downloading, what the library holds and how much room
// listening, what the library holds and how much room
// it has, and how the server itself is doing. One read for the page, polled
// while it is open.
@@ -36,17 +36,6 @@ type listeningStatusView struct {
LastPlayAt *string `json:"last_play_at"`
}
type downloadsStatusView struct {
Running int64 `json:"running"`
NeedsYou int64 `json:"needs_you"`
NeedsYouSince *string `json:"needs_you_since"`
ImportedDay int64 `json:"imported_day"`
GivenUpDay int64 `json:"given_up_day"`
// Live is the downloads not yet ended, the ones needing a person first.
Live []downloadView `json:"live"`
ClientsDown []clientDownView `json:"clients_down"`
}
// diskView is the filesystem one library folder, or the data folder, sits
// on.
type diskView struct {
@@ -91,15 +80,10 @@ type serverStatusView struct {
type adminStatusView struct {
Listening listeningStatusView `json:"listening"`
Downloads downloadsStatusView `json:"downloads"`
Library libraryStatusView `json:"library"`
Server serverStatusView `json:"server"`
}
// overviewLiveDownloads is how many running downloads the Overview lists;
// Activity has the rest.
const overviewLiveDownloads = 5
// overviewErrors is how many recent errors the Overview lists.
const overviewErrors = 10
@@ -136,12 +120,6 @@ func (h *handlers) handleGetAdminStatus(w http.ResponseWriter, r *http.Request)
out.Listening.LastPlayAt = &at
}
if err := h.downloadsStatus(r, q, &out.Downloads); err != nil {
h.logger.Error("admin status: downloads", "err", err)
writeAdminJSONErr(w, http.StatusInternalServerError, "server_error")
return
}
lib, err := q.LibraryStatus(ctx)
if err != nil {
h.logger.Error("admin status: library", "err", err)
@@ -150,8 +128,8 @@ func (h *handlers) handleGetAdminStatus(w http.ResponseWriter, r *http.Request)
}
out.Library = libraryStatusView{Tracks: lib.Tracks, Albums: lib.Albums, Artists: lib.Artists,
Bytes: lib.Bytes, Disks: []diskView{}}
if h.importer != nil {
for _, root := range h.importer.Roots() {
if h.scanner != nil {
for _, root := range h.scanner.Roots() {
out.Library.Disks = append(out.Library.Disks, diskOf(root))
}
}
@@ -170,39 +148,6 @@ func (h *handlers) handleGetAdminStatus(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, out)
}
func (h *handlers) downloadsStatus(r *http.Request, q *dbq.Queries, out *downloadsStatusView) error {
st, err := q.DownloadsStatus(r.Context())
if err != nil {
return err
}
*out = downloadsStatusView{Running: st.Running, NeedsYou: st.NeedsYou,
ImportedDay: st.ImportedDay, GivenUpDay: st.GivenUpDay,
Live: []downloadView{}, ClientsDown: []clientDownView{}}
if st.NeedsYou > 0 && st.NeedsYouSince.Valid {
since := formatTimestamp(st.NeedsYouSince)
out.NeedsYouSince = &since
}
// ListGrabs puts the ones needing a person first, then the running ones.
rows, err := q.ListGrabs(r.Context(), dbq.ListGrabsParams{MaxRows: overviewLiveDownloads})
if err != nil {
return err
}
for _, g := range rows {
if !g.EndedAt.Valid {
out.Live = append(out.Live, downloadFrom(g))
}
}
down, err := q.ListClientsDown(r.Context())
if err != nil {
return err
}
for _, c := range down {
out.ClientsDown = append(out.ClientsDown, clientDownView{Client: c.Client, Detail: c.Detail,
Since: formatTimestamp(c.FirstSeen)})
}
return nil
}
// diskOf reads the size and free space of the filesystem path is on.
func diskOf(path string) diskView {
var st syscall.Statfs_t

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