Compare commits

..
Author SHA1 Message Date
bvandeusen ccdec49c63 The first public release of Fabled Minstrel
release / web (push) Successful in 1m20s
release / go (push) Successful in 1m50s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 2m38s
release / android (push) Successful in 2m2s
release / Build signed APK (push) Successful in 1m56s
release / Build + push container image (push) Successful in 2m26s
2026-12-03 21:41:57 -05:00
bvandeusenandClaude Opus 5.5 d9a20d5e96 library, acoustid: two more real names the sweep found (#8209)
release / web (push) Successful in 1m29s
release / go (push) Successful in 1m56s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 2m44s
release / android (push) Successful in 2m6s
release / Build signed APK (push) Successful in 1m54s
release / Build + push container image (push) Successful in 17s
A comment named a real artist across a line break, which a per-line search
passes, and two fixture titles were close enough to real ones to replace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:34:54 -05:00
bvandeusenandClaude Opus 5.5 b25fc92e23 Revert the deliberate break (#8358)
release / web (push) Successful in 1m35s
release / go (push) Successful in 2m2s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 2m48s
release / android (push) Successful in 2m0s
release / Build signed APK (push) Successful in 1m54s
release / Build + push container image (push) Successful in 15s
Run 11423 went red on TestPublicRelease_OnlyFromAMainPushBuiltFromTheGatedExport
alone ("the public image build lacks --provenance=false"), in both the go
and integration lanes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:28:21 -05:00
bvandeusenandClaude Opus 5.5 d239a1a4cf test: DELIBERATE BREAK, expected red, reverted next (#8358)
release / web (push) Successful in 1m18s
release / go (push) Failing after 1m48s
release / govulncheck (push) Successful in 20s
release / integration (push) Failing after 2m37s
release / Build + push container image (push) Canceled after 0s
release / android (push) Canceled after 1m42s
release / Build signed APK (push) Canceled after 53s
The public image build loses --provenance=false. TestPublicRelease_
OnlyFromAMainPushBuiltFromTheGatedExport must fail on it. The step runs on
main only, so this run publishes nothing outside :dev either way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:25:25 -05:00
bvandeusenandClaude Opus 5.5 a65a86ea07 tests and comments: invented names for real songs and artists the sweep found (#8209)
release / go (push) Successful in 1m57s
release / web (push) Successful in 1m8s
release / integration (push) Successful in 2m42s
release / govulncheck (push) Successful in 20s
release / android (push) Successful in 1m53s
release / Build signed APK (push) Successful in 1m43s
release / Build + push container image (push) Successful in 24s
The Title Case sweep of the export found real song titles and artists in
fixtures and comments: three songs from one real album, a real song in a
release fixture, real artists in a tag test, a link test and a genre test,
a real song as a notification example, and a count from a real folder.
Each is now invented.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:14:49 -05:00
bvandeusenandClaude Opus 5.5 01cff2b702 ci: the export leaves out .gitattributes too (#8358)
release / web (push) Successful in 1m20s
release / go (push) Successful in 1m48s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 2m39s
release / Build signed APK (push) Successful in 1m51s
release / android (push) Successful in 1m57s
release / Build + push container image (push) Successful in 37s
It only lists what stays out of the export, so it is CI's file, and the
export step refuses a tree that carries it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:13:21 -05:00
bvandeusenandClaude Opus 5.5 5f69cfa792 docs: retake the README screenshots with the Fabled Minstrel header (#8209)
Taken on the invented demo library (tools/demo-library). Now playing has no
header and came out the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:13:07 -05:00
bvandeusenandClaude Opus 5.5 7ced019c77 ci: a merge to main is the public release; every dev push dry-runs it (#8358)
release / go (push) Successful in 1m54s
release / web (push) Successful in 1m29s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 2m44s
release / Build signed APK (push) Successful in 2m1s
release / Build + push container image (push) Failing after 4s
release / android (push) Successful in 2m9s
Every push now builds its image from the git archive export, after the
changelog and the leak gate have run on it, so a dev push is the public
release's dry run. A push to main then also commits and tags the export on
github.com/Fabled-Sword/minstrel as AmateurDungeoneer, publishes
ghcr.io/fabled-sword/minstrel :<name> and :latest, and creates the release
page on GitHub (public changelog) and on this forge (private changelog).

The scripts are Librarian's (ci/changelog.sh, ci/leakgate.sh,
ci/releases.mjs, with their tests), with Minstrel's false positives and a
changelog that ignores the forge-only v* tags from before the public
releases, so the first public release is the fixed note.

The tag build, its APK attach and its verify job, and the manual GHCR
dispatch are gone: phones get the app from the server image, and no
release carries a file. The push trigger has no path filter, because the
README, docs and tests ship in the public release too.

The README's image tags now name what GHCR carries: :latest and :<version>.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:07:36 -05:00
bvandeusenandClaude Opus 5.5 fde5cbbafd library, server: a fixture and a comment the leak gate refuses (#8358)
A hidden-folder fixture named an acquisition tool, and a comment cited a
milestone id. Both are reworded so the export passes ci/leakgate.sh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:07:36 -05:00
bvandeusenandClaude Opus 5.5 126afefd77 Revert the deliberate break (#8316)
release / go (push) Successful in 1m52s
release / integration (push) Successful in 2m23s
release / web (push) Successful in 1m7s
release / govulncheck (push) Successful in 19s
release / android (push) Successful in 1m53s
release / Build signed APK (push) Successful in 1m45s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 16s
release / Verify release artifacts (tag releases only) (push) Skipped
Run 11391 went red on exactly the certificate case (414 passed, 1 failed):
with trust failures unrecognised, the probe fell back to http.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:30:03 -05:00
bvandeusenandClaude Opus 5.5 2824e8fdff android: split the server screen's buttons out of the form (#8316)
release / go (push) Successful in 1m56s
release / web (push) Successful in 1m11s
release / integration (push) Successful in 2m42s
release / govulncheck (push) Successful in 19s
release / android (push) Failing after 2m6s
release / Build signed APK (push) Successful in 2m7s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
The form ran past detekt's 60-line limit for one function once it gained the
probe's progress and Cancel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:22:42 -05:00
bvandeusenandClaude Opus 5.5 b6ae3500ab test: DELIBERATE BREAK, expected red, reverted next (#8316)
release / go (push) Successful in 2m6s
release / android (push) Failing after 38s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 2m25s
release / web (push) Successful in 1m10s
release / Build signed APK (push) Successful in 3m11s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
A certificate that fails to verify is no longer recognised, so the probe falls
back to http past it. ServerProbeTest's certificate case must go red.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:11:06 -05:00
bvandeusenandClaude Opus 5.5 107832b640 android: the server address needs no scheme; the app tries https, then http (#8316)
The sign-in screen took only a full http:// or https:// URL and saved it
unchecked. It now accepts host, host:port or host/path. With no scheme typed
it asks https first and falls back to http only when https could not connect.
A certificate that fails to verify stops the probe instead, so nothing on the
path can force a quiet downgrade. Either way the address must answer
GET /api/auth/setup-status as Minstrel before it is saved, with its scheme.

Plain http still passes the cleartext guard, so the fallback only succeeds on
a home-network address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 11:11:01 -05:00
bvandeusenandClaude Opus 5.5 2ce4fd3edb Revert the deliberate break (#8372)
release / go (push) Successful in 1m52s
release / integration (push) Successful in 2m38s
release / web (push) Successful in 1m8s
release / govulncheck (push) Successful in 19s
release / android (push) Successful in 4m17s
release / Build signed APK (push) Successful in 4m43s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 13s
release / Verify release artifacts (tag releases only) (push) Skipped
This reverts commit 8af3c41b. Runs 11328 and 11329 showed what each lane
prints for a failing test, and that the step goes red with go test's own
status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 22:11:43 -05:00
bvandeusenandClaude Opus 5.5 f5ad422c17 ci: keep go test's status when it fails under -e (#8372)
release / web (push) Successful in 1m33s
release / go (push) Failing after 2m0s
release / govulncheck (push) Successful in 19s
release / integration (push) Failing after 2m45s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 2m34s
release / Build signed APK (push) Canceled after 1m58s
Break run 11328 went red for the wrong reason. The step shell runs with
-e, so a failing go test ended the brace group before `echo $?` wrote
its status; the step then died on `exit ""` ("numeric argument
required"). `|| rc=$?` keeps the group alive to record the status, and a
missing status file now exits 1 rather than relying on that error.

Breaks from 8af3c41b are still in place, so this run must be red with
go test's own exit code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 22:07:27 -05:00
bvandeusenandClaude Opus 5.5 8af3c41b6e test: DELIBERATE BREAK, expected red, reverted next (#8372)
release / web (push) Successful in 1m20s
release / go (push) Failing after 1m48s
release / govulncheck (push) Successful in 18s
release / integration (push) Failing after 2m32s
release / android (push) Failing after 3m29s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 3m44s
Proves the test-count lanes still show a failure and still go red:
- go lane: words TestCount fails a row, and TestDeliberatePanic kills
  the package binary mid-test; both outputs must appear.
- integration lane: quarantine TestFlag_HappyPath fails.
- android lane: BareUdnTest's six rows fail, and the count step still
  runs and reports them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 22:01:44 -05:00
bvandeusenandClaude Opus 5.5 1a8ea1bee9 ci: print how many Go and Android tests ran (#8372)
release / go (push) Successful in 1m51s
release / integration (push) Successful in 2m29s
release / web (push) Successful in 1m2s
release / govulncheck (push) Successful in 20s
release / android (push) Successful in 4m35s
release / Build signed APK (push) Successful in 4m49s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped
The web lane's Vitest summary already says how many tests ran; the go,
integration and android lanes said nothing, so a before-and-after had to
count tests from source.

- ci/testcount reads `go test -json` and prints what plain go test
  would (one line per package, the whole output of a failed test), then
  the pass/fail/skip counts for tests and subtests. Both Go lanes pipe
  through it and exit with go test's own status, kept in a file because
  the shell has no pipefail: the reader never decides the gate.
- The android lane sums Gradle's JUnit reports after the unit tests,
  failure or not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 21:49:35 -05:00
bvandeusenandClaude Opus 5.5 c71b9c1888 Revert the deliberate break (#8301)
release / go (push) Successful in 1m47s
release / integration (push) Successful in 2m35s
release / govulncheck (push) Successful in 20s
release / web (push) Successful in 1m16s
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 / Publish the release image to GHCR (dispatch 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-12-02 17:49:28 -05:00
bvandeusenandClaude Opus 5.5 f8595b9321 test: DELIBERATE BREAK, compile- and detekt-clean markers (#8301)
release / go (push) Successful in 1m50s
release / web (push) Failing after 1m11s
release / integration (push) Successful in 2m39s
release / govulncheck (push) Successful in 19s
release / android (push) Failing after 3m38s
release / Build signed APK (push) Successful in 4m54s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 17:41:08 -05:00
bvandeusenandClaude Opus 5.5 8f411d5ad3 test: DELIBERATE BREAK, keep the else on the drag break's line (#8301)
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / go (push) Canceled after 7s
release / integration (push) Canceled after 0s
release / web (push) Canceled after 0s
release / android (push) Canceled after 0s
release / govulncheck (push) Canceled after 0s
release / Build signed APK (push) Canceled after 0s
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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 17:40:57 -05:00
bvandeusenandClaude Opus 5.5 a81dee30fd test: DELIBERATE BREAK, detekt-clean drag rounding break (#8301)
release / go (push) Canceled after 12s
release / integration (push) Canceled after 0s
release / web (push) Canceled after 0s
release / android (push) Canceled after 0s
release / govulncheck (push) Canceled after 0s
release / Build signed APK (push) Canceled after 0s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 17:40:50 -05:00
bvandeusenandClaude Opus 5.5 74076be610 test: DELIBERATE BREAK, expected red, reverted next (#8301)
release / go (push) Successful in 1m57s
release / integration (push) Successful in 2m48s
release / govulncheck (push) Successful in 23s
release / web (push) Failing after 1m22s
release / android (push) Failing after 1m31s
release / Build signed APK (push) Failing after 3m12s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 17:33:27 -05:00
bvandeusenandClaude Opus 5.5 1bc08244ae test(android): merge repeated cases into tables, drop setter and action-name echoes (#8301)
Repeated cases are parameterized: speaker-id forms, the idle timer, drag
rounding, volume clamping and a playlist's cache verdict. Removed: tests
that a one-line setter set its field, that a mocked null came back null,
that three UPnP commands send the action name written beside them, and
the update repository's copy of the versioning rule its own test holds.
Sonos album play now checks only what its queue adds to GainMath's rule,
which GainMathTest owns. Cover URLs are checked against the host the
interceptors rewrite rather than a copied string. Web's drag table gets
back the 56px case Android's mirrors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 17:30:15 -05:00
bvandeusenandClaude Opus 5.5 e11e2f1649 web: a form's own failure wording shows for an unknown error; drop the unused audio loader seam (#8300)
release / integration (push) Successful in 2m21s
release / go (push) Successful in 1m41s
release / web (push) Successful in 1m1s
release / govulncheck (push) Successful in 18s
release / android (push) Successful in 5m13s
release / Build signed APK (push) Successful in 7m0s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 37s
release / Verify release artifacts (tag releases only) (push) Skipped
errMessage took a fallback but looked codes up with copyForCode, which never
returns nothing, so a settings card's "Couldn't save proxy depth." was
never seen: an unknown code read "Something went wrong." It now uses
knownCopy, as the register page already did, and copyForCode is gone.

audioLoader let a desktop shell swap the stream URL for its own cache. No
such shell exists and nothing called setAudioLoader, so the player reads
the track's stream_url directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 17:14:09 -05:00
bvandeusenandClaude Opus 5.5 877bb7e9c4 test(web): the repeat table pressed Repeat the wrong number of times (#8300)
release / go (push) Successful in 1m52s
release / integration (push) Successful in 2m32s
release / web (push) Successful in 1m9s
release / govulncheck (push) Successful in 18s
release / android (push) Successful in 4m20s
release / Build signed APK (push) Successful in 4m50s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 26s
release / Verify release artifacts (tag releases only) (push) Skipped
Repeat one is two presses from off and repeat all is one; the rows had them
swapped, which the deliberate-break run showed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 16:59:31 -05:00
bvandeusen b0c05891a4 Revert "test: DELIBERATE BREAK, expected red, reverted next (#8300)"
This reverts commit 2bfe6036e3.
2026-12-02 16:59:31 -05:00
bvandeusen 741594dea2 Revert "test: DELIBERATE BREAK, type-valid StageBadge break (#8300)"
This reverts commit 5c4e6ed0d9.
2026-12-02 16:59:31 -05:00
bvandeusenandClaude Opus 5.5 5c4e6ed0d9 test: DELIBERATE BREAK, type-valid StageBadge break (#8300)
release / go (push) Successful in 2m18s
release / web (push) Failing after 1m47s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 3m7s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / android (push) Canceled after 2m33s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 2m8s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 16:51:28 -05:00
bvandeusenandClaude Opus 5.5 2bfe6036e3 test: DELIBERATE BREAK, expected red, reverted next (#8300)
release / web (push) Failing after 20s
release / go (push) Successful in 2m40s
release / govulncheck (push) Successful in 23s
release / integration (push) Successful in 3m30s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 2m57s
release / Build signed APK (push) Canceled after 1m22s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 16:47:04 -05:00
bvandeusenandClaude Opus 5.5 4c4ddf741e test(web): drop URL-echo and scaffold tests, merge repeated cases into tables (#8300)
Client tests that only restated a function's URL, or asserted on the value
their own mock returned, are gone; what those functions do beyond the URL
(escaping an id, leaving out an empty note, paging) keeps a test. Repeated
cases in the player store, row keyboard handling, public routes, register
refusals and others are tables. The shuffle test used an rng that never
swapped, so it could not fail; it now pins the order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 16:46:39 -05:00
bvandeusenandClaude Opus 5.5 5d2c533074 providers: remove TreatAuthAsTransient, which changed only an error's text (#8299)
release / go (push) Successful in 1m48s
release / web (push) Successful in 1m19s
release / integration (push) Successful in 2m38s
release / govulncheck (push) Successful in 20s
release / android (push) Successful in 4m29s
release / Build signed APK (push) Successful in 4m57s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped
Without the option a 401 or 403 already fell to the default branch, which
answers ErrTransient without a retry, the same as the option's own branch.
The only difference was "(auth)" in the message. TheAudioDB and both
Last.fm providers set it; none read the message. The reason it gave, that
a bad key retries later instead of settling the row as "none", now sits on
the default branch, and the client's status table checks 401 and 403.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:31:09 -05:00
bvandeusenandClaude Opus 5.5 da21becead Revert the deliberate break (#8299)
Run 11302 failed all ten named tests, and with them apierror's
TestWrite_SendsTheEnvelopeAndHidesAPlainErrorsText and api's
TestFlag_BadReason, which pin the same rules from the handler side.

This reverts commit 21adbc2283.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:30:55 -05:00
bvandeusenandClaude Opus 5.5 21adbc2283 test: DELIBERATE BREAK, expected red, reverted next (#8299)
release / web (push) Successful in 1m43s
release / go (push) Failing after 2m6s
release / govulncheck (push) Successful in 20s
release / integration (push) Failing after 2m48s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 2m8s
release / Build signed APK (push) Canceled after 1m47s
- backup Coverage: a listed table missing from the schema goes unreported
  -> TestCoverage
- scrobble: exactly four minutes no longer qualifies -> TestQualifies
- listenbrainz submit: a 400 retried as transient
  -> TestClient_RefusalsMapToWhatTheWorkerDoes
- playevents: either skip condition alone is a skip
  -> TestRecordPlayEnded_AppliesTheSkipRule
- recsettings: tag scales up to 100 -> TestUpdateTaste_TagScales
- apierror From: a plain error answered 400 -> TestFrom
- auth RequireAdmin: no user in the context passes through
  -> TestRequireAdmin
- providers: a 404 is transient
  -> TestHTTPClient_GetJSON_AnswersNotFoundOrTransient
- quarantine: any reason accepted -> TestService_Refusals
- playsessions: exactly the window starts a new session
  -> TestFindOrCreate_JoinsWithinTheWindowAndStartsAfterIt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:26:57 -05:00
bvandeusenandClaude Opus 5.5 97cb2b2dd1 test(quarantine, playsessions): share one database reset per scenario (#8299)
release / go (push) Successful in 2m10s
release / integration (push) Successful in 3m2s
release / web (push) Successful in 1m30s
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 / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 1m21s
release / Build signed APK (push) Canceled after 42s
- quarantine: the four refusals (a report on a missing track, an unknown
  reason, resolving or deleting a missing track) are one table.
- playsessions: the four window tests are one listener's plays at 0, 15,
  45 and 76 minutes against a 30-minute window: a new session, joining,
  joining at exactly the window, and starting anew.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:22:38 -05:00
bvandeusenandClaude Opus 5.5 cfdbfa30e3 test(backup, scrobble, playevents, recsettings, apierror, auth, providers): merge repeated cases (#8299)
release / web (push) Successful in 1m41s
release / go (push) Successful in 2m4s
release / govulncheck (push) Successful in 23s
release / integration (push) Successful in 3m5s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 4m35s
release / Build signed APK (push) Canceled after 3m53s
- backup: schema coverage's three tests and the three AWS signing
  examples, one table each.
- scrobble: Qualifies' six boundary tests; the ListenBrainz client's
  refusal mapping, twelve tests of the same rule across three calls, one
  table over call x status; the two similarity lookups' success and URL
  tests, one table.
- playevents: the skip rule's three plays share one fixture. Dropped
  TestRecordPlayEnded_SubThreshold_NoEnqueue: the writer only calls
  scrobble.MaybeEnqueue, whose own test and Qualifies' table hold that
  case; the qualifying-play test still proves the writer calls it.
- recsettings: the three tag-scale tests share one database reset.
- apierror: Error() and From, one test each; auth: RequireAdmin's three.
- providers: GetJSON's not-found and transient answers, one table. Its
  two 401 tests expected the same answer with and without
  TreatAuthAsTransient, which changes only the error's text; the table
  says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:16:20 -05:00
bvandeusenandClaude Opus 5.5 b6454270b5 Revert the deliberate break (#8298, #8330)
release / web (push) Successful in 1m36s
release / go (push) Successful in 1m59s
release / Build signed APK (push) Successful in 5m4s
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 2m47s
release / android (push) Successful in 4m42s
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
Run 11291 failed all three named tests. The api package ran its whole suite
past the weakened cost and the lane went on to coverart, which also failed
TestEnrichArtist_APictureFoundIsInTheSyncLog on the fanart-path break.

This reverts commit 359101c451.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:29:14 -05:00
bvandeusenandClaude Opus 5.5 359101c451 test: DELIBERATE BREAK, expected red, reverted next (#8298, #8330)
release / go (push) Failing after 2m4s
release / integration (push) Failing after 3m2s
release / web (push) Successful in 1m49s
release / govulncheck (push) Successful in 22s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 53s
release / android (push) Canceled after 1m43s
The three tests run 11288 could not reach:
- artist enricher: "none" under older providers is not asked again
  -> TestEnrichArtist_WhichArtistsAreAsked
- artist enricher: a fanart path recorded with no fanart
  -> TestEnrichArtist_OnePictureOfTwo
- api: passwordCost default below bcrypt.DefaultCost
  -> TestPasswordCost_StoredPasswordsUseAtLeastBcryptsDefault

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:24:28 -05:00
bvandeusenandClaude Opus 5.5 201ad741ea Revert the deliberate break; the password-cost check is an ordinary test (#8298, #8330)
release / web (push) Successful in 1m33s
release / go (push) Successful in 1m57s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 2m53s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 3m32s
release / Build signed APK (push) Canceled after 3m3s
Run 11288 failed every named test it reached. The api TestMain's cost
check exited the test binary, and the integration lane runs each package's
binary once with no tests to warm the build, so it stopped the lane there
before coverart's database tests ran. The check is now a test of its own:
a weakened cost fails one test and the rest of the lane still runs.

This reverts commit e717e4370d.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:19:14 -05:00
bvandeusenandClaude Opus 5.5 e717e4370d test: DELIBERATE BREAK, expected red, reverted next (#8298, #8330, #8331)
release / integration (push) Failing after 58s
release / govulncheck (push) Successful in 19s
release / go (push) Failing after 2m0s
release / web (push) Successful in 1m35s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 3m28s
release / android (push) Canceled after 4m28s
- lastfm: no key answers transient, not not-found
  -> TestLastfm_AnswersNotFoundWithoutAsking
- deezer: off by default -> TestProviders_IdentityAndDefaults
- artist enricher: "none" under older providers is not asked again
  -> TestEnrichArtist_WhichArtistsAreAsked
- artist enricher: a fanart path recorded with no fanart
  -> TestEnrichArtist_OnePictureOfTwo
- getUser: an admin asking about another gets themself
  -> TestHandleGetUser
- decodePassword: enc: not decoded -> TestDecodePassword
- router: unknown /rest/ paths get the web app
  -> TestRouter_TheWebAppAndTheAPIsKeepTheirOwnPaths
- genretag: commas no longer split -> TestSplit
- api: passwordCost default below bcrypt.DefaultCost -> api's TestMain

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:14:00 -05:00
bvandeusenandClaude Opus 5.5 6ef96be290 api tests hash passwords at bcrypt's lowest cost; one genre splitter (#8330, #8331)
release / web (push) Successful in 1m30s
release / go (push) Successful in 1m55s
release / android (push) Successful in 4m31s
release / Build signed APK (push) Successful in 5m0s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 2m43s
release / Build + push container image (push) Successful in 13s
release / Verify release artifacts (tag releases only) (push) Skipped
#8330: every password the api handlers store goes through hashPassword at
bcrypt.DefaultCost, most of a second per hash under -race, so the password
tests took about 1.4s each, roughly 15s of the package. The cost is now a
package variable the tests' TestMain lowers to MinCost, after refusing a
production default below bcrypt.DefaultCost.

#8331: recommendation and taste each had a splitGenres and subsonic's
hasGenre split inline, the same rule three times. internal/genretag.Split
is the one copy, a stdlib-only leaf, and the two TestSplitGenres tables
are one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 14:05:33 -05:00
bvandeusenandClaude Opus 5.5 10b10b8179 test(coverart, subsonic, server): merge repeated cases into tables (#8298)
release / web (push) Successful in 1m35s
release / go (push) Successful in 1m58s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m0s
release / android (push) Successful in 4m26s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 5m8s
- coverart: the four providers' identity and default tests, Last.fm's five
  not-found-without-asking tests, the four "which artists are asked again"
  database tests (now one reset over four artists), and the thumbnail-only
  and fanart-only tests.
- subsonic: getUser's six tests and decodePassword's three, one table each.
  Dropped TestTokenMD5Derivation: it checked crypto/md5 against a constant
  and called no Minstrel code.
- server: the four web-app-versus-API path tests start one server, not four.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 13:58:07 -05:00
bvandeusenandClaude Opus 5.5 bd95cdb105 Revert the deliberate break (#8297)
release / go (push) Successful in 1m53s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 2m47s
release / android (push) Successful in 4m21s
release / web (push) Successful in 1m23s
release / Build signed APK (push) Successful in 5m2s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 15s
release / Verify release artifacts (tag releases only) (push) Skipped
All eight broken behaviours failed their named tests in run 11283. Also
failing, as expected: the other tests pinning the same rules from other
sides (Discover's own album cap, a genre mix's artist cap, recsettings'
similarity weight, and Subsonic's playlist visibility and write checks).

This reverts commit 60b0edac7a.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 13:47:51 -05:00
bvandeusenandClaude Opus 5.5 60b0edac7a test: DELIBERATE BREAK, expected red, reverted next (#8297)
release / web (push) Successful in 1m19s
release / go (push) Failing after 1m46s
release / govulncheck (push) Successful in 20s
release / integration (push) Failing after 2m38s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 3m8s
release / Build signed APK (push) Canceled after 2m23s
- service.go Get: another user sees a private playlist
  -> TestService_WhoMaySeeAndChangeAPlaylist
- service.go Reorder: duplicate positions accepted
  -> TestService_RefusesBadInput
- system.go: a build never draws covers
  -> TestBuildSystemPlaylists_SufficientActivity
- discover.go: three tracks per album
  -> TestCapCandidatesByAlbumAndArtist
- similarity.go Similarity: one seed side still matches
  -> TestSimilarity
- similarity.go ContextualMatchScore: seed likes count
  -> TestContextualMatchScore
- score.go: SimilarityWeight ignored
  -> TestScore
- sessionvector.go: two tracks are enough
  -> TestBuildSessionVector_SeedUntilThreeTracks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 13:43:27 -05:00
bvandeusenandClaude Opus 5.5 a2dae7ec8c test(playlists, recommendation): system-mix builds stop drawing covers no test reads; merge repeated cases (#8297)
release / web (push) Successful in 1m16s
release / go (push) Successful in 1m44s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 2m45s
release / android (push) Successful in 4m29s
release / Build signed APK (push) Successful in 4m40s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped
Timings from one run of the integration lane with -v (39c5b1ed, reverted
here) put the system-mix builds at 1.4-3.8s each, most of the playlists
package's 35s. A build draws a JPEG collage per mix; under -race that is
most of its time, and no build test looked at a cover. The build tests now
pass no data folder, which skips drawing, except SufficientActivity, which
keeps drawing and now checks every mix got a cover: nothing tested that the
build wires covers before.

Merged:
- playlists service: 22 tests become 5 scenario tests (access, bad input,
  partial update, track-list edits, cover-file cleanup), one database
  reset each.
- ARebuildKeepsEachMixsID into DailyNonceDeterminism (both built twice in
  one day); the two You might like builds into one.
- capCandidatesByAlbumAndArtist, Score, Similarity, ContextualMatchScore
  and the session-vector seed rule: one table each.
- LoadCandidates' six contextual-like database tests: the max and seed
  rules are ContextualMatchScore's unit table; the database test keeps what
  only it can see, a like reaching its track and a withdrawn like ignored.

Dropped: Score determinism with a fixed RNG (a pure function), Score's
cold-start case (the same input as the base case), and recencyDecay(nil)
and skipRatio's two cases, which Score's table covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 13:35:36 -05:00
bvandeusenandClaude Opus 5.5 39c5b1ed66 ci: TEMPORARY, print each database test's duration for one run (#8297)
release / go (push) Successful in 1m49s
release / web (push) Successful in 1m15s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 3m14s
release / android (push) Successful in 4m19s
release / Build signed APK (push) Successful in 4m43s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 3s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 13:28:18 -05:00
bvandeusenandClaude Opus 5.5 8ed66cf132 Revert the deliberate break (#8296)
release / web (push) Successful in 1m33s
release / go (push) Successful in 1m57s
release / govulncheck (push) Successful in 17s
release / integration (push) Successful in 3m23s
release / android (push) Successful in 4m26s
release / Build signed APK (push) Successful in 4m56s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 13s
release / Verify release artifacts (tag releases only) (push) Skipped
All seven broken behaviours failed their named tests: five in the go lane
of run 11273 (after 25c7db71 fixed the reconcile case) and the resolver
note and stale-run reap in the integration lane of run 11272.

This reverts commit c03b3e0aa7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:51:32 -05:00
bvandeusenandClaude Opus 5.5 25c7db71b1 test(library): the volume-absent refusals are tested apart from the mark cap (#8296)
release / web (push) Successful in 1m40s
release / go (push) Failing after 2m7s
release / govulncheck (push) Successful in 21s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 1m2s
release / Build signed APK (push) Canceled after 23s
release / integration (push) Canceled after 2m48s
Every case marked every track, so the 25% cap refused before the root
checks were reached: run 11272 broke the empty-root check and the test
still passed. The walk now marks one track of ten and clears a returned
one, which reconcile would do, so only the root and empty-walk checks can
refuse it; and the test asserts nothing was cleared either, since those
checks run before restores.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:48:47 -05:00
bvandeusenandClaude Opus 5.5 c03b3e0aa7 test: DELIBERATE BREAK, expected red, reverted next (#8296)
release / web (push) Successful in 1m59s
release / go (push) Failing after 2m20s
release / govulncheck (push) Successful in 22s
release / integration (push) Failing after 3m59s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 2m54s
release / android (push) Canceled after 3m37s
Seven behaviours broken, each aimed at one rewritten library test that
must fail:
- moved.go: an ambiguous match adopts the first candidate
  -> TestAdoptMovedTrack
- reconcile.go: an empty root passes the mount check
  -> TestReconcileMissing_RefusesWhenAVolumeLooksAbsent
- id3v2genre.go: whole-tag unsynchronisation is not undone
  -> TestReadID3v2GenreValues
- mbids.go: no Vorbis MUSICBRAINZ_TRACKID fallback for the recording
  -> TestReadTagMBIDs
- duplicate_resolve.go: rip and clean notes swapped
  -> TestResolveDuplicates_LinksCopiesAcrossReleasesAndRemovesNothing_Integration
- stage_publisher.go: Flush keeps the tick count
  -> TestStagePublisher_FlushesEveryNTicksAndOnFlush
- trigger.go: a stale run is never reaped
  -> TestTryStartScan_StartsUnlessAFreshScanIsRunning

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:43:13 -05:00
bvandeusenandClaude Opus 5.5 ac8792323c test(library): merge repeated cases into tables, drop tests of other code (#8296)
release / web (push) Successful in 1m30s
release / go (push) Successful in 1m57s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m26s
release / android (push) Successful in 4m40s
release / Build signed APK (push) Successful in 5m12s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 28s
release / Verify release artifacts (tag releases only) (push) Skipped
- Moved-file adoption: 14 tests become one table. uniqueMatch, the row
  converters and pgtype's zero UUID are dropped: the adoption table covers
  the first two, and the third tests pgx.
- Reconcile: marking and its change rows, and restoring and its change rows,
  are one test each; the five "a volume looks absent" refusals are one table.
  Dropped: an error-propagation test.
- Genres: the ID3 reader cases, the normalisers and extractGenres across
  ID3, FLAC, Ogg and MP4 are one table each.
- MusicBrainz tag ids: eleven per-format tests become one table.
- Scan trigger: start / skip / reap is one table. Dropped: a closed-pool test.
- Stage publisher: six tests become three.
- Duplicate resolver: the cross-release cases (rip, renamed, kept as fine,
  two titles) asserted the same outcome once the resolver stopped removing
  files. They become one table that also checks the group's note, which is
  where rip and clean still differ. The auto-resolve-off song-link check
  moves into the existing auto-resolve-off test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:32:36 -05:00
bvandeusenandClaude Opus 5.5 4811ec2ec9 Revert the deliberate break (#8295)
release / go (push) Successful in 1m51s
release / web (push) Successful in 1m16s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m19s
release / Build signed APK (push) Successful in 5m7s
release / android (push) Successful in 4m26s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 22s
release / Verify release artifacts (tag releases only) (push) Skipped
Run 11264 failed every named test:
- TestMountedRoutes_RequireASessionAndAdminRoutesAnAdmin
- TestRegister_AfterTheFirstAccountAnInviteIsTheOnlyWayIn
- TestAdminUsers_DemotingStopsAtTheLastAdmin
- TestHandleLogin_AWrongPasswordAndAnUnknownUserLookAlike
- TestUpdateProfile_ChangesOnlyTheFieldsSent
- TestEnumerate_LeavesHiddenFilesAndFoldersOut

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 11:05:35 -05:00
bvandeusenandClaude Opus 5.5 8e44666131 test(api): the invite-only test starts from exactly one account (#8295)
release / web (push) Successful in 1m17s
release / integration (push) Failing after 3m23s
release / govulncheck (push) Successful in 18s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / go (push) Failing after 1m53s
release / Build signed APK (push) Canceled after 1m3s
release / android (push) Canceled after 1m26s
The deliberate break letting the second account in without an invite did
not fail it: accounts earlier tests made through sign-up have no test
prefix, survive dbtest's reset, and kept the count above one. The test now
clears users first. The deliberate break stays for one more run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 10:56:44 -05:00
bvandeusenandClaude Opus 5.5 22f801d8f1 test(api): the route walk reports a handler it reached instead of crashing (#8295)
release / go (push) Failing after 2m3s
release / web (push) Successful in 1m40s
release / govulncheck (push) Successful in 21s
release / integration (push) Failing after 3m32s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 2m48s
release / android (push) Canceled after 3m28s
With the admin check removed, the walk reached a handler that panicked on
its bare wiring, and the panic ended the whole api test binary, hiding
every other failure. The walk now recovers and names the route that ran
its handler. The deliberate break above stays in place for one more run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 10:51:39 -05:00
bvandeusenandClaude Opus 5.5 6f89c3c212 test: DELIBERATE BREAK, expected red, reverted next (#8295)
release / go (push) Failing after 2m31s
release / web (push) Successful in 1m36s
release / govulncheck (push) Successful in 21s
release / integration (push) Failing after 2m51s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 2m13s
release / Build signed APK (push) Canceled after 1m42s
Proves the reviewed tests can fail. Each break, and the test that must fail:
- admin routes lose RequireAdmin -> TestMountedRoutes_RequireASessionAndAdminRoutesAnAdmin
- the second account signs up without an invite -> TestRegister_AfterTheFirstAccountAnInviteIsTheOnlyWayIn
- the last admin can be demoted -> TestAdminUsers_DemotingStopsAtTheLastAdmin
- an unknown user gets a different refusal -> TestHandleLogin_AWrongPasswordAndAnUnknownUserLookAlike
- email is stored as typed -> TestUpdateProfile_ChangesOnlyTheFieldsSent
- the scan walks hidden folders -> TestEnumerate_LeavesHiddenFilesAndFoldersOut

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 10:46:59 -05:00
bvandeusenandClaude Opus 5.5 3fd3c1f7c6 test(api): merge repeated cases into tables, drop skips dbtest already makes (#8295)
release / web (push) Successful in 1m34s
release / go (push) Successful in 2m0s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m24s
release / android (push) Successful in 4m46s
release / Build signed APK (push) Successful in 5m12s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 29s
release / Verify release artifacts (tag releases only) (push) Skipped
- The like/unlike story runs as one sequence that checks the rows after each step.
- The invite-only sign-up cases are one test, which now also checks that a
  refused sign-up creates no account.
- Demoting an admin, and stopping at the last one, is one test.
- A wrong password and an unknown user are one test, which now also checks
  that the two refusals are identical.
- The cover-path resolver tests repeated the cover handler's tests branch
  for branch; the handler tests stay.
- The Range-from-start stream test only re-checked http.ServeContent.
- The APK's nil-user 401 is covered by the mounted-route walk.
- 68 copies of the MINSTREL_TEST_DATABASE_URL skip go: every one of those
  tests reaches dbtest.Pool, which already skips.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 10:35:48 -05:00
bvandeusenandClaude Opus 5.5 81cc29595b test(api): one walk over the mounted router checks access and id errors (#8295)
release / go (push) Successful in 2m3s
release / web (push) Successful in 1m29s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m29s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 3m28s
release / Build signed APK (push) Canceled after 3m3s
The access tests checked hand-built routers that applied RequireAdmin
themselves, so none could catch a production route mounted outside its
group. One test now walks every route Mount registers: each non-public
route answers 401 without a session, and each admin route 403 to a
listener. The per-endpoint malformed-id (400) and unknown-id (404) tests
become one table over the real routes. Profile updates, playlist kind
filters and empty searches each fold into one table; writeErr's envelope
tests move to apierror.Write, which they were testing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 10:29:59 -05:00
bvandeusenandClaude Opus 5.5 877e1d2631 fix(library): hidden files and folders are not part of the library (#8305)
A full scan, the watcher's directory watches and the files it queues all
skip any name below a library root that starts with a dot. A download
manager can park replaced copies in a hidden folder, and macOS leaves
"._" files beside the music; neither is a track. A track already indexed
from a hidden path is marked missing at the next full scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 10:29:59 -05:00
bvandeusenandClaude Opus 5.5 0e24fd388f fix(web): ws 8.23.1, past the pong-flood advisory
npm audit flags ws 8.0.0-8.22.2 (GHSA-37g9-w4hg-h9qr). Only jsdom, the
test DOM, pulls it in; the lockfile moves to the patched release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 10:29:59 -05:00
bvandeusenandClaude Opus 5.5 7fe0c68899 ci: the integration lane runs only packages with database tests, built in parallel first
release / web (push) Failing after 5s
release / go (push) Successful in 1m52s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m15s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 4m8s
release / android (push) Canceled after 4m33s
The integration job ran `go test -p 1 -race ./...`: every package, one at
a time, including 18 with no database test whose unit tests the go lane
had already run. -p 1 also serialized compiling, about 50s before the
first test ran.

ci/db-test-packages.sh lists the packages whose tests reach Postgres
(through internal/dbtest or MINSTREL_TEST_DATABASE_URL); a package that
mentions neither cannot run a database test. The job builds those test
binaries with full parallelism (-run '^$'), then runs them serially as
before. make test-integration uses the same list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 10:19:56 -05:00
bvandeusenandClaude Opus 5.5 56285881aa fix(coverart): album art goes to Minstrel's data folder, never beside the music (#8286)
release / go (push) Successful in 1m58s
release / web (push) Successful in 1m25s
release / govulncheck (push) Successful in 22s
release / integration (push) Successful in 4m24s
release / android (push) Successful in 4m33s
release / Build signed APK (push) Successful in 5m4s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped
Another program files the library now. The cover enricher wrote a
cover.jpg into each album folder it found art for, from the files' tags or
from a provider, and an admin's cover retry deleted that file again, even
if the other program had since put its own cover at that path.

The enricher now keeps every cover it writes under
<data>/album-art/<album>/cover.jpg, and a retry removes a cover only from
there. A cover.jpg an older build left beside the music stays, and is read
as the library's own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:24:55 -05:00
bvandeusenandClaude Opus 5.5 c073e41613 fix(library): duplicate auto-resolve is off by default (#8252)
release / go (push) Successful in 2m18s
release / web (push) Successful in 1m34s
release / govulncheck (push) Successful in 22s
release / integration (push) Successful in 4m47s
release / android (push) Successful in 4m46s
release / Build signed APK (push) Successful in 5m35s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 17s
release / Verify release artifacts (tag releases only) (push) Skipped
Other programs file music into the library, so Minstrel acts on
duplicates only once an admin turns this on. Migration 0114 sets the
column default to false and turns the setting off on installs that hold
the old default; the Go default follows, so an unreadable database
behaves like a fresh one. The pass removes no file either way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:29:04 -05:00
bvandeusenandClaude Opus 5.5 677a421675 fix(library): the duplicate resolver never removes a file on its own (#8252)
release / go (push) Successful in 2m28s
release / web (push) Successful in 1m42s
release / govulncheck (push) Successful in 23s
release / integration (push) Successful in 5m9s
release / android (push) Successful in 5m28s
release / Build signed APK (push) Successful in 5m54s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 34s
release / Verify release artifacts (tag releases only) (push) Skipped
Other programs file music into the library now, and a startup pass
deleted a whole album a download manager had just filed, keeping older
loose copies of the same songs. The resolver assumed Minstrel was the
only program writing the library; it is not.

An automatic pass now changes only Minstrel's database:
- copies of one song, on one album or across releases, are linked as one
  song, so likes, plays and mixes count it once, and any group an admin
  may want to thin stays pending for review (and is announced);
- distinct versions are still dismissed, and rips still held back;
- a one-album wrong slot gets a note naming the song MusicBrainz or
  AcoustID says the recording is, for the admin who settles it.

Removing a copy is an admin's merge or wrong-slot settle, as before. When
an admin merges, a copy in a folder named for its album ("Album (Year)",
or its "CD nn" folder) now outranks a loose copy of the same audio.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:09:11 -05:00
bvandeusenandClaude Opus 5.5 63af193b13 fix(web): sign-up and password-reset headings use the display face too
release / web (push) Successful in 1m17s
release / go (push) Successful in 1m50s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 4m1s
release / android (push) Successful in 4m26s
release / Build signed APK (push) Successful in 4m47s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 22s
release / Verify release artifacts (tag releases only) (push) Skipped
The previous commit meant to carry these and didn't.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:33:53 -05:00
bvandeusenandClaude Opus 5.5 c6e4948d26 fix(web): the header name and sign-in headings use the display face
release / web (push) Canceled after 0s
release / android (push) Canceled after 0s
release / govulncheck (push) Canceled after 0s
release / Build signed APK (push) Canceled after 0s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / go (push) Canceled after 8s
release / integration (push) Canceled after 7s
The app name in the header was Inter at weight 600, a weight the house
style doesn't use, and read as a plain label beside Fraunces section
titles. It is the wordmark, so it now takes Fraunces at 500, as page
titles do, from 18px up. The sign-in, sign-up, reset and invite
headings follow the same rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:33:47 -05:00
bvandeusenandClaude Opus 5.5 1aea3e9a1b chore: take workbench pointers and real library data out of the public tree
release / go (push) Successful in 2m1s
release / govulncheck (push) Successful in 20s
release / web (push) Successful in 1m18s
release / integration (push) Successful in 4m11s
release / android (push) Successful in 4m4s
release / Build signed APK (push) Successful in 4m33s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 29s
release / Verify release artifacts (tag releases only) (push) Skipped
A sweep of the export (git archive) against the release leak standard:

- Internal ids in comments: a split "(rule 157)", two "RULE 131" headers
  and a "Preference 172" the id search missed because it was
  case-sensitive.
- Comments that quoted or credited the operator (shuffle caps, mix
  rotation, player bar layout, ID3v1 table).
- Real artists still in the suspect-source fixtures (and the Beck example
  in its comment): replaced with invented ones in the same file shapes.
- "26,171 tracks", a count from a real library, in the plural examples:
  now 12,345.
- Comments pointing at CI files the export leaves out (release.yml, the
  ci-go image, the Gitea keystore secret, an M8 milestone, .dockerignore
  history); client/README describes the release image, not the lanes.
- renovate.json is export-ignore: it targets the workbench's dev branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 06:56:35 -05:00
bvandeusenandClaude Opus 5.5 fb5fb9d4e0 test(recommendation): spread fixtures use hex track ids (#8216)
candBy scans the id into a UUID, so a title starting with 'o' failed to
parse before the test ran.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 06:56:35 -05:00
bvandeusenandClaude Opus 5.5 27e3725e54 fix(recommendation): radio and shuffle keep one artist's songs apart (#8216)
release / web (push) Successful in 1m17s
release / go (push) Failing after 1m42s
release / govulncheck (push) Successful in 17s
release / integration (push) Failing after 3m57s
release / android (push) Successful in 4m23s
release / Build signed APK (push) Successful in 4m50s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
Radio returned its picks in score order, and a seed's own artist matches
it best, so a DROELOE radio opened with four DROELOE songs in a row. The
artist cap bounded how many songs an artist got, not where they played.

SpreadArtists reorders picks so an artist doesn't play again within
three songs where another choice exists. Each slot takes the best
remaining pick outside that gap; when none is, the artist heard longest
ago goes next, so two artists alternate. Which songs are picked doesn't
change. Radio counts the seed's artist as just played; the library
shuffle spreads from a blank start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 06:48:04 -05:00
bvandeusenandClaude Opus 5.5 352720f13f chore(android): stop tracking Android Studio's project state
android/.idea/ has been in .gitignore since the Kotlin rewrite, but the
files committed before that line kept being tracked: the run target, the
JDK, the device list. They are one workstation's IDE state, and the
public export would have carried them. Local copies are kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 06:46:25 -05:00
bvandeusenandClaude Opus 5.5 11b01df446 ci(release): say where GHCR_USER is read from (#8207)
release / web (push) Successful in 1m45s
release / go (push) Successful in 2m13s
release / govulncheck (push) Successful in 23s
release / integration (push) Successful in 4m42s
release / android (push) Successful in 5m4s
release / Build signed APK (push) Successful in 5m9s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch 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-28 20:04:31 -05:00
bvandeusenandClaude Opus 5.5 c6915dfe8f ci(release): GHCR login reads GHCR_USER as a variable or a secret (#8207)
release / android (push) Canceled after 0s
release / govulncheck (push) Canceled after 0s
release / Build signed APK (push) Canceled after 0s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / go (push) Canceled after 10s
release / integration (push) Canceled after 11s
release / web (push) Canceled after 11s
The dry-run dispatch (run 11160) built the release image but showed
vars.GHCR_USER empty while secrets.GHCR_TOKEN was set; a real release
would have stopped at login.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 20:04:23 -05:00
bvandeusenandClaude Opus 5.5 143bb8561c ci(release): a dispatch builds the public release image for GHCR from the export (#8207)
release / web (push) Successful in 1m29s
release / go (push) Successful in 1m58s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 4m17s
release / android (push) Successful in 4m49s
release / Build signed APK (push) Successful in 5m39s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped
A new publishing job, ghcr-release, runs only on a workflow_dispatch with
ghcr_release ticked, behind every verifying lane:

- names the release with ci/version.sh (tag v<name>);
- exports `git archive HEAD`, refuses it if it carries .gitea or ci,
  and matches its tree (staged with add -A -f) to the public repo's
  v<name> tag; a dry run tolerates a missing tag as revision=unreleased;
- stages the freshly built APK and sidecar into the export;
- builds with --provenance=false, labelled source=the GitHub repo,
  revision=the public commit, version=<name>;
- unless ghcr_dry_run (the default), logs in with vars.GHCR_USER and
  secrets.GHCR_TOKEN and pushes :<name> once and :latest. A real run
  must be on main.

image-release stands aside on a GHCR dispatch, so a release moves no
private channel. The concurrency group now includes the event, so a
dispatch and a push on one ref don't cancel each other. The gate test
counts ghcr-release as a publisher and pins its trigger, its export
build, its provenance flag and its source label.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:41:08 -05:00
bvandeusenandClaude Opus 5.5 e1f270362d chore(release): everything that ships points at GitHub and GHCR (#7897)
release / go (push) Successful in 2m7s
release / web (push) Successful in 1m25s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m30s
release / android (push) Successful in 4m39s
release / Build signed APK (push) Successful in 5m10s
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
- Module path: github.com/Fabled-Sword/minstrel, in go.mod, every
  import and the Dockerfile's version ldflags.
- buildinfo.ProjectURL, the contact outside services see in Minstrel's
  User-Agent: https://github.com/Fabled-Sword/minstrel.
- README's compose example pulls ghcr.io/fabled-sword/minstrel:latest.
- docs/security.md sends problem reports to the GitHub issues.
- The demo-library stack builds Minstrel from the checkout, since :dev
  is not published to GHCR.
- hygiene.go's same-site example uses example.com names.

The workbench CI (.gitea/, ci/, export-ignored) still builds and
publishes :dev to the private registry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:28:16 -05:00
bvandeusenandClaude Opus 5.5 18efd01eaa feat(brand): the product calls itself Fabled Minstrel (#8168)
release / go (push) Successful in 1m55s
release / web (push) Successful in 1m27s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m31s
release / android (push) Successful in 4m43s
release / Build signed APK (push) Successful in 5m23s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 25s
release / Verify release artifacts (tag releases only) (push) Skipped
Where Minstrel names itself to a person it now gives its full name:
- the README heading, logo text and first line;
- the default app name, which feeds the browser tab, link previews and
  the header;
- the login heading, which now follows the app-name setting too;
- the emails' brand line and sign-off;
- the default From name for email.

On a phone the header shows the mark alone, as the nav shows its icons
alone; the left lane is too narrow for the full name, and the link's
label still names it. Running text, email subjects, code identifiers and
the Android launcher label keep "Minstrel".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:15:20 -05:00
bvandeusenandClaude Opus 5.5 05e087268a fix(library): a scan and a duplicate-resolver pass never touch the files at once (#8197)
release / go (push) Successful in 2m17s
release / web (push) Successful in 1m29s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m28s
release / android (push) Successful in 4m25s
release / Build signed APK (push) Successful in 5m8s
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
The resolver checked for a running scan once, at the start of a pass. At
boot that check could run before the startup scan recorded its run, and a
scan that began mid-pass was never seen, so the pass removed copies the
scan had listed (23 "no such file" errors on dev, 2026-11-28).

A gate now keeps the two apart for their whole length: a full scan and
each watcher batch hold it, a scan that meets a pass waits for it (up to
30 minutes, then gives up with a named error), and a pass that meets a
scan is put off and tried again a minute later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:28:52 -05:00
bvandeusenandClaude Opus 5.5 7c6c47cdb2 feat(mailer): emails follow a light system theme, and stay dark otherwise
release / go (push) Successful in 2m0s
release / integration (push) Successful in 4m16s
release / web (push) Successful in 1m26s
release / govulncheck (push) Successful in 20s
release / android (push) Successful in 4m23s
release / Build signed APK (push) Successful in 4m52s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 17s
release / Verify release artifacts (tag releases only) (push) Skipped
Every email is still drawn dark inline, so a client that can't tell the
reader's theme shows the app's own look. A stylesheet gives each coloured
element the design system's light colours when the reader's system is
light. A test checks that every element drawn dark carries the class that
lightens it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:15:48 -05:00
bvandeusenandClaude Opus 5.5 c662bc1f90 fix(subsonic): getLyrics by title alone answers nothing when two artists share the title (#8128)
release / go (push) Successful in 1m46s
release / web (push) Successful in 1m15s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m13s
release / android (push) Successful in 4m45s
release / Build signed APK (push) Successful in 5m16s
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
An app that asks for lyrics by title without an artist got the first
matching song with lyrics, which could be another artist's song of the
same name. It now answers empty, so the app can look elsewhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:51:25 -05:00
bvandeusenandClaude Opus 5.5 6ed9db4f0c test(likes): seed the second copy at its own path (#8126)
release / web (push) Successful in 1m39s
release / go (push) Successful in 2m3s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m22s
release / android (push) Successful in 4m43s
release / Build signed APK (push) Successful in 5m41s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 40s
release / Verify release artifacts (tag releases only) (push) Skipped
seedTrack derives the file path from the title, so two copies titled
alike upserted into one row and the test compared a track with itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 12:23:03 -05:00
bvandeusenandClaude Opus 5.5 3557c31416 test(likes): track like and unlike answer 200 with the copies they changed (#8126)
release / web (push) Successful in 1m41s
release / go (push) Successful in 2m5s
release / govulncheck (push) Successful in 20s
release / integration (push) Failing after 4m31s
release / android (push) Successful in 5m2s
release / Build signed APK (push) Successful in 5m34s
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
Three more assertions in likes_test.go still expected 204 from the track
like and unlike routes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 12:09:11 -05:00
bvandeusenandClaude Opus 5.5 4587b0a038 fix(release): outside services see the build's real version in Minstrel's User-Agent (#8129)
release / web (push) Successful in 1m37s
release / go (push) Successful in 2m1s
release / govulncheck (push) Successful in 19s
release / integration (push) Failing after 4m20s
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 3m47s
release / android (push) Canceled after 4m27s
MusicBrainz, the Cover Art Archive and AcoustID ask a client to name
itself with a version and a contact. Minstrel sent three different
strings: Minstrel/1.0 to MusicBrainz, Minstrel/dev to the Cover Art
Archive and no version at all to AcoustID, whatever the build. All three
now come from buildinfo.UserAgent, which carries buildinfo.Version and
the operator's contact address when one is configured, else the project
URL. ProjectURL is that one place to repoint when the project moves
(#7897).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 12:00:41 -05:00
bvandeusenandClaude Opus 5.5 e2172e925e fix(taste): a play still open, or closed unheard, no longer grades as a skip (#8127)
The taste build graded every play in its window, and a play with no
completion ratio and no played duration came out as completion 0: a song
playing during the rebuild, or a row the sweeper closed without hearing
how it ended, counted as abandoned and pushed its artist and tags
negative. Only plays whose completion is known are graded now; an open
play is graded once it ends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 11:59:34 -05:00
bvandeusenandClaude Opus 5.5 698ff23105 fix(likes): the web marks every copy of a liked song, not only the one tapped (#8126)
A like is on the song: the server likes every copy sharing its song_key,
but the web's optimistic update marked only the tapped track, so the
same song on another album or a compilation showed an empty heart until
the liked ids were fetched again. A track like or unlike now answers 200
with the ids of every copy it changed, the asked one first, and the web
marks them all. Clients that ignore the body (Android) are unaffected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 11:58:13 -05:00
bvandeusenandClaude Opus 5.5 1c4307e6ef fix(subsonic): a scrobble of an unknown song answers not found (70) (#8125)
release / web (push) Successful in 1m20s
release / go (push) Successful in 1m49s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m3s
release / android (push) Successful in 4m26s
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 4m43s
A scrobble whose id named no track reached the play writer and came back
as a generic failure (0). The handler now looks the song up first, as
stream does, and answers 70 with nothing recorded; a lookup that fails
for another reason is still a generic error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 11:56:12 -05:00
bvandeusenandClaude Opus 5.5 4ca6c6be38 fix(home): a section that panics fails the Home call instead of the server (#8124)
HomeData loads its seven sections in bare goroutines joined by a
WaitGroup. A panic in one of them was off the request's goroutine, out
of the HTTP recoverer's reach, and would stop the whole server. The
sections now run through one helper that recovers a panic into that
section's error, with the stack, so the call fails as a query error
fails it. They stay request-scoped: each uses the request's context and
the call waits for all of them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 11:54:54 -05:00
bvandeusenandClaude Opus 5.5 c9d54b0e7e fix(subsonic): updatePlaylist checks the songs to add before changing anything (#8123)
The name, comment, removals and additions are separate writes, and the
songs to add were only found missing when the last of them ran, so an
unknown songIdToAdd answered error 70 over a playlist already renamed
and trimmed. Every song to add is now looked up first, alongside the
index check, and an unknown one answers 70 with nothing changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 11:53:32 -05:00
bvandeusenandClaude Opus 5.5 ad17849205 fix(playlists): a replayed append whose reply was lost adds nothing more (#8122)
An append that reached the server but whose reply never reached the
phone stayed in the offline queue and was sent again, and since an
append is an action, the song landed twice. Android now names each
append with a request id, carried by the live send and its queued row
alike; POST /api/playlists/{id}/tracks takes it as request_id, and the
server records it per playlist in the append's own transaction
(playlist_append_requests, pruned after 30 days). A send whose id is
already recorded changes nothing; a failed append rolls its id back
with it. Without an id an append behaves as before, so queued rows
from older builds and Subsonic clients are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 11:52:12 -05:00
bvandeusenandClaude Opus 5.5 6996561cb1 refactor: one cover fallback icon on Android, one paged-query type on the web
release / web (push) Successful in 1m19s
release / go (push) Successful in 1m45s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m56s
release / android (push) Successful in 4m34s
release / Build signed APK (push) Successful in 5m3s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 25s
release / Verify release artifacts (tag releases only) (push) Skipped
Ten Android covers wrote out the same muted icon for missing artwork;
they now call CoverFallbackIcon beside CoverTile, and ShelfPlaylistCards'
NoArtIcon wrapper is gone. AlbumDrillDown and AlphaLibrary each declared
the infinite-query shape they read; both now take PagedQuery<T> from
api/types. Folds the two small copies the M664 DRY close-out found (#8006).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 11:48:17 -05:00
bvandeusenandClaude Opus 5.5 db05d16800 fix(android): ktlint's multiline-expression wrap on copySharedCopy
release / go (push) Successful in 1m58s
release / web (push) Successful in 1m28s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m24s
release / android (push) Successful in 4m51s
release / Build signed APK (push) Successful in 5m12s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 31s
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:17:01 -05:00
bvandeusenandClaude Opus 5.5 5d85739038 refactor(android): error messages come from the web's copy, one source for both apps (DRY B6)
release / web (push) Successful in 1m27s
release / go (push) Successful in 1m54s
release / govulncheck (push) Successful in 18s
release / android (push) Failing after 1m10s
release / integration (push) Successful in 4m9s
release / Build signed APK (push) Successful in 4m43s
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
Android's ErrorCopy was a hand-kept copy of web/src/lib/styles/
error-copy.json that had drifted: 14 of the web's codes were missing
(a server shutting down, a bad setting value, the backup and duplicates
codes), so those read "Something went wrong." on the phone, and only 2
of the web's 7 codes appended the server's specifics.

Now app/build.gradle.kts copies error-copy.json and a new
error-detail-codes.json (the list web/src/lib/api/errors.ts kept
inline) into the app's Java resources, and ErrorCopy reads them. The
three codes only Android had (auth_required, not_found,
cleartext_public) move into the shared file. PasswordRules' too-short
line is the shared password_too_short copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:11:34 -05:00
bvandeusenandClaude Opus 5.5 25cee5ed69 fix(android): new passwords follow the web's rules and wording (DRY B5)
Settings › Password said "New passwords do not match." where the web
says "Passwords do not match.", and neither it nor an admin resetting
someone's password checked the 8-character minimum before sending: the
reset button lit up after one character. auth/PasswordRules mirrors
web/src/lib/auth/password.ts: the minimum, the "At least 8
characters." hint under the field, the too-short and mismatch wording.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:09:48 -05:00
bvandeusenandClaude Opus 5.5 c45be1720a fix(android): Previous starts the song over after 3 seconds, as on the web (DRY B4)
Previous always went back a song. It now does what the web player
does: past the first 3 seconds it starts the current song over, and
before that it goes back one. It greys out only in the opening seconds
of the queue's first song. PlayerController decides it, so a cast to a
Sonos speaker behaves the same: the restart is a seek to 0 there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:08:58 -05:00
bvandeusenandClaude Opus 5.5 cb7028c745 refactor(web): one ConfirmModal asks before what can't be undone; no native dialogs (DRY B2, B3)
Deleting a playlist asked in the browser's own confirm() box and
reported errors with alert(). Four other deletes each built Modal +
Cancel + a destructive button by hand, two of them in bronze rather
than the destructive oxblood. Suspect sources removed a file on a
second click while Reports asks in a dialog for the same act.

ConfirmModal is the web's twin of Android's ConfirmDestructiveDialog:
title, a body saying what goes, Cancel, and a confirm button in the
destructive action colour that can show a busy label. Reports (x2),
Needs a file, Admin > Users, the playlist page and Suspect sources use
it. The playlist page's errors go to toasts. A source guard keeps
confirm() and alert() out of the app; it flags the old playlist page.

The two web source guards share lib/testing/sourceGuard.ts.

ListenBrainz status (Settings > Connections) and the recommendation
metrics now offer Try again when they fail to load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:07:43 -05:00
bvandeusenandClaude Opus 5.5 a5d94754bf refactor(android): one plural() says every count, so none reads "1 tracks" (DRY B1)
The playlist card, the playlist header and the playlist a mix was
started from said "${n} tracks" whatever n was. Seven count labels
were each written by hand; they now go through shared/plural(), which
also formats the number for the listener's locale, as the web's counts
do. PluralTest names any hand-written copy (checked against the tree
before this change: it flags all seven).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:04:22 -05:00
bvandeusenandClaude Opus 5.5 b46725e387 fix(android): the playlist writes test imports WriteOutcome from its new home
release / go (push) Successful in 1m53s
release / web (push) Successful in 1m22s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m11s
release / android (push) Successful in 4m37s
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 28s
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:39:36 -05:00
bvandeusenandClaude Opus 5.5 6a216a9e84 fix(android): detekt's file-name, function-count and line-length findings on the DRY batch
release / web (push) Successful in 1m41s
release / go (push) Successful in 2m2s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m22s
release / android (push) Failing after 3m45s
release / Build signed APK (push) Successful in 5m2s
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
SendOrQueue.kt is named for its one class, WriteOutcome.kt.
toggleTrackLike becomes an extension on LikesRepository, keeping the
class under the function cap. A long test line is split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:27:37 -05:00
bvandeusenandClaude Opus 5.5 bae3421057 feat(email): every email Minstrel sends uses one layout (#8150)
The password reset, the new-music and activity summaries and the SMTP
test message each drew their own page; the test message had no layout
at all. They now share internal/mailer's layout: the Minstrel name at
the top, the email's heading and message on a card in the design
system's dark theme, and a footer saying which server sent it and why,
signed "— Minstrel", with the notification-settings link on the
summaries. A plain-text body in the same frame goes alongside.

An email supplies only its content templates and a Frame (heading,
server, reason). Links, buttons and quiet text take named styles from
the layout ({{style "link"}}), so colours change in one place; an
unknown style name fails the render. The SMTP test message is a
template now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:27:16 -05:00
bvandeusenandClaude Opus 5.5 a18d5aaa11 fix(android): restore Home's Most played tile and its skeleton (DRY A1 follow-up)
release / govulncheck (push) Successful in 19s
release / web (push) Successful in 1m29s
release / go (push) Successful in 1m54s
release / android (push) Failing after 1m25s
release / integration (push) Successful in 4m11s
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 3m54s
The A1 edit that moved the Most played cover onto TrackCoverThumb
matched the skeleton tile's cover box first and cut from there to the
real tile's body, dropping CompactTrackTile's header. The skeleton keeps
its plain placeholder box; the real tile uses TrackCoverThumb.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:24:15 -05:00
bvandeusenandClaude Opus 5.5 9bf831e20e refactor(android): one rule for which failed writes wait in the offline queue (DRY D1)
Six repositories decided for themselves which failed writes to queue:
playlists queued only on no answer, notifications split 4xx from 5xx,
and likes and hidden tracks queued everything, a refusal included, which
the replayer then sent again only to drop it.

They all go through cache/mutations/sendOrQueue now: no answer, a 5xx,
408 or 429 queue the write; any other 4xx is a refusal and is not
queued (playlists still throw it so the screen can say why; the others
log it). Cancellation passes through. isRetryableStatus is the one test
of a retryable status, and the replayer's isPermanent is its complement.
WriteOutcome moves to cache/mutations and gains Refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:23:41 -05:00
bvandeusenandClaude Opus 5.5 af5384e672 refactor(android): the admin screens use the shared UiState and one load helper (DRY A4)
Users, Reports, Tag sources and the admin landing each declared their
own Loading/Empty/Success/Error sealed interface and the same
try / list / isEmpty / catch-into-ErrorCopy refresh. They use the shared
UiState<T> now (kept as typealiases for their state types), loading
through two new helpers in shared/UiState.kt: loadUiState, which turns a
failure into Error and lets cancellation through, and List.toListState,
which gives Empty for an empty list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:21:31 -05:00
bvandeusenandClaude Opus 5.5 5853c52640 refactor(android): the track-list heart buttons share LikesRepository.toggleTrackLike (DRY A8)
Album detail, playlist detail and the player each flipped a track's like
with the same lines (desired = id !in likedTrackIds; toggleLike(TRACK…)).
They call toggleTrackLike(trackId, likedIds) now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:19:54 -05:00
bvandeusenandClaude Opus 5.5 d2918aeeb0 refactor(android): Home and the Artist page shuffle-play an artist through one function (DRY A5)
Home's artist tile and the Artist page's Play each fetched the artist's
tracks, shuffled and queued them, with their own copy of the error
handling and different words for an empty artist ("This artist has no
tracks to play." vs "No tracks to play for this artist."). Both call
library/data/LibraryPlayback.kt's shufflePlayArtist now, beside
playAlbumFromStart for Home's album tiles, the way PlaylistPlayback
serves the playlist tiles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:19:26 -05:00
bvandeusenandClaude Opus 5.5 e049c27bdf refactor(android): every ask-before-destroying dialog is ConfirmDestructiveDialog (DRY A6)
Remove the file / Remove from library, Delete user, Clear cache and Sign
out each drew their own AlertDialog, coloured four ways: a plain text
button, error-red text, an error-red button and an error-container
button. They now use the shared ConfirmDestructiveDialog, whose confirm
is the destructive action colour. It gains an optional confirmWord, a
word to type before confirming, which Delete user keeps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:18:42 -05:00
bvandeusenandClaude Opus 5.5 548e31ea57 fix(android): a settings card that fails to load offers Try again instead of a blank form (DRY A7)
The Profile card showed its form once loading stopped, whether or not
the load had worked. After a failed load the name and email fields were
empty and Save was enabled, so saving wrote blanks over the real
profile. ListenBrainz had the same shape.

Both cards now go through SettingsLoad: a spinner while loading, one
settings row with Try again when the load failed, and the form only
once the data is in. The view models keep a load failure in loadError,
apart from the form's save message. The web's cards do the same
(SettingsLoadStatus).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:17:57 -05:00
bvandeusenandClaude Opus 5.5 a48219d807 fix(android): the album and playlist headers and Home's Most played covers fall back when the art fails (DRY A1)
release / web (push) Successful in 1m48s
release / go (push) Successful in 2m30s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m34s
release / android (push) Failing after 3m8s
release / Build signed APK (push) Failing after 3m7s
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
Three covers loaded art outside the shared ServerImage: the playlist
header and Most played tile used Coil's AsyncImage directly, and the
album header passed ServerImage no fallback. A failed load left a blank
box. They now go through CoverTile / TrackCoverThumb, which show the
placeholder glyph while loading and when the load fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:16:40 -05:00
bvandeusenandClaude Opus 5.5 abdb689e08 refactor(android): one transport button pair, and Previous/Next grey out at the ends of the queue (DRY A2)
The mini player and Now Playing each drew their own play/pause button
with its UPnP loading spinner, and their own Previous/Next. They share
TransportControls.kt now (PlayPauseButton, SkipButton). PlayerUiState
gains hasPrevious/hasNext from Media3's hasPrevious/NextMediaItem, and
both screens disable the skip buttons when there is nowhere to go, as
the web does.

The cover's shared-element hero modifier, also written twice, is one
nowPlayingCoverHero().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:16:40 -05:00
bvandeusenandClaude Opus 5.5 d5d9952cd7 feat: tapping a search result starts radio from that track, on web and Android (DRY A3)
Android played the visible search results as a queue; the web started
radio. Both now start radio seeded from the tapped track: the song plays
first, then songs like it. Android falls back to playing the track alone
when radio can't be had (offline, or an empty answer).

The web's two identical onTrackPlay handlers (search and search/tracks)
become one, radioFromRow. PlayerController gains playRadio, which
replaces the queue; the track menu's startRadio still keeps the current
song playing and queues radio after it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:16:40 -05:00
bvandeusenandClaude Opus 5.5 ebb8e331a2 refactor(web): Admin's Overview and the Collection draw a waiting queue with one row (DRY W9)
release / web (push) Successful in 1m42s
release / go (push) Successful in 2m13s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m38s
release / android (push) Successful in 5m11s
release / Build signed APK (push) Successful in 5m29s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 27s
release / Verify release artifacts (tag releases only) (push) Skipped
The "what is waiting, how long, Open" row was written out four times: the
failed scan, each queue and each status problem on the Overview, and each
queue on the Collection. NeedsYouRow draws it once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:24:47 -05:00
bvandeusenandClaude Opus 5.5 6152dacac3 fix(web): the liked page test imports page() at the top level (DRY W10)
The import had landed inside a multi-line import from likes.js.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:24:20 -05:00
bvandeusenandClaude Opus 5.5 47423fb529 refactor(web): Library › Albums and › Artists are one A–Z page (DRY W8)
The two pages matched line for line apart from the noun, the filter field
and the sort key: the count, the quick filter, the lettered grid paged as
you scroll, the admin and listener empty states, and the "search the full
library" link when the filter matches nothing loaded. AlphaLibrary now
draws them once and each page supplies its query, noun, match, key and
card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:23:54 -05:00
bvandeusenandClaude Opus 5.5 abf30b1295 refactor(web): Admin, Settings and Collection share one rail layout (DRY W7)
The three areas each repeated the same title, left rail and content grid.
SectionLayout now draws it once, with the rail and any lines under the
title as snippets.

Admin pages now get the content cap Settings has (max-w-[100rem]): both lay
their groups out in SettingsColumns, and without it Admin's two columns
stretched across a very wide screen. The Collection keeps its uncapped
lists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:23:10 -05:00
bvandeusenandClaude Opus 5.5 f298c44ecd fix(web): the Fingerprinting card's Try again reloads it, and the settings cards type-check (DRY W3)
release / web (push) Failing after 16s
release / go (push) Successful in 1m54s
release / Build signed APK (push) Canceled after 0s
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) Canceled after 18s
release / android (push) Canceled after 1m48s
release / integration (push) Canceled after 2m14s
The Fingerprinting card's load-failure line pointed Try again at a load()
that no longer exists, and canSave closing over a value derived from the
form left TypeScript unable to type the form itself. Try again calls
f.load, and canSave states that it returns a boolean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:22:39 -05:00
bvandeusenandClaude Opus 5.5 5f88fe941d test(web): the search and liked page tests take page() from the shared fixture (DRY W10)
Four test files defined the same Page<T> envelope helper; they now import
it from test-utils/fixtures/page.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:22:07 -05:00
bvandeusenandClaude Opus 5.5 c290667b8a refactor(web): genre and year albums page like every other list (DRY W6)
The genre and year drill-downs hand-rolled their own pager (a request token
to drop late answers, loading, failed and later-page-failed flags), on the
note that the codebase had no way to make a query from a changing URL. The
search pages have since done exactly that:
$derived(q ? createXInfiniteQuery(q) : null).

browse.ts gains createAlbumsByGenreInfiniteQuery and
createAlbumsByYearInfiniteQuery, keyed per selection so a late page for the
previous one never lands in the current list. Both pages draw their albums
through one AlbumDrillDown view (back link, count, grid, ListContinuation),
and the out-of-date note is gone. Tests drive the pages through
mockInfiniteQuery, as the search pages' do, with the page() fixture now in
test-utils.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:21:55 -05:00
bvandeusenandClaude Opus 5.5 7314101f91 refactor(web): every ⋮ menu shares one trigger and popover; album and artist menus are one (DRY W5)
release / web (push) Failing after 11s
release / go (push) Failing after 2m45s
release / govulncheck (push) Successful in 18s
release / integration (push) Failing after 4m51s
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 2m12s
release / android (push) Canceled after 5m8s
The ⋮ trigger, its popover and the close-on-outside-click and Escape
handling were hand-rolled in AlbumMenu, ArtistMenu, TrackMenu, PlaylistCard
and RowActionsMenu. KebabMenu now draws them once; each menu supplies its
items and any popover it opens (Add to playlist, Report a problem).

AlbumMenu and ArtistMenu were the same menu apart from their entity and
"Go to artist"; both are now CollectionMenu with the entity filled in. Its
track cache is kept per entity id, so a menu reused for another row
fetches that row's tracks. Escape now also closes the playlist card's menu
and the mobile row menu with focus inside it. IconProp is exported once,
from TrackMenuItem (W10).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:17:17 -05:00
bvandeusenandClaude Opus 5.5 d99498be0b refactor(web): one password rule and one wording for account-form errors (DRY W4)
The 8-character minimum was written into sign-up, reset, Settings › Account
and Admin › Users as minlength="8" and a message, and each page mapped
password_too_short, username_invalid and username_taken to its own copy of
the same sentence. lib/auth/password.ts now holds the minimum, the hint and
"Passwords do not match.", and the pages take an error code's wording from
the shared error copy (knownCopy), falling back to their own.

username_invalid's shared copy now states the rule (3–32 characters:
letters, numbers, underscores, hyphens), as the pages did, on web and
Android alike. Account's mismatch line reads "Passwords do not match." like
the other forms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:14:50 -05:00
bvandeusenandClaude Opus 5.5 87c650aca1 refactor(web): the admin settings cards share one load-and-save cycle (DRY W3)
Five settings cards (Fingerprinting, Loudness, Public address, Proxies,
Notification email) each hand-rolled the same cycle: load into a stored copy
and an editable one, say when they differ, save, adopt what the server
stored, toast. lib/settings/settingsForm.svelte.ts now runs it once
(createSettingsForm), and SettingsLoadStatus draws the "Loading…" / "Couldn't
load … Try again" line for those five and for Library folders and AcoustID.

The Proxies card dropped the server's reason when a save was refused and
toasted a fixed "Couldn't save proxy depth."; it now says why, as the other
cards do. Two cards' "Loading <thing>…" lines now read "Loading…" like the
rest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:13:32 -05:00
bvandeusenandClaude Opus 5.5 dae46ea980 refactor(web): every cover thumbnail goes through Cover, so a failed load falls back (DRY W2)
Seven places drew their own cover image. The Missing, Suspect sources,
Hidden and Reports rows showed a Music2 icon only when the track had no
album; a cover that failed to load (not fetched yet, or gone) showed a
broken image. The queue row, play bar and Now Playing each set the
placeholder in their own onerror, and the playlist card's images had no
fallback at all.

Cover gains fallback="track" (the Music2 icon a track row uses), and all
seven go through it, so each one handles a missing src and a failed load
the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:09:15 -05:00
bvandeusenandClaude Opus 5.5 cceeaeb5c8 fix(web): Next is off at the end of the queue with repeat one, since it only stops there (DRY W1)
release / web (push) Successful in 1m38s
release / go (push) Successful in 1m57s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m19s
release / android (push) Successful in 4m53s
release / Build signed APK (push) Successful in 5m18s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 25s
release / Verify release artifacts (tag releases only) (push) Skipped
With repeat one on the last track, the play bar and Now Playing enabled
Next, but store.skipNext treats an explicit Next at the end the same for
repeat one as for repeat off: it pauses. The button now follows the store:
on when there is a track after this one or the queue wraps (repeat all).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:06:58 -05:00
bvandeusenandClaude Opus 5.5 14afd86b8e refactor(web): the play bar and Now Playing share one set of transport rules (DRY W1)
PlayerBar and the Now Playing page each carried their own copy of when
Previous and Next are enabled, the repeat label, the volume icon and the
range-input handlers, and the 3-second "restart rather than go back"
threshold was written in both and again in store.skipPrev.
lib/player/controls.ts now holds them once (canSkipPrev, canSkipNext,
repeatLabel, volumeIcon, inputNumber, RESTART_THRESHOLD_SEC), and the store
reads its threshold from there. Behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 03:06:36 -05:00
bvandeusenandClaude Opus 5.5 02cecc4eb7 docs(api): the session cookie comment says sessions expire server-side, because they do (#8108)
release / web (push) Successful in 1m26s
release / go (push) Successful in 1m56s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m29s
release / android (push) Successful in 4m29s
release / Build signed APK (push) Successful in 5m10s
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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:30:38 -05:00
bvandeusenandClaude Opus 5.5 40c53c8b98 test(playlists): name a mix by its seed artist too in the rebuild-keeps-ids test (#8081)
release / govulncheck (push) Successful in 20s
release / go (push) Successful in 1m48s
release / web (push) Successful in 1m17s
release / integration (push) Successful in 4m17s
release / android (push) Successful in 4m24s
release / Build signed APK (push) Successful in 4m52s
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
The fixtures make one artist row per track, all named alike, so two Songs
like mixes with different seed artists share a display name, and the test
read them as one mix held twice. It now names a mix by name and seed
artist, as snapshotSystemTracks does (lesson: a snapshot keyed by display
name merges same-named rows).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:14:41 -05:00
bvandeusenandClaude Opus 5.5 1dff4b7ddb fix(android): a like, unlike, flag or unflag made while an older one is still queued can't be undone by it (#8079)
A toggle went live first and queued only on failure, and the replayer
collapses toggles only among queued rows. So a like queued offline, then an
unlike that reached the server live before the queue drained, ended with
the queued like replaying last: the user's last action lost. A refresh also
replaced the local set with the server's, dropping a queued toggle's state
until it replayed.

- When the queue holds a toggle for the same entity, the new one queues
  behind it (as NormalizationRepository already does); the replayer then
  sends the newest per entity. Quarantine flag and unflag do the same.
- refreshIds and the quarantine refresh keep what is still queued over the
  server's answer (MutationQueue.pendingLikeStates /
  pendingQuarantineStates).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:13:48 -05:00
bvandeusenandClaude Opus 5.5 e05673a9f1 fix(android): signing out ends the server session, not only the local one (#8108)
signOut cleared the session cookie before calling /api/auth/logout, so the
logout went without the cookie that names the session to drop, and the
server session lived on until it expired. The app still shows signed-out at
once; the logout now goes first with the cookie, bounded to 5 s and run in
the application scope so leaving Settings can't cancel it, and the cookie is
cleared after it, whether it worked or not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:11:42 -05:00
bvandeusenandClaude Opus 5.5 e34c3d7bf3 fix(android): a song on repeat is a play per listen, and a late start reply can't make a quick skip record twice (#8071, #8073)
The play reporter keyed a play on the current track id, which repeat-one
and the same song twice in a row never change, so any number of listens
became one play closed at the last loop's position. PlayerController now
counts media-item transitions (Media3 reports a repeat as one) as
PlayerUiState.listenSeq, and the reporter keys a play on (track, listen).

A play_started reply cleared the in-flight flag whichever play it was for.
After a quick skip, song A's late reply cleared the flag song B's start had
set, so skipping B before its reply recorded it offline as well as live.
Each start now carries a token, and only its own play's reply adopts the id
or clears the flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:10:09 -05:00
bvandeusenandClaude Opus 5.5 5939248bef fix(metrics): web and Android tag plays with one source vocabulary, so a surface reads the same on either (#8075)
The recommendation metrics judge each surface against a baseline of manual
plays. The web tagged only system mixes, so its radio, album, artist and
history plays all sat in the baseline; Android tagged nearly everything, and
its search, Liked-list, library-shuffle and artist-top plays fell to Other.
The surface deltas depended on which client someone listened on.

- The web sends the vocabulary Android uses: radio:<seed>, album:<id>,
  artist:<id>, artist-top:<id>, home:most_played and history, kept in
  web/src/lib/player/playSource.ts.
- The baseline is now named in one place (isManualSource): no source, a
  search pick, or a Liked-list pick.
- library_shuffle gets its own row, the random baseline the mixes exist to
  beat; artist-top counts as an artist play.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:08:37 -05:00
bvandeusenandClaude Opus 5.5 0c9faeca9f fix(web): a song on repeat is a play per listen, and a stall before play_started answers doesn't record it twice (#8071, #8072)
The events dispatcher keyed a play on the track id, so repeat-one, a
one-track queue on repeat-all, or the same song twice in a row stayed one
play, closed at the last loop's position and usually graded a skip. The
player store now counts listens (player.listen moves whenever playback
starts an item from its beginning) and the dispatcher keys a play on
(track, listen).

play_started's reply was adopted only while still 'playing', and nothing
marked a start in flight, so a stall or pause just after starting threw the
id away and the next 'playing' posted a second start, which closed the
first as a skip. The dispatcher now holds the pending listen and adopts the
reply whenever that listen is still current.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:06:08 -05:00
bvandeusenandClaude Opus 5.5 2898e9d746 fix(playevents): a late offline replay no longer closes the play that is live now (#8074)
RecordOfflinePlay auto-closed whatever play was open at the replayed play's
original, often hours-old, time. When Android drained its offline queue
while the next song was already playing, each replay ended the live row
before it began, as a zero-length skip. That stuck when the live play's own
close was lost, and for a Subsonic app's now-playing row it became a skip
plus a second play.

autoClosePriorOpen now leaves open any row that started after the time it
was asked to close at, for every caller; #8019's guard for the Subsonic
path moves into it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:04:06 -05:00
bvandeusenandClaude Opus 5.5 b6749fcf16 fix(sync): an artist picture found after the artist first synced reaches the Android app (#8080)
The library sync sends each artist's picture paths, and an app learns that a
row changed only from the change log. The artist enricher wrote the paths
without logging, so an artist synced before its picture arrived kept showing
the album-cover fallback on Android until something else touched it. A
picture found is now logged in the same transaction as the write; settling
"none" changes nothing an app shows and isn't logged.

The MBID backfill's heals of albums.mbid and artists.mbid, also part of the
sync payload, are now logged too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:03:21 -05:00
bvandeusenandClaude Opus 5.5 8ba1d109c3 fix(events): a like made in a Subsonic app reaches the other apps, and an open web tab follows likes and playlist changes (#8077)
The native like endpoints announce a like on the event bus; Subsonic star
and unstar announced nothing, so the web and Android apps showed a stale
heart until they refetched. Subsonic now publishes the same events, through
one shape both surfaces build (eventbus.LikeChanged, eventbus.LedBy).

The web listened only for the nightly rebuild and notifications, so an open
tab ignored likes and playlist changes made in another tab, on Android or
in a Subsonic app. It now refreshes its liked views on any like event and
its playlists (and the open one) on playlist.created/updated/deleted/
tracks_changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:02:12 -05:00
bvandeusenandClaude Opus 5.5 528ea9df0c fix(likes): unliking any copy of a song retires the listening context captured on another (#8078)
release / go (push) Successful in 1m49s
release / web (push) Successful in 1m16s
release / govulncheck (push) Successful in 25s
release / integration (push) Failing after 4m12s
release / android (push) Successful in 4m47s
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
A like is on the song: LikeTrack and UnlikeTrack change every copy sharing
its song_key. The contextual like (the session captured while it played) is
written on the copy that was playing, but an unlike soft-deleted only the
copy it named. Unliking from the Liked list, which shows one copy per song,
or from another album holding the song, left the context active, and the
engine kept boosting candidates matching it.

The soft-delete now covers every copy of the song, and the engine's reader
counts only contexts whose song is still liked, as a backstop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:59:09 -05:00
bvandeusenandClaude Opus 5.5 d1f76167c8 fix(playlists): each daily mix keeps its id across rebuilds (#8081)
The nightly rebuild deleted every system playlist and inserted new rows, so
each mix got a new id every day. A Subsonic app caches, pins, downloads and
syncs a playlist by id, and saw its mixes deleted and recreated daily: a
stored mix answered "not found" and an offline download was orphaned.

The rebuild now refills yesterday's row for the same mix in place (keyed by
kind, plus the seed artist for "Songs like" and the name for a genre mix),
inserts only mixes that are new, and deletes the ones today's build didn't
make, along with their collage files. The rollups move updated_at, which is
the "changed" time Subsonic apps use to see a mix was refreshed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:57:41 -05:00
bvandeusenandClaude Opus 5.5 dbf39f90f8 fix(playlists): a restored playlist draws its collage again instead of showing a broken image (#8105)
A collage is a file in the data directory, which the backup doesn't carry,
but playlists.cover_path travelled, so a restored playlist pointed at a file
that wasn't there and its tile showed a broken image until someone edited it.

- The backup leaves cover_path out, so a restored playlist starts with none.
- The nightly rebuild (and the catch-up at startup) draws each person's own
  playlist collages again from their albums' current covers, so one drawn
  before the art arrived fills in later.
- The cover endpoint draws a collage whose file has gone missing, rather
  than answering 404.
- SetPlaylistCover only bumps updated_at when the path changes, so a redraw
  isn't a change to the playlist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:55:30 -05:00
bvandeusenandClaude Opus 5.5 436a970f7b fix(backup): a restore says Subsonic apps are signed out, and restores ListenBrainz switched off (#8104)
The backup leaves out each person's Subsonic password and ListenBrainz
token, which are sealed under the stream secret, but no restore message
said so. The CLI and docs sent people to Admin for keys that live in each
person's own Settings, and the web said nothing. All three now say that
Subsonic apps are signed out and where to make a new Subsonic password and
save the ListenBrainz token.

listenbrainz_enabled travelled without the token, so a restored account
read as on but unable to send. It is now left out too and restores off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:53:37 -05:00
bvandeusenandClaude Opus 5.5 4c0bd9df04 fix(subsonic): a scrobble's time is bounded as a native play's is (#8076)
The native events endpoint clamps a client's play time to between the
account's creation and a few minutes past now. A Subsonic scrobble took
its time as sent, so an app with a wrong clock dated plays years out,
onto the wrong day in History and into Rediscover's ordering. The clamp
moves to playevents.ClampClientTime and both surfaces use it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:52:37 -05:00
bvandeusenandClaude Opus 5.5 408c4f9c24 fix(subsonic): starred songs list only songs the listener can play (#8109)
getStarred and getStarred2 shared the web's liked-songs query, which keeps a
liked song whose file is missing and ignores the listener's quarantine.
Subsonic can't show a song as unplayable, so an app's Favorites offered
songs that failed to stream, or played the copy the listener hid. Subsonic
now reads ListPlayableLikedTrackRows, which filters both before the cap,
as #8020 did for albums, search and genres. The web's list is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:51:42 -05:00
bvandeusenandClaude Opus 5.5 f3997b657c fix(providers): saving a key for an enabled source tries the gaps again (#8102)
A source that needs a key, such as Last.fm, answers "not found" without
one, and the enricher settles each row it tried that way at the current
version. Switching Last.fm on before entering its key settled every gap
without it, and saving the key didn't move the version, so Last.fm never
came back to them. The sources signature now marks each enabled source
that has a key, so a key arriving or leaving moves the version. Replacing
one key with another still doesn't.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:50:29 -05:00
bvandeusenandClaude Opus 5.5 3a7081be19 fix(scrobble): plays that can't be sent no longer block ListenBrainz for everyone (#8103)
The worker skipped a queued play whose account had since switched
ListenBrainz off, or whose token couldn't be read, and left it pending. The
batch is the oldest fifty pending rows, so skipped rows came back first on
every tick, and fifty of them stopped scrobbling for every account. They are
now marked failed with the reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:48:55 -05:00
bvandeusenandClaude Opus 5.5 c6a9535cf7 fix(auth): a password reset signs out Subsonic apps too, and a change can (#8107)
A reset ended every session but left the API key and Subsonic password
working, and anyone signed in to the account can make either. So whoever had
the account kept it through a Subsonic app after the owner reset the
password. The forgotten-password reset and an admin's reset now replace the
API key with one nobody holds and clear the Subsonic password.

A self-service change keeps Subsonic apps signed in by default, since it
would sign out the owner's own apps too. The web and Android password forms
gain "Sign out Subsonic apps too", sent as sign_out_subsonic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:48:21 -05:00
bvandeusenandClaude Opus 5.5 1c28e17dfc fix(auth): one invite makes one account, and a burst of sign-ups can't outrun the limit (#8106)
release / go (push) Successful in 2m8s
release / govulncheck (push) Successful in 19s
release / web (push) Successful in 1m13s
release / integration (push) Successful in 4m7s
release / android (push) Successful in 4m15s
release / Build signed APK (push) Successful in 4m46s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 25s
release / Verify release artifacts (tag releases only) (push) Skipped
Registration inserted the user and only then claimed the invite. When the
claim lost a race it kept the account anyway, so parallel sign-ups on one
invite link each made an account. The insert and the claim now run in one
transaction: RedeemInvite's row lock makes the second sign-up wait for the
first, find the invite used, and roll its account back with invite_invalid.

The register and forgot-password limits checked and counted in two steps,
so a parallel burst all read the count before any attempt was added. They
now call AttemptLimiter.Allow, which does both under the lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:45:07 -05:00
bvandeusenandClaude Opus 5.5 1b13aa8b7f fix(library): drop the stray zero a tagger writes after every UTF-16 string, not only the last (#8060)
release / go (push) Successful in 2m0s
release / web (push) Successful in 1m10s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m10s
release / android (push) Successful in 4m56s
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 15s
release / Verify release artifacts (tag releases only) (push) Skipped
The first repair trimmed one stray zero at the end of a UTF-16 frame. The
same tagger writes one after every string, so a custom field (TXXX) such
as ARTISTS or REPLAYGAIN carries one between its name and its value as
well, and dhowden/tag still refused those files. Zeros between a
terminator and the next byte order mark, or the end of the frame, are now
dropped too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 15:52:03 -05:00
bvandeusenandClaude Opus 5.5 c9e058b3c9 fix(library): a UTF-16 tag frame with a stray trailing zero no longer hides the whole file (#8060)
release / go (push) Successful in 2m4s
release / web (push) Successful in 1m21s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m9s
release / android (push) Successful in 4m28s
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 14s
release / Verify release artifacts (tag releases only) (push) Skipped
Some taggers end a UTF-16 text frame with a two-byte terminator and then
one more zero byte, so the frame holds an odd number of bytes.
dhowden/tag refuses the whole tag when it meets one, and the scanner
then skipped the file: 61 tracks on dev (whole albums from one tagger,
with a genre or year frame written this way) never reached the library.

internal/tagread.ReadFrom reads with dhowden/tag first. When that fails
on an ID3v2.3/2.4 tag, it rebuilds the tag in memory with the stray
byte trimmed from each such frame and reads it again. Anything else
still fails with dhowden/tag's own error. The scanner, both MBID
backfills, embedded cover art and Subsonic lyrics all read through it.

The ID3v2 primitives (syncsafe and frame sizes, the extended header,
unsynchronisation) move from library/id3v2genre.go into tagread, so the
genre reader and the repair share one copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 14:05:55 -05:00
bvandeusenandClaude Opus 5.5 17a9052acb refactor(api): the cover-source and tag-source admin cards share their handlers (#8002)
release / web (push) Successful in 1m16s
release / go (push) Successful in 1m49s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 3m56s
release / android (push) Successful in 4m8s
release / Build signed APK (push) Successful in 4m29s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 13s
release / Verify release artifacts (tag releases only) (push) Skipped
admin_cover_sources.go and admin_tag_sources.go were the same list,
update and test handlers over two settings services, each with its own
copy of the response mapping. With both services now a
providers.Service, admin_provider_sources.go holds the handlers and wire
types once, and each family's routes pass their own service. The wire
shape is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 13:01:48 -05:00
bvandeusenandClaude Opus 5.5 d8abc457e7 fix(providers): Last.fm's rate limit retries art later, and both Last.fm sources share one pace (#8002)
The cover-art Last.fm provider read every JSON error code as "no art",
so a burst of rate-limit (29) or service-unavailable (8, 11, 16)
answers marked albums and artists as having nothing on Last.fm. The tag
provider already retried those. providers.LastfmError is now the one
mapping, used by both.

Each family also paced Last.fm on its own at 4 requests a second, so
together they could reach 8 a second against the 5-per-key limit when
an admin uses one key for both. Both now wait on providers.LastfmPacer.
The client's own spacing is a providers.Interval, so a pace can be
shared.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 13:00:51 -05:00
bvandeusenandClaude Opus 5.5 b901560edf refactor(providers): one paced, retrying HTTP client for cover art and tags (#8002)
coverart/httpclient.go and tags/httpclient.go were the same client:
pacing, exponential backoff with jitter, 401/403-as-transient, body
caps. Tags had added a User-Agent and a shared Pacer, cover art an image
GET. providers.HTTPClient now has all of it, with the tests that were in
coverart. ErrTransient is shared too, so both families' errors.Is still
match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:58:55 -05:00
bvandeusenandClaude Opus 5.5 487e11f59f refactor(providers): cover art and tags share one registry and settings service (#8002)
coverart and tags each carried a line-for-line copy of the provider
registry and the settings service: reconcile at boot, seal and reveal
API keys, bump the sources version when the enabled set or the
registered set changes. A fix to either had to be made twice.

internal/providers now holds Registry, Service (over a small Store
interface) and EnabledAs[T]. Each family keeps its own tables, provider
set and capabilities: a 40-line Store adapter over its sqlc queries and
its capability views (EnabledAlbumProviders, EnabledTrackTagProviders).
Provider, ProviderSettings, TestableProvider, ProviderInfo and
ProviderUpdatePatch stay as the families' names for the shared types.
The service has unit tests over an in-memory store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:57:19 -05:00
bvandeusenandClaude Opus 5.5 58fb2bbe9d refactor: drop code nothing calls, and the sync log rows no app reads (#8002)
release / go (push) Successful in 1m56s
release / web (push) Successful in 1m18s
release / govulncheck (push) Successful in 19s
release / android (push) Successful in 4m20s
release / Build signed APK (push) Successful in 4m52s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / integration (push) Successful in 4m0s
release / Build + push container image (push) Successful in 25s
release / Verify release artifacts (tag releases only) (push) Skipped
- library.ProbeDurationMs and IsAudioFile, and db.MigrationsFS, had no
  callers.
- The delta sync logged and hydrated like and playlist changes on every
  like, playlist edit and duplicate merge, including a GetPlaylistsByIDs
  query per sync. Android applies only artists, albums and tracks, and
  the web doesn't sync; likes and playlists reach both through their own
  endpoints and live events. The like and playlist-entry deletes also
  went to every caller unscoped, user ids included. They are no longer
  written or served, and migration 0112 clears the rows already logged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:52:35 -05:00
bvandeusenandClaude Opus 5.5 39fa740bff test: one test-database opener, dbtest.Pool, in place of 39 copies (#8002)
Every package carried its own testPool/newPool/newTestPool: skip under
-short or without MINSTREL_TEST_DATABASE_URL, migrate, connect,
register the close, and usually ResetDB. dbtest.Open does the first
four (migrating once per test binary) and dbtest.Pool adds the reset.
The per-package wrappers that did nothing else are gone; fixture
helpers that seed rows keep their own signatures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:49:02 -05:00
bvandeusenandClaude Opus 5.5 47e749225e refactor(recommendation): both candidate pools score through one listener context (#8002)
LoadCandidates and LoadCandidatesFromSimilarity each loaded contextual
likes, the taste profile and context affinity, and each built
ScoringInputs field by field, so a new scoring input added to one pool
would be missing from the other. loadScoringContext loads them once
and scoringContext.inputs builds every candidate's inputs; the
similarity pool adds its similarity score on top.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:46:44 -05:00
bvandeusenandClaude Opus 5.5 55a290cf4d refactor(coverart): one image Content-Type table for /api and Subsonic (#8002)
api/media.go and subsonic/stream.go each had imageContentType, the
same map in a different order, serving the same files.
coverart.ImageContentType is now the one copy, with its test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:45:50 -05:00
bvandeusenandClaude Opus 5.5 074d9ffb0e refactor(api): one password rule, one hash, one unique-violation check (#8002)
The length check and bcrypt call were copied into sign-up, reset,
change and both admin paths; the unique-violation test into three api
handlers and the library. checkNewPassword and hashPassword now sit in
api/prelude.go, and db.IsUniqueViolation serves api and library. The
taken-username and taken-email conflicts now carry a message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:45:18 -05:00
bvandeusenandClaude Opus 5.5 cfdd6b916f fix(subsonic): a handler without a caller answers error 50 everywhere (#8002)
Sixteen handlers answered a missing caller with error 50 "Not
authenticated"; the star, unstar and scrobble handlers answered error 0
"Unauthenticated". Middleware stops such a request first, so no app saw
it, but the next handler copied would pick one at random. requireUser
now holds the check, the same shape as /api's, at all 21 sites.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:44:05 -05:00
bvandeusenandClaude Opus 5.5 0811775af6 fix(api): every /api error answers in one envelope, so Android shows the real reason (#8002)
Three error shapes were on the wire: {"error":{"code","message"}} from
writeErr, a flat {"error":"code"} from the admin queues, playback errors
and RequireAdmin, and plain text from RequireUser's 401s. Android reads
only the first, so an admin's quarantine, duplicate or suspect-file
error, and "you're not an admin", all showed "Something went wrong."

apierror.Write is now the one writer, and api.writeErr, RequireAdmin,
RequireUser, the client-APK endpoints, the events stream, the unknown-
route 404 and the admin scan all go through it. The flat writers are
gone, and the web client drops its second branch. The admin codes keep
their names; each now carries a message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:43:27 -05:00
bvandeusenandClaude Opus 5.5 125099ede2 fix(server): a background job that panics no longer stops the server (#8002)
release / go (push) Successful in 2m6s
release / web (push) Successful in 1m25s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m18s
release / android (push) Successful in 4m19s
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 30s
release / Verify release artifacts (tag releases only) (push) Skipped
Background jobs run in their own goroutines, outside the router's panic
recovery, and only five of them recovered. A panic in the scrobble,
similarity, co-play, gc, tags, compactor, notification, backup or
safety-net loop, or in a scan or rebuild started off a request, ended
the process and every stream in it.

internal/periodic now runs each job: a pass at start (or after one
interval, Delayed), then one per interval and on any WakeOn channel,
each pass under recover with the stack logged. Detached one-shot work
(scans, the lazy system-playlist build, bulk cover refetch, leveled
prerender, the backup run, the playlist catch-up) runs under
periodic.Safe. The duplicate resolver keeps its own loop for its
retry-soon timer, and its pass already recovers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:38:56 -05:00
bvandeusenandClaude Opus 5.5 9b36effbaf fix(android): playlist screens and the replay loop meet detekt's limits (#8023)
release / go (push) Successful in 1m49s
release / web (push) Successful in 1m11s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m6s
release / android (push) Successful in 4m19s
release / Build signed APK (push) Successful in 4m44s
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
The replay loop's per-row choice moves to replayRow, so the loop has no
continue. The playlist detail's top bar and the playlists list's body
move into their own composables. ReorderableRow.kt is named for its row,
not for ReorderHandles, its parameter type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:42:27 -05:00
bvandeusenandClaude Opus 5.5 7e112ac523 feat(android): make, rename, delete and reorder playlists, offline-first (#8023)
release / go (push) Successful in 2m5s
release / web (push) Successful in 1m15s
release / govulncheck (push) Successful in 19s
release / android (push) Failing after 1m21s
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 1m43s
release / integration (push) Canceled after 3m24s
- Add to playlist opens with a New playlist row, which makes the list
  and adds the song; the sheet lists only the listener's own lists.
- Playlists has a + to make an empty playlist and open it.
- On a playlist the listener owns: rename, make public or private and
  delete from the top bar; swipe a song away and long-press its cover to
  drag it to a new place. Mixes and other people's lists stay read-only.
- Each change shows at once and goes through the offline queue: a
  create carries the phone's own id, a removal names the song expected,
  a reorder sends the new order, and one playlist's queued changes go
  out in the order they were made.
- The queue's drag-and-swipe row is now shared by the queue and
  playlists (ReorderableRemovableRow).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:32:43 -05:00
bvandeusenandClaude Opus 5.5 a77f3ae6ff feat(playlists): changes a phone queues offline are safe to send twice (#8023)
release / go (push) Successful in 1m59s
release / web (push) Successful in 1m23s
release / govulncheck (push) Successful in 22s
release / integration (push) Successful in 4m38s
release / android (push) Successful in 4m45s
release / Build signed APK (push) Successful in 5m22s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 17s
release / Verify release artifacts (tag releases only) (push) Skipped
- A new playlist can carry the client's own id; sending the create
  again finds the same list.
- Removing a song can name the song expected at that position; if
  another song is there now, nothing is removed (409 list_changed).
- A reorder can give the songs in their new order (track_ids); sending
  it again changes nothing.
- The playlist service tells the owner's clients about every change
  itself, so a change made from a Subsonic app refreshes the web and
  Android apps too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:22:40 -05:00
bvandeusenandClaude Opus 5.5 1df91678ba fix(subsonic): someone else's private playlist reads as absent when an app tries to change it (#8021)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:22:40 -05:00
bvandeusenandClaude Opus 5.5 df2095baae feat(subsonic): apps can make, change and delete playlists (#8021)
release / web (push) Successful in 1m43s
release / go (push) Successful in 2m21s
release / govulncheck (push) Successful in 20s
release / integration (push) Failing after 4m31s
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 2m44s
release / android (push) Canceled after 3m43s
createPlaylist makes a playlist, or with playlistId replaces its songs;
updatePlaylist renames it, sets its comment and visibility, removes songs
by the index the app was shown and adds songs; deletePlaylist deletes it.
A song index counts only the entries getPlaylist lists, so a hidden
entry ahead of it doesn't shift which song goes.

The playlist service gains ReplaceTracks and RemovePositions; the owner
and system-mix checks that each change repeated are one function.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:17:15 -05:00
bvandeusenandClaude Opus 5.5 3491cf4c58 feat(admin): switches for ListenBrainz similarity and MusicBrainz track lists
release / go (push) Successful in 1m50s
release / web (push) Successful in 1m15s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m11s
release / android (push) Successful in 4m33s
release / Build signed APK (push) Successful in 4m40s
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
Both lookups ran with no way to stop them. Admin › Metadata sources now
has an "Other lookups" group with a switch each, both on by default
(lookup_settings, migration 0111). Off, the similarity worker asks
ListenBrainz nothing and still links what it already fetched; the
duplicate resolver gets ErrLookupOff and decides from the track lists it
already has. The setting is backed up, and docs/security.md names the
switches. docs/security.md also says every account but the first needs an
invite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:59:25 -05:00
bvandeusenandClaude Opus 5.5 1942cb39cf test: example addresses come from the documentation range
Sonos, UPnP and public-address tests used addresses from a real home
network. They now use 198.51.100.x (RFC 5737), keeping the last number.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:59:25 -05:00
bvandeusenandClaude Opus 5.5 dd27e014c0 fix(auth): an invite is the only way to an account
The README offered open registration, and the register handler still had
a branch for a registration_settings mode nothing could set. Now every
account after the first needs an invite; the first still needs the setup
token from the log. Migration 0110 drops registration_settings and its
queries, and backups no longer carry it (an older backup that holds it
restores without it). The web form asks for the invite token as required.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:59:25 -05:00
bvandeusenandClaude Opus 5.5 de335333da test(subsonic): a library download by search3 leaves out the missing song
release / web (push) Successful in 1m18s
release / go (push) Successful in 1m46s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 3m56s
release / android (push) Successful in 4m15s
release / Build signed APK (push) Successful in 4m46s
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 fixture's C has a missing file, and search3 now lists only what the
listener can play, as getAlbumList2 already did with the same fixture.
The paging test expected the old behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:13:00 -05:00
bvandeusenandClaude Opus 5.5 9207a7529d docs: say which outside services Minstrel contacts, what it sends and how to turn each off
release / web (push) Successful in 1m24s
release / go (push) Successful in 1m52s
release / govulncheck (push) Successful in 19s
release / integration (push) Failing after 4m6s
release / android (push) Successful in 4m25s
release / Build signed APK (push) Successful in 4m59s
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-25 22:02:00 -05:00
bvandeusenandClaude Opus 5.5 14aa3dcd5e chore: remove code left from acquisition and Discover suggestions, and uncalled queries
Nothing reached any of it:
- MusicBrainz search (artists, albums, songs), artist lookups and the
  query escaping they used. The release-group lookups the duplicate
  resolver uses stay.
- Release-group covers, and artist-level tags for artists not in the
  library.
- Nine named queries with no caller (CountTracksByArtist went with the
  previous commit), two of them describing request-progress reporting.

The MusicBrainz client's retry and not-found tests now drive the
release-group lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:02:00 -05:00
bvandeusenandClaude Opus 5.5 987c2a68fa fix(web): a failed like reverts only itself
A like or unlike that failed restored the whole liked list from before it
started, undoing any like made while it was in flight. Now only its own id
goes back to how it was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:02:00 -05:00
bvandeusenandClaude Opus 5.5 785b15ab5f fix(library): a scan cut off by a restart no longer blocks saving library folders
A restart mid-scan left its scan_runs row unfinished, and saving library
folders refused ("A library scan is running") until a later scan reaped it,
up to 12 hours on. Startup now closes such rows with the reason before the
boot scan, as backups already do. Saving folders and the duplicate sweep
share one check that treats a run past StuckScanThreshold as dead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:02:00 -05:00
bvandeusenandClaude Opus 5.5 1ff4bc8258 fix(subsonic): albums, folders and search list only what the listener can play
getAlbum, getMusicDirectory and search2/3 ignored the listener's quarantine
and listed missing files, which an app then failed to stream; song counts
counted both. They now pass the listener and leave out missing files, as
the mixes already did. Subsonic can't mark a song unplayable, so leaving it
out is how the native apps' greyed-out row comes across.

Song search filters in SQL (SearchPlayableTracks), so a library sync paging
through search3 never gets a short page that reads as the end. Album song
counts come from one query for the whole page (CountPlayableTracksByAlbums)
instead of one per album.

tracks.sql also drops CountTracksByArtist, which nothing called; see the
next commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:02:00 -05:00
bvandeusenandClaude Opus 5.5 d0675e1817 fix(android): a device's cached data stays with the account that made it
Queued offline writes, Home, history, the quarantine list, notifications and
the resume queue carry no user id, and nothing cleared them when someone
signed out. The next person to sign in on a shared phone inherited them,
and the queued likes and plays were sent under their session.

The cached data now has an owner (Room v15, auth_session.cacheOwnerUserId).
When a different account signs in, AccountCache clears those tables in one
transaction and empties the player before adopting it. The replayer only
sends queued writes while their owner is signed in. The same person signing
back in, after a sign-out or an expired session, keeps everything. Signing
out from Settings sends what is still queued first, for up to five seconds.

An install updated from before this adopts whoever is signed in, keeping
their data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 22:02:00 -05:00
bvandeusenandClaude Opus 5.5 333523b30e fix(subsonic): one listen is one play, and a daily mix played in a Subsonic app is credited to it
release / web (push) Successful in 1m23s
release / go (push) Successful in 1m55s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m16s
release / android (push) Successful in 4m50s
release / Build signed APK (push) Successful in 5m29s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 17s
release / Verify release artifacts (tag releases only) (push) Skipped
A Subsonic app reports "now playing" when a song starts and "played" when
it ends. The played report used to close the now-playing row as a play of
its own and write a second one, so every listen counted twice, and as a
skip when the app sent the song's start time. The report now completes the
app's own row for that song. A late report for an earlier song no longer
cuts short the song playing now.

Subsonic's scrobble doesn't say where a song was played from, so Minstrel
remembers, per user and app, the daily mix the app last opened (for six
hours). A play of a song in that mix is credited to it: the mix's metrics
count it and its rotation moves on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 21:48:17 -05:00
bvandeusenandClaude Opus 5.5 7f7e946bad feat: artist pictures in the web and Android apps
release / web (push) Successful in 1m59s
release / go (push) Successful in 2m23s
release / govulncheck (push) Successful in 22s
release / integration (push) Successful in 4m59s
release / android (push) Successful in 5m29s
release / Build signed APK (push) Successful in 6m26s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 31s
release / Verify release artifacts (tag releases only) (push) Skipped
Minstrel fetched artist pictures but showed them only to Subsonic apps.
GET /api/artists/{id}/image now serves the picture, or else the artist's
newest album cover, the same image Subsonic apps get. Artist listings
point at it when the artist has a picture and keep the album cover
otherwise; the artist page points at it whenever the artist has albums,
and the web artist page shows it beside the name.

Android shows the picture for cached artists that have one, and the
album cover for the rest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:32:55 -05:00
bvandeusenandClaude Opus 5.5 1965e82013 feat(subsonic): artist pictures in Subsonic apps
release / go (push) Successful in 1m47s
release / web (push) Successful in 1m10s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m3s
release / android (push) Successful in 4m27s
release / Build signed APK (push) Successful in 5m2s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 17s
release / Verify release artifacts (tag releases only) (push) Skipped
getCoverArt now answers an artist's id: the artist picture Minstrel
fetched, when its file is there, or else the cover of the artist's most
recently added album that has one, which is what Minstrel's own artist
cards show. Every artist entry carries its id as coverArt, so apps ask.

The lookup is coverart.ResolveArtistPath, beside the album one, and looks
through at most ten of an artist's albums for a cover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 18:20:30 -05:00
bvandeusenandClaude Opus 5.5 6dfa7b25fb fix(subsonic): the lint findings in artist info and the lyrics handler name
release / go (push) Successful in 2m1s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m11s
release / web (push) Successful in 1m20s
release / android (push) Successful in 4m23s
release / Build signed APK (push) Successful in 5m11s
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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:48:57 -05:00
bvandeusenandClaude Opus 5.5 f87aba5b86 feat(subsonic): scan status, artist and album info, lyrics, ratings and users
release / go (push) Failing after 1m15s
release / web (push) Successful in 1m18s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 3m57s
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 4m33s
release / Build signed APK (push) Canceled after 4m9s
The last Subsonic methods apps call that Minstrel didn't answer:

- getScanStatus counts the songs whose files are present and says
  whether a scan is running; startScan, for an admin, starts the scan the
  web app's Rescan starts, and answers "scanning" straight away since the
  scan records itself a moment later.
- getArtistInfo and getArtistInfo2 give the artist's MusicBrainz id and the
  artists in this library that sound like them, from an artist, album or
  song id; getAlbumInfo and getAlbumInfo2 give the album's MusicBrainz id.
  Minstrel fetches no biographies or outside images, so none are sent.
- getLyrics (by artist and title) and getLyricsBySongId (OpenSubsonic
  songLyrics, now declared) read lyrics when asked: a .lrc file beside the
  song gives timed lyrics, otherwise the song's own lyrics tag.
- setRating accepts a rating and keeps none: a like is Minstrel's only
  rating, and a low rating is never read as a dislike.
- getUsers lists every user, for an admin only.

ArtistRef no longer fixes its XML element name, so it can appear as
similarArtist; every field holding it names the element.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:43:13 -05:00
bvandeusenandClaude Opus 5.5 b801f81058 feat(subsonic): an artist's top songs, and the play queue carried between devices
release / go (push) Successful in 1m50s
release / web (push) Successful in 1m14s
release / govulncheck (push) Successful in 44s
release / integration (push) Successful in 4m11s
release / android (push) Successful in 6m15s
release / Build signed APK (push) Successful in 7m51s
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
getTopSongs ranks the named artist's songs by how often they were played
through on this server, then by likes, then in album order, so an artist
nobody has played yet still has songs to offer. Missing files and the
listener's quarantined songs are left out.

savePlayQueue keeps one queue per listener: the songs in order, the one
playing, how far into it, and the app that saved it. getPlayQueue gives it
back to that listener only; a song no longer in the library drops out.
Saving no songs clears it. The queue lives in a new play_queues table,
which backups carry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:03:29 -05:00
bvandeusenandClaude Opus 5.5 8731e9695a feat(subsonic): browse by genre and by folder
release / web (push) Successful in 1m16s
release / go (push) Successful in 1m47s
release / android (push) Successful in 4m30s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 3m59s
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 15s
release / Verify release artifacts (tag releases only) (push) Skipped
Subsonic apps can now list genres and play one (getGenres,
getSongsByGenre), and apps that browse by folder, such as DSub, can open
an artist to its albums and an album to its songs (getMusicDirectory),
with the album lists and search they use in that mode (getAlbumList,
search2).

Genres are split and counted as the web's genre index counts them, now
with an album count beside the song count. A genre's songs leave out the
listener's quarantined ones and missing files. Folders are Minstrel's
artists and albums, under the same ids as the tag-based calls.

getAlbumList2 and search3 now share their selection with the folder
versions, so the two modes list and find the same things.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:40:21 -05:00
bvandeusenandClaude Opus 5.5 da64d95264 test(subsonic): read similar songs from their own keys, not a map over the whole response
release / web (push) Successful in 1m30s
release / go (push) Successful in 1m59s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m18s
release / android (push) Successful in 4m37s
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 14s
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:34:20 -05:00
bvandeusenandClaude Opus 5.5 bb2897dfd5 feat(subsonic): playlists and daily mixes, the weighted shuffle, and radio
release / go (push) Successful in 2m0s
release / web (push) Successful in 1m23s
release / govulncheck (push) Successful in 20s
release / integration (push) Failing after 4m23s
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 2m8s
release / android (push) Canceled after 3m38s
Subsonic apps now get what Minstrel picks, not only what it holds:

- getPlaylists lists the listener's daily mixes first, then their own
  playlists, then other people's public ones; getPlaylist returns the
  playable songs in order, as <entry> elements in XML.
- getRandomSongs answers with the weighted shuffle (likes up, skips down,
  the last hour's plays out), narrowed by genre and release year.
- getSimilarSongs and getSimilarSongs2 answer with Minstrel's radio, seeded
  from a song, or from a random song of an album or artist.

Radio's selection moves out of the /api/radio handler into
recommendation.Picker, built by recsettings.Service.Picker, so the web and
Android apps and the Subsonic apps pick through one piece of code and one
tuning. SongRef loses its XMLName so the field holding it names the element.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:25:49 -05:00
bvandeusenandClaude Opus 5.5 66861a2bc4 test: the case-and-spacing duplicate title matches its renamed pair
release / go (push) Successful in 2m6s
release / web (push) Successful in 1m11s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m17s
release / android (push) Successful in 4m58s
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 26s
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:34:43 -05:00
bvandeusenandClaude Opus 5.5 4e1807cbba test: invented artists, albums and MusicBrainz ids in place of real ones
release / web (push) Failing after 1m16s
release / go (push) Successful in 1m48s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m0s
release / android (push) Successful in 4m34s
release / Build signed APK (push) Successful in 5m9s
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
Test data and example comments named real artists, records and songs, and
carried real MusicBrainz ids. One mapping swaps them for invented ones
throughout (Fields of Ontario, Plastic Apes, Marlo Davies, ...), keeping
what each case tests: sort order, index letter, escaping, title keys,
artist-prefix stripping. A test username is no longer the operator's name.

The cover-art and Last.fm connection checks still query real releases;
they reach live services and need something that exists there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:21:34 -05:00
bvandeusenandClaude Opus 5.5 4244d81dfd build: keep the pipeline's own files out of the source release export
git archive, which makes the public source release, now leaves out the
workflow, ci/version.sh, ci-requirements.md and the two tests that pin the
workflow file (without it they would fail go test ./...). docs/security.md
no longer points readers at the workflow file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:14:58 -05:00
bvandeusenandClaude Opus 5.5 29ab3f93fc docs(readme): tell iPhone users to use a Subsonic app, and what it can do
release / web (push) Successful in 1m25s
release / go (push) Successful in 1m55s
release / govulncheck (push) Successful in 22s
release / integration (push) Successful in 4m7s
release / android (push) Successful in 4m45s
release / Build signed APK (push) Successful in 5m15s
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
There is no iOS app. The first-run steps now say which Subsonic apps to use
on an iPhone and where to make their password, and the README no longer says
Subsonic apps get Minstrel's mixes: they browse, search, play, like and
scrobble, and the mixes, smart shuffle and radio stay in the web and Android
apps for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:14:31 -05:00
bvandeusenandClaude Opus 5.5 cd78529ae8 fix(subsonic): answer what the OpenSubsonic spec and Subsonic apps require
- getOpenSubsonicExtensions answers, without credentials, as the spec
  requires of a server that says openSubsonic=true; it lists
  apiKeyAuthentication. An apiKey sent with u is error 43 and an unknown
  apiKey error 44, the extension's codes; a wrong key still counts toward the
  sign-in throttle.
- search3 with an empty query (or two quote marks) matches everything, paged
  in a stable order, so apps that keep a copy of the library (Symfonium) can
  download it. A page of songs reads its albums and artists in two queries,
  not two per song.
- getAlbumList2 serves type=starred and highest (the listener's liked
  albums) and byYear (oldest first, newest first for a backwards range).
- Internet radio, podcasts, bookmarks, shares, chat and now-playing answer
  with an empty list instead of "Method not implemented", so an app shows an
  empty tab rather than an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:14:31 -05:00
bvandeusenandClaude Opus 5.5 1efc65ee10 docs: retake the Home screenshots now a featured guest is a credit, not a mix
The demo library's "Low Tide Choir feat. Ruby Calloway" track no longer
makes a "Songs like Low Tide Choir feat. Ruby Calloway" mix on Home. The
demo README's teardown line now sets DEMO_MUSIC, which compose needs even to
stop the stack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:30:23 -05:00
bvandeusenandClaude Opus 5.5 6351b4651a fix(scanner): a featured guest or a listed collaborator is a credit on the track, not an artist of their own
release / web (push) Successful in 1m13s
release / go (push) Successful in 1m46s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m52s
release / android (push) Successful in 4m11s
release / Build signed APK (push) Successful in 4m42s
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
A track tagged "Low Tide Choir feat. Ruby Calloway" was filed under an
artist of that whole name, with its own page, its own place in the artist
list and its own "Songs like" mix. It is now filed under Low Tide Choir and
keeps "Low Tide Choir feat. Ruby Calloway" as its credit, shown wherever the
track is listed, sent to Subsonic apps and scrobbled.

A collaboration is split only when the file lists its artists one by one
(Picard's ARTISTS tag, read from FLAC, Ogg, Opus, MP3 and M4A). "A & B" on
its own may be one band, so it stays whole. A Vorbis file's artist id is now
its first, not the guest's.

Tag-read version 10 re-reads the library once; the scan's tidy-up removes
the credit-named artists it leaves empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:08:55 -05:00
bvandeusenandClaude Opus 5.5 2bc6c60938 docs: README screenshots come from an invented demo library
release / web (push) Successful in 1m16s
release / go (push) Successful in 1m47s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m1s
release / android (push) Successful in 4m31s
release / Build signed APK (push) Successful in 4m52s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 13s
release / Verify release artifacts (tag releases only) (push) Skipped
Every artist, album, cover and song in the screenshots is generated by
tools/demo-library, so none of it is anyone's real music or art. The
folder builds the library (ffmpeg-synthesised audio, drawn covers),
gives a demo account two months of listening so every Home mix appears,
runs Minstrel and Postgres on a network with no internet, and retakes
the screenshots with Playwright. The README now shows Home, Now playing
and Home on a phone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:24:15 -05:00
bvandeusenandClaude Opus 5.5 f4336cdc23 fix: an album's tracks are credited to their own artists, not all to the album's
release / go (push) Successful in 1m52s
release / web (push) Successful in 1m6s
release / integration (push) Successful in 4m15s
release / govulncheck (push) Successful in 23s
release / android (push) Successful in 4m9s
release / Build signed APK (push) Successful in 4m39s
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
Albums are now filed under their album artist, so a compilation's tracks
and a featured guest's track have a different artist from their album.
The web album page and Subsonic getAlbum named every track after the
album's artist, so a compilation read Various Artists on every row. Both
now name each track by its own artist, read in one query, and fall back
to the album's artist if that lookup fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:05:58 -05:00
bvandeusenandClaude Opus 5.5 55a6f1e437 fix(web): opening an admin or Collection page directly no longer bounces an admin to Home
The two route gates read the signed-in user without waiting for the root
layout to load it. SvelteKit runs layout loads side by side, so a
refresh or a bookmark found no user yet and redirected to Home. Each gate
now awaits parent() before it judges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:05:58 -05:00
bvandeusenandClaude Opus 5.5 c4eaa33e24 fix(web): a Home row with one or two items no longer stretches them across the page
release / go (push) Successful in 1m50s
release / web (push) Successful in 1m14s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m9s
release / android (push) Successful in 4m13s
release / Build signed APK (push) Successful in 4m39s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 25s
release / Verify release artifacts (tag releases only) (push) Skipped
Home rows size their tiles to fill the window, and a row with fewer
items than fit split the whole width between them. One suggestion in
You might like became an album cover as wide as the page. Tiles now
grow to at most twice their minimum width; rows with enough items
still fill the window exactly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:01:35 -05:00
bvandeusenandClaude Opus 5.5 6dda9ef219 fix(web): the app opens over plain HTTP on a home network instead of showing a blank page
Browsers offer crypto.randomUUID only on HTTPS pages and localhost. The
player's client id called it at startup, so opening Minstrel at
http://<host>:4533, as the README's quick start says to, threw before
anything rendered. The id now falls back to crypto.getRandomValues,
which every page has.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:01:35 -05:00
bvandeusenandClaude Opus 5.5 8530b838b0 fix(db): the startup wait closes its probe connection without dropping the error check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:01:35 -05:00
bvandeusenandClaude Opus 5.5 040b90898b fix: Minstrel waits for its database at startup instead of exiting
release / web (push) Successful in 1m12s
release / go (push) Failing after 1m12s
release / govulncheck (push) Successful in 16s
release / integration (push) Successful in 3m49s
release / android (push) Successful in 4m28s
release / Build signed APK (push) Successful in 5m54s
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 first docker compose up starts Minstrel and a new Postgres together, and
the database spends several seconds initialising before it takes
connections. Minstrel tried once and exited, and with no restart policy
in the quick-start compose it stayed down. It now retries every two
seconds for up to two minutes, logging each attempt, and only then exits
with the last connection error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:46:19 -05:00
bvandeusenandClaude Opus 5.5 34c0690667 test(library): drop an unused field from the album-artist test
release / go (push) Successful in 1m49s
release / web (push) Successful in 1m14s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m2s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / android (push) Successful in 4m28s
release / Build signed APK (push) Successful in 4m48s
release / Build + push container image (push) Successful in 17s
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:16:16 -05:00
bvandeusenandClaude Opus 5.5 1a98a23d1f feat(library): albums are filed under their album artist, and empty rows are tidied after a scan
release / go (push) Failing after 1m13s
release / web (push) Successful in 1m16s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m4s
release / android (push) Successful in 4m48s
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) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
The scanner read only the track artist, so a compilation tagged
Various Artists, or an album with one featured-artist track, became one
album per track artist. It now files the album under the album artist
the file names (ALBUMARTIST / TPE2 / aART, with its MusicBrainz id),
and each track keeps its own artist. Tag-read version 9 re-reads the
library so existing tracks move back onto one album.

A scan now ends by removing album rows no track points to, and artists
left with no albums or tracks, telling clients they are gone. Albums
whose tracks are only missing stay for Needs a file, an artist a Songs
like playlist is seeded from stays, and rows made in the last ten
minutes are left alone so a file being added is never caught half way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:08:21 -05:00
bvandeusenandClaude Opus 5.5 ad75f3ac7e chore: comments and tests explain themselves, and the dev compose drops its healthcheck
release / go (push) Successful in 1m39s
release / web (push) Successful in 1m15s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m3s
release / android (push) Successful in 4m46s
release / Build signed APK (push) Successful in 5m5s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 26s
release / Verify release artifacts (tag releases only) (push) Skipped
Test names, assertion messages and comments no longer cite internal
task or rule numbers; each says the reason itself. The dev compose
starts Minstrel after the database without a healthcheck to gate on,
since Minstrel waits for its database at startup on its own. The
published-names test is removed; that check is a local grep before
publishing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:58:58 -05:00
bvandeusenandClaude Opus 5.5 104f9fd141 feat: Your genres leads with the genres you play most, not A to Z
release / web (push) Successful in 1m8s
release / go (push) Successful in 1m40s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 3m43s
release / Build + push container image (push) Successful in 22s
release / Verify release artifacts (tag releases only) (push) Skipped
release / android (push) Successful in 4m21s
release / Build signed APK (push) Successful in 4m55s
release / Attach APK to the Release (tag releases only) (push) Skipped
The genre mix builder already ranks genres by how much you listen to
them (taste profile, then plays and likes, then library size), but the
rank was lost when the mixes were stored and both apps sorted the shelf
by name. Each playlist now has a shelf_rank (migration 0107), which the
genre builder fills 1..n in that listening order, even where it picked a
narrower genre before a broader one. The list and detail endpoints carry
it, and the web and Android Home sort the genre shelf by it, unranked
playlists after by name. Android's playlist cache gains the column
(Room v14).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:10:08 -05:00
bvandeusenandClaude Opus 5.5 7cc14da1a7 feat(android): Home's album and artist shelves step down in size, as on web
release / go (push) Successful in 2m3s
release / web (push) Successful in 1m32s
release / integration (push) Successful in 4m39s
release / govulncheck (push) Successful in 19s
release / android (push) Successful in 5m3s
release / Build signed APK (push) Successful in 5m10s
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
Recently added keeps the 144dp album cover. The You might like and
Rediscover album shelves use 120dp covers, and every artist shelf 104dp
circles, following web's 176 / 144 / 128px tile ranking. Album and
artist cards and their skeletons take the size as a parameter; other
screens keep the defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 13:54:45 -05:00
bvandeusenandClaude Opus 5.5 3f0980a815 docs(db): UpsertArtist matches on mbid only; the comment said name too
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 13:54:45 -05:00
bvandeusenandClaude Opus 5.5 38d138a759 fix(android): the square playlist card dims by the shelf tiles' shared alpha
release / web (push) Successful in 1m37s
release / go (push) Successful in 2m3s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 4m19s
release / android (push) Successful in 4m52s
release / Build signed APK (push) Successful in 5m54s
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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 13:33:00 -05:00
bvandeusenandClaude Opus 5.5 a00fb5a0e0 feat(android): tall playlist cards on a phone held upright, two in view
release / web (push) Successful in 1m24s
release / go (push) Successful in 2m2s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 4m2s
release / android (push) Failing after 4m1s
release / Build signed APK (push) Failing after 4m14s
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
Below 600dp the Playlists shelf's wide cards left one playlist in view.
There the shelf now uses tall cards: the cover on top, and under it the
cover-coloured panel with the name, what the mix is built from and the
play button, sized so two show whole with a glimpse of the third. Wider
screens keep the wide cards; placeholders follow the same switch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 13:23:24 -05:00
bvandeusenandClaude Opus 5.5 23a7b18076 fix(android): the update bar moves while a download already under way finishes
release / web (push) Successful in 1m13s
release / go (push) Successful in 1m42s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m53s
release / android (push) Successful in 4m37s
release / Build signed APK (push) Successful in 4m52s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 27s
release / Verify release artifacts (tag releases only) (push) Skipped
On Wi-Fi the app fetches a new build ahead, holding the download turn.
An Update tap during that waited behind it with a bar stuck at zero,
because the fetch reported its progress to nobody. The repository now
publishes the running download's progress, and the bar follows it
whoever started the download.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 13:00:24 -05:00
bvandeusenandClaude Opus 5.5 ad7609e4c1 fix(android): name the HSL thirds, give PlaceholderShape its own file, trim the cards file
release / web (push) Successful in 1m14s
release / go (push) Successful in 1m47s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m6s
release / android (push) Successful in 4m27s
release / Build signed APK (push) Successful in 4m52s
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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:38:58 -05:00
bvandeusenandClaude Opus 5.5 d42a355612 feat(android): Home shelves you can tell apart, matching web
release / go (push) Successful in 1m56s
release / web (push) Successful in 1m8s
release / govulncheck (push) Successful in 20s
release / android (push) Failing after 1m16s
release / integration (push) Successful in 3m59s
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 4m29s
Playlists show as wide cards washed in their cover's colour, Songs like
as circles labelled with the artist, and genres as colour bands with a
fan of three covers across 80% of the band, leftmost on top. Each tile
on a shelf gets a cover no tile before it shows, and the size and
refresh time the mixes share sit once beside the shelf's title.

The cached playlist row keeps the cover albums and creation time the
playlists list now carries (Room v13, MIGRATION_12_13). Placeholders
take their shelf's shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:29:00 -05:00
bvandeusenandClaude Opus 5.5 e71c132cc7 test(playlists): key the same-day snapshot by mix, not by name
release / web (push) Successful in 1m20s
release / go (push) Successful in 1m49s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 4m8s
release / android (push) Successful in 4m48s
release / Build signed APK (push) Successful in 5m39s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 1m20s
release / Verify release artifacts (tag releases only) (push) Skipped
The fixture makes one artist row per track, so artists share names, and
with twelve Songs like mixes two can both be "Songs like X". Keyed by
name, their tracks merged and interleaved in tie order, so the snapshot
varied though the mixes did not. Name plus seed artist identifies a mix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:17:17 -05:00
bvandeusenandClaude Opus 5.5 e4728e003a test(playlists): the same-day determinism test names the mix that changed
release / go (push) Successful in 1m47s
release / web (push) Successful in 1m8s
release / govulncheck (push) Successful in 27s
release / integration (push) Failing after 4m2s
release / android (push) Successful in 4m48s
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) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 07:45:43 -05:00
bvandeusenandClaude Opus 5.5 806658aa60 feat(playlists): twelve Songs like mixes a day, drawn from a top-24 artist pool
release / go (push) Successful in 2m2s
release / web (push) Successful in 1m14s
release / govulncheck (push) Successful in 20s
release / integration (push) Failing after 4m5s
release / android (push) Successful in 4m38s
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) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
Six mixes stretched to oversized circles on a wide window; twelve fill
the row at its normal tile size. The pool doubles with the count so the
daily shuffle still rotates which artists get a mix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 07:24:58 -05:00
bvandeusenandClaude Opus 5.5 46d97e51f7 fix(web): a genre band's fan spans 80% of its width, leftmost cover on top
release / go (push) Successful in 1m59s
release / web (push) Successful in 1m26s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 4m22s
release / android (push) Successful in 4m28s
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 4m43s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 07:15:12 -05:00
bvandeusenandClaude Opus 5.5 c4ac14d77a fix(web): genre fans grow with their band, and short shelves fill the row
release / go (push) Successful in 1m51s
release / web (push) Successful in 1m31s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m22s
release / android (push) Successful in 4m58s
release / Build signed APK (push) Successful in 5m6s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 27s
release / Verify release artifacts (tag releases only) (push) Skipped
A genre band's fan of covers is sized to the band's height (74% of it),
larger than before, and may run under the genre's name again; the name
sits on a dark translucent backing that keeps it readable over any cover.

A shelf with fewer items than fit across the page now splits the whole
width between them, so no shelf ends partway across.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:09:52 -05:00
bvandeusenandClaude Opus 5.5 ca70cf7678 test(web): a wide card's wash is its cover colour as washTone tones it
release / web (push) Successful in 1m45s
release / go (push) Successful in 2m10s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m23s
release / android (push) Successful in 4m58s
release / Build signed APK (push) Successful in 5m36s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 40s
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 17:51:13 -05:00
bvandeusenandClaude Opus 5.5 b8aacc71e3 fix(web): import the shelf helpers the shelf tests use
release / go (push) Successful in 2m6s
release / web (push) Failing after 1m18s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m2s
release / android (push) Successful in 4m19s
release / Build signed APK (push) Successful in 5m5s
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-23 17:29:39 -05:00
bvandeusenandClaude Opus 5.5 e311e434a8 fix(web): home shelves fill the window and their text stays readable on any cover
release / web (push) Failing after 11s
release / go (push) Successful in 1m52s
release / govulncheck (push) Successful in 23s
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 / integration (push) Canceled after 4m12s
release / android (push) Canceled after 4m3s
release / Build signed APK (push) Canceled after 2m3s
A wide card or genre band's wash keeps its cover's hue but caps its
lightness and saturation, so a pale or loud cover no longer washes the
card too light for its text; the faintest text on it is 80% parchment,
and a test checks 4.5:1 against the lightest wash allowed. A genre's
name keeps clear of its fan of covers.

Shelves size their tiles to the window: each shows a whole number of
tiles that fill its width, a short shelf grows its tiles up to a cap,
and the arrows page by whole tiles. On a very wide screen the page stops
at 140rem and centres.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 17:25:27 -05:00
bvandeusenandClaude Opus 5.5 16225f09f7 fix(web): shelf headings count through plural(), and the day-count test matches calendar days
release / go (push) Successful in 1m53s
release / web (push) Successful in 1m44s
release / govulncheck (push) Successful in 24s
release / integration (push) Successful in 5m6s
release / android (push) Successful in 5m21s
release / Build signed APK (push) Successful in 5m49s
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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 16:13:57 -05:00
bvandeusenandClaude Opus 5.5 5e7b8a7694 feat(web): home shelves you can tell apart at a glance
release / go (push) Successful in 1m46s
release / web (push) Failing after 1m8s
release / govulncheck (push) Successful in 23s
release / integration (push) Successful in 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 / Build signed APK (push) Canceled after 1m38s
release / android (push) Canceled after 3m3s
Each home shelf now has its own shape. Main mixes and playlists are wide
cards: the lead album's cover on a wash of its own colour, with the name
and what the mix is built from beside it rather than over the art. Songs
like mixes are circles, the shape artists already have. Genre mixes are
short bands with a fan of three covers. Shelf sizes step down from the
main mixes.

Tiles show album covers in place of the four-cover collage, and no cover
repeats along a shelf while a tile still has an unused one. The size and
refresh time every mix on a shelf shares is said once, beside the shelf's
title. Library pages keep the square card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 16:09:02 -05:00
bvandeusenandClaude Opus 5.5 ec017838a2 feat(playlists): playlists list their cover albums, and system mixes say what they hold
release / go (push) Successful in 2m2s
release / web (push) Successful in 1m26s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 4m11s
release / android (push) Successful in 4m10s
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 2m48s
Each playlist on the wire (list and get) carries cover_album_ids: up to
six distinct albums with art, in the order they first appear. A shelf of
playlist tiles takes each tile's first album that no tile before it
shows, so no cover repeats along the shelf.

System mixes are stored with a one-line description of what they are
built from, written in one place so the web and Android apps show the
same words. Songs like and genre mixes have none; their names say it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:59:44 -05:00
bvandeusenandClaude Opus 5.5 0e2538e888 chore: license Minstrel under the AGPL-3.0
release / go (push) Successful in 2m1s
release / web (push) Successful in 1m23s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m9s
release / android (push) Successful in 4m34s
release / Build signed APK (push) Successful in 5m14s
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
LICENSE is the GNU Affero General Public License v3.0, verbatim from
gnu.org, replacing the MIT text from the first commit. The README says
what it means for someone running a changed copy as a service.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:41:03 -05:00
bvandeusenandClaude Opus 5.5 84d700b036 docs(screenshots): home page on the current UI
The account name in the header reads "demo" so no real account ships
with the repository.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:32:29 -05:00
bvandeusenandClaude Opus 5.5 dbe075c686 test(release): the published tree names no music-finding tool
release / go (push) Successful in 2m16s
release / web (push) Successful in 1m26s
release / integration (push) Successful in 4m37s
release / govulncheck (push) Successful in 22s
release / android (push) Successful in 4m35s
release / Build signed APK (push) Successful in 5m4s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 17s
release / Verify release artifacts (tag releases only) (push) Skipped
A go-lane test reads every tracked file and path and fails on any of the
music-finding tools Minstrel no longer uses or ships beside. It holds their
names only as hashes, so it does not name them itself, and a second test
shows the matcher catching a stand-in name in any case and inside a word.

Also gone: the screenshots of the removed integration, requests and
auto-approve screens (the README no longer shows the old admin page), and
comments that still spoke of indexer keys and re-acquisition.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:24:04 -05:00
bvandeusenandClaude Opus 5.5 71a1a7414a fix(library): a file back at a waiting track's path brings it back at once
release / go (push) Successful in 1m40s
release / web (push) Successful in 1m15s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 3m50s
release / android (push) Successful in 4m29s
release / Build signed APK (push) Successful in 4m45s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 42s
release / Verify release artifacts (tag releases only) (push) Skipped
The watcher scans single files and never reconciles, and a file restored
with its old mtime takes the unchanged skip, so a track whose file came
back at the same path waited in Needs a file for the next full scan. The
scan now clears the mark when the path it reads belongs to a waiting
track, and tells clients it plays again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:05:48 -05:00
bvandeusenandClaude Opus 5.5 813c289bc0 fix(web): track menus open past a short list, and the player's flag box opens up
release / web (push) Successful in 1m24s
release / go (push) Successful in 1m48s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m55s
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 2m2s
release / android (push) Canceled after 2m53s
TrackList no longer clips its rows, so a row's menu shows under a one-row
search result; the first and last rows round their own corners instead.
The flag box takes its menu's direction, so on the player bar it opens
above the bar instead of off the screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:01:40 -05:00
bvandeusenandClaude Opus 5.5 285a24f0ab feat(db): fold every migration into one baseline at version 106
release / web (push) Successful in 1m13s
release / go (push) Successful in 1m48s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 3m56s
release / android (push) Successful in 4m19s
release / Build signed APK (push) Successful in 4m40s
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
0106_baseline.up.sql is the schema at version 106 and the settings rows
it starts with, taken from a database migrated through 0001–0106; a
database built from the baseline alone dumps identically. A database
already at 106 skips it. Comments that pointed at a migration number now
name the table or constraint instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 00:57:18 -05:00
bvandeusenandClaude Opus 5.5 13df3d756d style(api): gofmt the playback-error resolutions
release / go (push) Successful in 2m6s
release / web (push) Successful in 1m27s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m16s
release / android (push) Successful in 4m18s
release / Build signed APK (push) Successful in 4m40s
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-23 00:44:53 -05:00
bvandeusenandClaude Opus 5.5 27b52c3993 feat(db): migration 106 also drops the request enums
release / go (push) Failing after 1m16s
release / web (push) Successful in 1m15s
release / govulncheck (push) Successful in 19s
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 2m16s
release / Build signed APK (push) Canceled after 1m7s
release / integration (push) Canceled after 3m40s
request_kind and request_status were the requests table's column types
and outlived it. No database has run 106 yet, so it carries the drop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 00:36:23 -05:00
bvandeusenandClaude Opus 5.5 c5e5387977 chore: clear the request-era leftovers
release / integration (push) Canceled after 0s
release / web (push) Canceled after 0s
release / android (push) Canceled after 0s
release / govulncheck (push) Canceled after 0s
release / Build signed APK (push) Canceled after 0s
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 / go (push) Canceled after 8s
A playback error can no longer be resolved as "requested": the server
refuses it, migration 106 takes it out of the CHECK (no row used it), and
the Reports history and types drop its label. The web and Android error
tables lose the copy for errors only the wanted list, follows, release-type
profiles, downloads and indexers sent, and comments stop naming Discover,
following and the requests page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 00:33:18 -05:00
bvandeusenandClaude Opus 5.5 8c6bbac48d feat(db): drop the acquisition and Discover tables
release / web (push) Successful in 1m22s
release / go (push) Successful in 1m49s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 4m10s
release / android (push) Successful in 4m27s
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 22s
release / Verify release artifacts (tag releases only) (push) Skipped
Migration 105 removes the tables the acquisition and Discover features
kept, and users.auto_approve_requests. Before library_album_matches goes,
an album with no release-group MBID takes the one its match listed.
Tables drop without CASCADE, in reference order, so a reference from a
table that stays stops the migration. The down migration refuses: the
data is gone, and a backup from before it is the way back.

The backup table list, the test reset list and the duplicate and user
queries follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 00:20:22 -05:00
bvandeusenandClaude Opus 5.5 741c748135 test(api): quarantine tests no longer clear the requests table
release / web (push) Successful in 1m32s
release / go (push) Successful in 1m58s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m34s
release / android (push) Successful in 4m37s
release / Build signed APK (push) Successful in 5m15s
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
dbtest.ResetDB clears it, and the table is on its way out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 19:11:08 -05:00
bvandeusenandClaude Opus 5.5 51afbb8df5 feat(android): Admin Quarantine is Reports, with the web's two removals
release / android (push) Canceled after 0s
release / govulncheck (push) Canceled after 0s
release / Build signed APK (push) Canceled after 0s
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 / web (push) Canceled after 11s
release / integration (push) Canceled after 11s
release / go (push) Canceled after 12s
The Admin card is Reports ("Tracks listeners flagged"). Each report
offers Resolve, Remove the file (the file goes and the track waits for a
good copy, with its likes and plays) and Remove from library (track,
file and history). Both removals now ask first; Delete file used to
delete on the tap.

They stay online-only: each deletes a file for good against a live
queue, so a replay hours later could act on a decision another admin
has since made. Offline they fail with the reason and the row returns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 19:11:00 -05:00
bvandeusenandClaude Opus 5.5 f52eb1a6fa test(web): the Reports history names a full removal as the page now does
release / go (push) Successful in 1m59s
release / web (push) Successful in 1m33s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m34s
release / Build + push container image (push) Successful in 24s
release / Verify release artifacts (tag releases only) (push) Skipped
release / android (push) Successful in 4m51s
release / Build signed APK (push) Successful in 5m21s
release / Attach APK to the Release (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:51:58 -05:00
bvandeusenandClaude Opus 5.5 bcd9e422a5 feat(web): every Collection queue can remove the file and keep the track
release / web (push) Failing after 1m28s
release / go (push) Successful in 1m53s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 4m16s
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 2m13s
release / android (push) Canceled after 2m59s
Reports offers "Remove the file" ahead of "Remove from library": the
bad file goes and the track waits in Needs a file, with its likes and
plays, for a good copy. Suspect sources gets "Remove this file", and the
Duplicates wrong-slot action and its route are named for what they do
(remove-files). Their toasts and copy name Needs a file.

Missing files becomes Needs a file in the rail, the Collection header and
the Overview counts. Each track says why it waits and who removed it, and
can be forgotten one at a time or by folder; the list exports as a CSV or
copies to the clipboard. The empty state says how a track gets there and
how it leaves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:47:36 -05:00
bvandeusenandClaude Opus 5.5 492eb2fb9a feat(library): Missing files says why each track waits, and can forget or export it
release / go (push) Successful in 1m49s
release / web (push) Successful in 1m26s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m29s
release / android (push) Successful in 4m43s
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
- The missing list carries each track's disc and track number, its
  recording and release-group MBIDs, the Collection queue its file was
  removed from, and the admin who removed it.
- POST /api/admin/library/missing/forget deletes waiting tracks for good,
  tidying away an album or artist they leave empty, and writes a
  track_forget audit row naming each. It is all or nothing: a track that
  has its file again is refused with 409 track_has_file.
- GET /api/admin/library/missing.csv exports every waiting track (artist,
  album, disc, track, title, MBIDs, why, since) to hand to whatever finds
  music.
- DELETE /api/admin/tracks/{id} is retired. No client called it; its
  service becomes tracks.Service.ForgetTracks.

Grimoire #7744 (milestone 635).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:34:01 -05:00
bvandeusenandClaude Opus 5.5 9462052625 feat(library): removing a bad file keeps its track, waiting for a good copy
release / go (push) Successful in 2m6s
release / web (push) Successful in 1m15s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m46s
release / android (push) Successful in 4m47s
release / Build signed APK (push) Successful in 5m38s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 31s
release / Verify release artifacts (tag releases only) (push) Skipped
Reports, Duplicates and Suspect sources now end the same way: the file
goes and the track stays, marked missing with its likes, plays and
playlist places, until a good copy lands in the library and move
adoption or missing-pair folding brings it back.

- library.RemoveFile removes one track's file and marks the track
  missing with the queue it was removed from and who removed it
  (tracks.removed_reason / removed_by, migration 0104). The duplicate
  resolver's wrong-slot removal shares the same marking.
- POST /api/admin/quarantine/{id}/remove-file removes a reported file,
  clears the listeners' reports, marks open playback errors deleted and
  records removed_file in the Reports history. A wrong-file or
  wrong-tags report drops the file's recording MBID.
- POST /api/admin/library/suspect-sources/{id}/remove removes a video
  rip's file and its MBID, and writes a suspect_file_remove audit row.
- The removal reason clears with the missing mark when a file returns.

Grimoire #7743 (milestone 635).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:17:26 -05:00
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
bvandeusen 0192c0744c Merge pull request 'Main builds and bundles its own signed APK, so a merge ships the app without a release (#6465)' (#157) from dev into main
release / govulncheck (push) Successful in 16s
release / web (push) Successful in 1m33s
release / go (push) Successful in 1m51s
release / android (push) Successful in 5m24s
release / integration (push) Successful in 5m29s
release / Build signed APK (push) Successful in 5m34s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 38s
release / Verify release artifacts (tag releases only) (push) Skipped
2026-10-26 13:22:20 -04:00
bvandeusenandClaude Opus 5.5 be642cd53f ci: main builds and bundles its own signed APK, so a merge ships the app without a release (#6465)
release / web (push) Successful in 1m51s
release / go (push) Successful in 2m6s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 6m53s
release / android (push) Successful in 5m41s
release / Build signed APK (push) Successful in 5m38s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 18s
release / Verify release artifacts (tag releases only) (push) Skipped
android-release now runs on main as well as dev and tags, and image-release
requires its success on every ref. :latest carries the stable APK built from
main's own commit instead of the newest release's, so a merged app change
reaches stable phones on the next pull. Releases stay as optional bookmarks
that attach the APK for download.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 12:49:39 -04:00
bvandeusen 7529266f5b Merge pull request 'DLNA renderers, app updates told like Librarian, acquisition without Lidarr, Collection and admin rework (M502–M505, M542)' (#156) from dev into main
release / web (push) Successful in 1m29s
release / go (push) Successful in 1m49s
release / govulncheck (push) Successful in 26s
release / android (push) Successful in 6m19s
release / integration (push) Successful in 6m47s
release / Build signed APK (releases and dev) (push) Successful in 6m17s
release / Attach APK to the Release (tag releases only) (push) Successful in 3s
release / Build + push container image (push) Successful in 23s
release / Verify release artifacts (tag releases only) (push) Successful in 2s
2026-10-26 12:32:32 -04:00
bvandeusenandClaude Opus 5.5 7d5dcd454e docs: two comments state the rule rather than its history (#6277)
release / govulncheck (push) Successful in 17s
release / web (push) Successful in 1m47s
release / go (push) Successful in 2m2s
release / android (push) Successful in 5m49s
release / Build signed APK (releases and dev) (push) Successful in 6m1s
release / integration (push) Successful in 6m18s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 18s
release / Verify release artifacts (tag releases only) (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 11:20:17 -04:00
bvandeusenandClaude Opus 5.5 3fa5d9fc3a fix: an app update is offered only when the app changed; casting no longer sticks on "loading" when the same queue plays again (#6455, #6456)
release / govulncheck (push) Successful in 16s
release / web (push) Successful in 1m30s
release / go (push) Successful in 1m46s
release / android (push) Successful in 5m2s
release / Build signed APK (releases and dev) (push) Successful in 5m13s
release / integration (push) Successful in 5m22s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 13s
release / Verify release artifacts (tag releases only) (push) Skipped
ci/version.sh --apk names the APK from android/ alone, and the APK lane
calls it. The app offers an update when the server's APK name differs from
its own, so a name derived from the whole repo offered every phone a rebuild
of the app it already had on each server-only deploy. The image keeps the
union set: it bundles the APK under client/.

Casting (#6456):
- setMediaItems with the tracks already queued (play the queued album from
  another track) cleared the cast and waited for a resync that the id-keyed
  collector never ran. It is now a move within the queue: Seek TRACK_NR on a
  Sonos, start that track on a one-track renderer; the play() goes through.
- A queue replaced through setMediaItems could take the Sonos incremental
  diff, which cleared target without restoring active, so the app thought it
  was back on the phone while the speaker played on, and the chosen start
  track was ignored. The diff now runs only while the route is still active;
  a replaced queue reloads in full at its start index.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 10:08:02 -04:00
bvandeusenandClaude Opus 5.5 fa75bd08d7 feat: a newer app is told in a snackbar on Home and installed from a sheet holding Settings' card, fetched ahead on Wi-Fi (#6452)
release / govulncheck (push) Successful in 21s
release / web (push) Successful in 1m41s
release / go (push) Successful in 1m55s
release / android (push) Successful in 5m19s
release / Build signed APK (releases and dev) (push) Successful in 5m31s
release / integration (push) Successful in 5m39s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 28s
release / Verify release artifacts (tag releases only) (push) Skipped
Mirrors Librarian (#6446, #6448), after Gallery's update tray (canon #6367).

- Home shows "Version X of the app is on your server." / "…is downloaded
  and ready." with Update / Install; the button opens a bottom sheet
  holding the same About card Settings shows, so there is one install
  path. Each build is told at most once a day, kept on disk.
- The shell-wide update banner and its in-memory dismissals are gone.
- AppUpdates (singleton) holds the offer and the install, so Home and
  Settings show the same state. Checks run when either screen opens, on
  every return to the front, every 5 minutes while shown, and on Home's
  pull to refresh.
- UpdateFetchWorker downloads the newer APK ahead on an unmetered network
  (battery and storage not low, three tries); the download writes a .part
  file and keeps it under the build's name only once its size and sha256
  match, so Install is usually one tap.
- Back from allowing installs, the update the listener asked for carries
  on (kept in SavedStateHandle) instead of asking them to tap again.
- An offer needs a higher code AND a different name: the same app built
  again at a later minute is not offered.
- Server: /api/client/version reports the APK's sha256, worked out from
  the served file and cached by size and mtime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 07:46:01 -04:00
bvandeusenandClaude Opus 5.5 de41169ccb fix(android): detekt — no four-way destructuring, single-track loader within the function cap (#6451)
The library-duration fallback rides on the poll outcome instead of being its
own member, and the adopt path reads the target's fields by name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 07:46:01 -04:00
bvandeusen 165c87047e Merge pull request 'Duplicates and video rips resolve themselves (M498)' (#155) from dev into main
release / Build signed APK (releases and dev) (push) Skipped
release / govulncheck (push) Successful in 17s
release / web (push) Successful in 1m20s
release / go (push) Successful in 1m36s
release / integration (push) Successful in 4m15s
release / android (push) Successful in 5m18s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 28s
release / Verify release artifacts (tag releases only) (push) Skipped
2026-10-08 22:30:10 -04:00
bvandeusen 05bc85f2b8 Merge dev: scroll-loaded lists, Liked tabs, missing files kept out of the queue (#5416, #5417, #5418)
release / Build signed APK (releases and dev) (push) Skipped
release / govulncheck (push) Successful in 14s
release / web (push) Successful in 1m4s
release / go (push) Successful in 1m21s
release / integration (push) Successful in 3m56s
release / android (push) Successful in 4m14s
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
2026-10-08 20:08:04 -04:00
bvandeusen d1fe3758d5 Merge dev: Suspect sources report (#5410)
release / Build signed APK (releases and dev) (push) Skipped
release / web (push) Successful in 1m13s
release / go (push) Successful in 1m28s
release / govulncheck (push) Successful in 14s
release / integration (push) Successful in 4m46s
release / android (push) Successful in 5m29s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 30s
release / Verify release artifacts (tag releases only) (push) Skipped
2026-10-08 16:03:53 -04:00
bvandeusen 664b129947 Merge pull request 'One track-list shape across the web app, drag reorder that snaps (M494)' (#152) from dev into main
release / web (push) Successful in 1m17s
release / go (push) Successful in 1m36s
release / Build signed APK (releases and dev) (push) Skipped
release / govulncheck (push) Successful in 27s
release / integration (push) Successful in 4m20s
release / android (push) Successful in 4m45s
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
2026-10-08 15:08:09 -04:00
bvandeusen c9fa18ecb7 Merge pull request 'Notifications inbox (M489), Discover taste-arm fix, web tooling majors' (#151) from dev into main
release / govulncheck (push) Successful in 16s
release / web (push) Successful in 1m8s
release / Build signed APK (releases and dev) (push) Skipped
release / go (push) Successful in 1m27s
release / integration (push) Successful in 5m1s
release / android (push) Successful in 5m35s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 1m34s
release / Verify release artifacts (tag releases only) (push) Skipped
2026-10-08 11:11:08 -04:00
bvandeusen 3077ed75fe Merge pull request 'Readable accent text app-wide; Android queue drag math under test' (#144) from dev into main
release / govulncheck (push) Successful in 18s
release / Build signed APK (releases and dev) (push) Skipped
release / web (push) Successful in 1m16s
release / go (push) Successful in 1m30s
release / integration (push) Successful in 4m2s
release / android (push) Successful in 4m20s
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
2026-10-08 06:29:48 -04:00
bvandeusen 97e84a79eb Merge pull request 'Multi-value genres for FLAC/Ogg/MP4, readable tinted and error text, no missing-track seeds' (#143) from dev into main
release / Build signed APK (releases and dev) (push) Skipped
release / govulncheck (push) Successful in 31s
release / web (push) Successful in 1m19s
release / go (push) Successful in 1m41s
release / android (push) Successful in 4m44s
release / integration (push) Successful in 17m13s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 1m20s
release / Verify release artifacts (tag releases only) (push) Skipped
2026-10-07 23:53:09 -04:00
bvandeusen a29ceaaeab Merge pull request 'Similarity cache and round-robin artist arms (#5296, #5297)' (#142) from dev into main
release / android (push) Successful in 5m1s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 2m25s
release / Verify release artifacts (tag releases only) (push) Skipped
release / go (push) Successful in 2m28s
release / web (push) Successful in 57s
release / govulncheck (push) Successful in 19s
release / Build signed APK (releases and dev) (push) Skipped
release / integration (push) Successful in 5m9s
2026-10-07 20:02:59 -04:00
bvandeusen 54b2720d76 Merge pull request 'Fold stale missing tracks into their on-disk replacement (M485)' (#141) from dev into main
release / Build signed APK (releases and dev) (push) Skipped
release / govulncheck (push) Successful in 15s
release / web (push) Successful in 1m2s
release / go (push) Successful in 1m20s
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped
release / integration (push) Successful in 3m51s
release / android (push) Successful in 4m19s
release / Attach APK to the Release (tag releases only) (push) Skipped
2026-10-07 18:17:51 -04:00
bvandeusen fe142e3451 Merge dev: request completion fix, x/text bump, full-logo tab icon (#140)
release / govulncheck (push) Successful in 22s
release / Build signed APK (releases and dev) (push) Skipped
release / web (push) Successful in 1m54s
release / go (push) Successful in 2m22s
release / integration (push) Successful in 5m7s
release / android (push) Successful in 5m47s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 17s
release / Verify release artifacts (tag releases only) (push) Skipped
2026-10-07 15:35:01 -04:00
bvandeusen 3bdfa94f39 Merge dev: M483 release-group ids for Lidarr (#139)
release / integration (push) Successful in 3m46s
release / android (push) Successful in 4m24s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build signed APK (releases and dev) (push) Skipped
release / govulncheck (push) Successful in 17s
release / web (push) Successful in 1m1s
release / go (push) Successful in 1m21s
release / Build + push container image (push) Successful in 16s
release / Verify release artifacts (tag releases only) (push) Skipped
2026-10-07 12:29:12 -04:00
bvandeusen 22ea27efff Merge pull request 'Lidarr: album adds that Lidarr accepts, artist monitoring that sticks' (#138) from dev into main
release / govulncheck (push) Successful in 27s
release / Build signed APK (releases and dev) (push) Skipped
release / web (push) Successful in 1m21s
release / go (push) Successful in 1m48s
release / integration (push) Successful in 4m24s
release / android (push) Successful in 5m16s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 25s
2026-10-07 11:08:18 -04:00
bvandeusen 09bd71629a Merge pull request 'M401: AcoustID recording-id lookup' (#137) from dev into main
release / Build signed APK (releases and dev) (push) Skipped
release / govulncheck (push) Successful in 34s
release / web (push) Successful in 1m6s
release / go (push) Successful in 1m24s
release / integration (push) Successful in 4m3s
release / android (push) Successful in 5m17s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 1m26s
release / Verify release artifacts (tag releases only) (push) Skipped
2026-10-07 09:50:11 -04:00
bvandeusen c83670d216 Merge pull request 'M464 loudness leveling (steps 4–8), APK distribution and security baseline adoptions' (#136) from dev into main
release / web (push) Successful in 1m41s
release / go (push) Successful in 2m0s
release / Build signed APK (releases and dev) (push) Skipped
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 6m6s
release / android (push) Successful in 7m23s
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
2026-10-06 23:11:35 -04:00
bvandeusen 1e9aed214b Merge pull request 'M462 security hardening and M464 loudness analysis (steps 1–3)' (#135) from dev into main
release / go (push) Successful in 2m19s
release / web (push) Successful in 1m43s
release / govulncheck (push) Successful in 35s
release / Build signed APK (releases and dev) (push) Skipped
release / android (push) Successful in 6m10s
release / integration (push) Successful in 19m35s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 2m24s
release / Verify release artifacts (tag releases only) (push) Skipped
2026-10-06 14:19:58 -04:00
bvandeusen 3638d1d822 Merge pull request 'M400: acoustic duplicate detection, history-preserving merge, and fingerprinting settings' (#134) from dev into main
release / Build signed APK (releases and dev) (push) Skipped
release / Build + push container image (push) Successful in 1m32s
release / Verify release artifacts (tag releases only) (push) Skipped
test-go / test (push) Successful in 1m46s
test-go / integration (push) Successful in 4m19s
test-web / test (push) Successful in 33s
2026-09-11 20:56:55 -04:00
bvandeusen 18618bd135 Backfill fingerprints for the existing library (M400 #3908) (#133)
release / Build signed APK (releases and dev) (push) Skipped
release / Build + push container image (push) Successful in 16s
release / Verify release artifacts (tag releases only) (push) Skipped
test-web / test (push) Successful in 49s
test-go / test (push) Successful in 1m11s
test-go / integration (push) Successful in 3m16s
2026-09-11 15:34:19 -04:00
bvandeusen d2985f3841 Acoustic fingerprints at ingest, a delete that can't lose history, and a reproducible candidate draw (#132)
release / Build signed APK (releases and dev) (push) Skipped
release / Build + push container image (push) Successful in 20s
release / Verify release artifacts (tag releases only) (push) Skipped
test-web / test (push) Successful in 1m0s
test-go / test (push) Successful in 1m20s
test-go / integration (push) Successful in 3m35s
android / Build + lint + test (push) Successful in 4m48s
2026-09-11 14:43:00 -04:00
bvandeusen f70df9f827 Recommendation relevance, the rollback unit, and a version that names what shipped (#131)
test-web / test (push) Successful in 1m5s
test-go / test (push) Successful in 1m33s
test-go / integration (push) Successful in 4m25s
android / Build + lint + test (push) Successful in 5m33s
release / Build signed APK (releases and dev) (push) Successful in 4m38s
release / Build + push container image (push) Successful in 16s
release / Verify release artifacts (tag releases only) (push) Successful in 2s
2026-09-10 23:37:57 -04:00
bvandeusen 439c8625d5 Fix the rebundle step: a non-matching grep must not kill it (#130)
test-go / test (push) Successful in 59s
test-go / integration (push) Successful in 3m1s
release / Build signed APK (releases and dev) (push) Successful in 4m41s
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Successful in 2s
2026-09-10 10:49:40 -04:00
bvandeusen 1d67c160b2 Versioning rework, a dev channel, and the miniplayer gap (#129)
release / Build signed APK (releases and dev) (push) Skipped
android / Build + lint + test (push) Failing after 4s
release / Build + push container image (push) Failing after 5s
release / Verify release artifacts (tag releases only) (push) Skipped
test-go / test (push) Successful in 1m24s
test-go / integration (push) Successful in 6m25s
2026-09-10 08:33:26 -04:00
bvandeusen 237380b122 New brand mark, and both clients stop fetching their fonts at runtime (#128)
test-web / test (push) Successful in 54s
android / Build + lint + test (push) Successful in 5m36s
release / Build signed APK (tag releases only) (push) Successful in 4m36s
release / Build + push container image (push) Successful in 24s
release / Verify release artifacts (tag releases only) (push) Successful in 2s
2026-09-09 14:36:15 -04:00
bvandeusen 4f077736b6 Merge PR #127: Sonos queue verification, cast double-download fix, stutter instrumentation
android / Build + lint + test (push) Successful in 4m16s
release / Build signed APK (tag releases only) (push) Successful in 5m25s
release / Build + push container image (push) Successful in 1m16s
release / Verify release artifacts (tag releases only) (push) Successful in 1s
2026-08-18 10:50:10 -04:00
bvandeusen 727f68950e Merge PR #126: missing-file lifecycle, UPnP stall recovery, Android browse parity, Flutter client removed
release / Build signed APK (tag releases only) (push) Skipped
test-web / test (push) Successful in 1m5s
test-go / test (push) Successful in 1m26s
release / Build + push container image (push) Successful in 1m38s
release / Verify release artifacts (tag releases only) (push) Skipped
android / Build + lint + test (push) Successful in 4m54s
test-go / integration (push) Successful in 5m19s
2026-08-17 16:28:13 -04:00
bvandeusen aa9f534f3c Merge pull request 'Genre index: sort A–Z, and repair casing damage at scan time' (#124) from dev into main
test-web / test (push) Successful in 49s
test-go / test (push) Successful in 1m9s
test-go / integration (push) Successful in 5m1s
release / Build signed APK (tag releases only) (push) Successful in 4m2s
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Successful in 2s
2026-08-07 21:40:33 -04:00
bvandeusen 011b4d9a9c Merge pull request 'ci(release): verify a tag release actually shipped its artifacts' (#123) from dev into main
release / Build signed APK (tag releases only) (push) Successful in 3m38s
release / Build + push container image (push) Successful in 1m31s
release / Verify release artifacts (tag releases only) (push) Successful in 2s
2026-08-07 08:32:48 -04:00
bvandeusen d5aa081157 Merge pull request 'Recommendation metrics: publish the margin of error on every delta' (#122) from dev into main
test-web / test (push) Successful in 52s
test-go / test (push) Successful in 1m10s
test-go / integration (push) Successful in 4m53s
release / Build signed APK (tag releases only) (push) Successful in 3m57s
release / Build + push container image (push) Successful in 1m37s
2026-08-06 21:50:41 -04:00
bvandeusen a99f855e98 Merge pull request 'Missing files: detect them, stop offering them, and follow them when they move' (#121) from dev into main
test-go / test (push) Successful in 56s
test-go / integration (push) Successful in 5m0s
release / Build signed APK (tag releases only) (push) Successful in 4m14s
release / Build + push container image (push) Successful in 15s
2026-08-06 20:40:39 -04:00
bvandeusen 7e4727fc49 Merge pull request 'Genre tags: read multi-value frames correctly, and repair existing rows' (#120) from dev into main
test-go / test (push) Successful in 57s
test-go / integration (push) Successful in 4m57s
release / Build signed APK (tag releases only) (push) Successful in 4m23s
release / Build + push container image (push) Successful in 1m39s
2026-08-05 22:10:41 -04:00
bvandeusen 1b7fa635d8 Merge pull request 'Silent self-update, active sessions with real client IPs, genre/year browsing, handoff fix' (#119) from dev into main
test-web / test (push) Successful in 1m3s
test-go / test (push) Successful in 1m13s
test-go / integration (push) Successful in 5m29s
android / Build + lint + test (push) Successful in 5m34s
release / Build signed APK (tag releases only) (push) Successful in 5m5s
release / Build + push container image (push) Successful in 16s
2026-08-05 15:14:48 -04:00
bvandeusen 57d2299180 Merge pull request 'Queue row gestures: album art as grab surface + swipe-to-remove' (#118) from dev into main
test-web / test (push) Successful in 48s
android / Build + lint + test (push) Successful in 5m15s
release / Build signed APK (tag releases only) (push) Successful in 4m38s
release / Build + push container image (push) Successful in 1m48s
2026-08-04 11:37:30 -04:00
bvandeusen fa7ea41ccf Merge pull request 'Minstrel gets a mark — favicon, header lockup, Android adaptive icon' (#117) from dev into main
test-web / test (push) Successful in 47s
android / Build + lint + test (push) Successful in 4m37s
release / Build signed APK (tag releases only) (push) Successful in 8m36s
release / Build + push container image (push) Successful in 1m37s
2026-08-03 20:52:27 -04:00
bvandeusen 324059b2bd Merge pull request 'Discover request surface — taste-aware, rotating, snoozable, tag-targeted (milestone #268)' (#116) from dev into main
test-web / test (push) Successful in 1m5s
test-go / test (push) Successful in 1m30s
android / Build + lint + test (push) Successful in 5m1s
test-go / integration (push) Successful in 5m29s
release / Build signed APK (tag releases only) (push) Successful in 4m21s
release / Build + push container image (push) Successful in 17s
2026-08-03 08:38:24 -04:00
bvandeusen 1138d75a45 Merge pull request 'Playlist-track atomic replace + ci-requirements true-up' (#115) from dev into main
release / Build signed APK (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 1m33s
android / Build + lint + test (push) Successful in 4m30s
2026-08-01 12:23:37 -04:00
1406 changed files with 42637 additions and 70093 deletions
-4
View File
@@ -33,8 +33,4 @@ docs/
!.env.example !.env.example
# CI workflow files don't need to ship in the image. # CI workflow files don't need to ship in the image.
#
# This said `.forgejo/` and `.github/` — neither of which this repo has. Gitea
# Actions reads `.gitea/`, so the one directory that actually exists was the
# one not excluded, and every workflow edit invalidated the context.
.gitea/ .gitea/
+10
View File
@@ -0,0 +1,10 @@
# Files only the build pipeline uses stay out of `git archive`, which makes
# the public source release. The two release tests pin the workflow file, so
# they leave with it; without it they would fail `go test ./...`.
.gitea/ export-ignore
ci/ export-ignore
ci-requirements.md export-ignore
renovate.json export-ignore
internal/server/release_gate_test.go export-ignore
internal/server/release_version_test.go export-ignore
.gitattributes export-ignore
+313 -368
View File
@@ -1,13 +1,20 @@
name: release name: release
# Builds and pushes the minstrel container image to the Gitea registry. # Builds and pushes the minstrel container image to the Gitea registry, and on
# main also makes the public release.
# #
# push to dev → :dev (freshly-built dev APK bundled) # push to dev → :dev (freshly-built dev APK bundled), and the
# push to main → :latest + :<sha> (latest-release APK bundled) # public release's dry run
# push tag vYYYY.MM.DD.HHMM → :latest (fresh APK bundled) # push to main → :latest + :<sha> (freshly-built stable APK bundled), then
# workflow_dispatch → manual trigger (same rules based on the ref) # THE PUBLIC RELEASE: one commit and tag v<name> on
# github.com/Fabled-Sword/minstrel, the image
# ghcr.io/fabled-sword/minstrel :<name> + :latest, and a
# release page with its changelog on both forges
# workflow_dispatch → the same as a push to the dispatched branch, private
# half only; force_red checks the gate (see below)
# #
# That is the whole tag map. # That is the whole tag map. The rest of this header is about the private
# registry; the public release is described at image-release.
# #
# :<sha> on main is the ROLLBACK UNIT — every production commit addressable # :<sha> on main is the ROLLBACK UNIT — every production commit addressable
# without a release ceremony. It is minted only on main, where rollback is # without a release ceremony. It is minted only on main, where rollback is
@@ -41,35 +48,26 @@ name: release
# image in the same run from the same commit, and the channel cannot go # image in the same run from the same commit, and the channel cannot go
# stale against its own artifact. # stale against its own artifact.
# #
# Release model: the tag IS the artifact's version name with a `v` in front. # Every branch build carries the app built from its own commit, so a merge to
# `v2026.09.10.1432` and `2026.09.10.1432` are the same string, derived from # main is all it takes to put a new app in front of stable phones: `:latest`
# the tagged commit's UTC timestamp — so there is no mismatch to reconcile # serves it from /api/client/apk and the in-app update offers it. The app is
# between what the tag says and what the APK reports, and nothing to look up # never published on its own; it reaches phones only through the server.
# when minting one.
# #
# TAGS ARE IMMUTABLE. Never move, retarget or delete a published tag. A # Release model: a merge to main IS the release. Its name is v<YYYY.MM.DD.HHMM>
# same-day second release is not a collision — HHMM makes every tag unique # from the merge commit's UTC time, so every merge has its own. The run makes
# by construction, so the answer is simply another tag. Anyone installing # the tag on both forges; nobody tags by hand.
# from a moved tag would hold something the tag no longer points at, which
# is a worse failure than an extra row in the tag list.
# #
# :latest is updated by every main push AND every tag push, so it always # TAGS ARE IMMUTABLE. Never move, retarget or delete a published tag. A re-run
# reflects the newest blessed image. # finds its tag already published: on the same tree it goes on, on another it
# stops. A failed public half is fixed on dev, and the next merge carries a new
# name.
# #
# APK pipeline: on tag pushes the android-release job builds + signs the # APK pipeline: on every push the android-release job builds + signs the
# Android APK and uploads it as a workflow artifact. The image-release # Android APK and uploads it as a workflow artifact. The image-release job
# job declares `needs: android-release`, so the docker image cannot # declares `needs: android-release` and requires its success, so the docker
# start building until the APK is guaranteed-ready — no polling, no # image cannot start building until the APK is guaranteed-ready — no polling,
# race, no silent-failure mode. Attaching the APK to the gitea Release is # no race, no silent-failure mode, and no image that moves a channel without
# its own job (release-assets), behind the test gate below. # an app inside it.
#
# :latest always carries an APK. Because every main push also moves
# :latest (not just tags), a main build with no APK would silently strip
# the in-app update channel off :latest until the next release. So on
# non-tag builds image-release pulls the MOST RECENT release's signed APK
# AND the version sidecar published beside it — the recorded values, not
# recomputed ones — so no rebuild is needed, just a rebundle. Tag builds
# keep bundling their own freshly-built APK.
# #
# THE GATE. Every verifying lane lives in this file — # THE GATE. Every verifying lane lives in this file —
# Go (vet, lint, short tests), the Postgres integration suite, the web app # Go (vet, lint, short tests), the Postgres integration suite, the web app
@@ -88,23 +86,20 @@ name: release
# path filters for the same reason: a web-only push still runs the Go suite, # path filters for the same reason: a web-only push still runs the Go suite,
# because "not run" must never read as "passed". # because "not run" must never read as "passed".
# #
# What publishes, and is therefore gated: the image tags (image-release) and # What publishes, and is therefore gated: everything image-release pushes, the
# the APK + version sidecar attached to a tag's Release (release-assets). # private image tags and the whole public release. android-release only BUILDS
# android-release only BUILDS the signed APK into a workflow artifact, which # the signed APK into a workflow artifact, which nobody outside this run can
# nobody outside this run can pull, so it runs in parallel with the lanes # pull, so it runs in parallel with the lanes instead of after them.
# instead of after them; attaching it to the Release is the publishing half,
# and that half waits for the gate.
# #
# To watch the gate refuse: dispatch this workflow with force_red=true. The go # To watch the gate refuse: dispatch this workflow with force_red=true. The go
# lane fails on purpose, and both publishing jobs must report skipped. # lane fails on purpose, and the publishing job must report skipped.
# No path filter. The README, docs and tests ship in the public release too,
# so a merge to main that changes only them must still run, or it would not
# release.
on: on:
push: push:
branches: [main, dev] branches: [main, dev]
tags: ['v*']
paths-ignore:
- 'docs/**'
- '**/*.md'
workflow_dispatch: workflow_dispatch:
inputs: inputs:
force_red: force_red:
@@ -113,10 +108,10 @@ on:
default: false default: false
# A rapid re-push to main supersedes the in-flight build: the later commit # A rapid re-push to main supersedes the in-flight build: the later commit
# wins. Tags are immutable and unique, so no tag build can be superseded by # wins. The event name is in the group so a dispatch and a push on the same
# another run on the same ref. # ref never cancel each other.
concurrency: concurrency:
group: ${{ github.workflow }}-${{ github.ref }} group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }}
cancel-in-progress: true cancel-in-progress: true
jobs: jobs:
@@ -153,8 +148,16 @@ jobs:
- name: golangci-lint - name: golangci-lint
run: golangci-lint run ./... run: golangci-lint run ./...
# ci/testcount prints what plain go test would, plus how many tests
# ran. The step exits with go test's own status, kept aside in a file
# because the shell has no pipefail. The `|| rc=$?` matters: under
# `-e` a bare failing go test ends the group before its status is
# written, and a missing file fails the step as 1, never as a pass.
- name: go test (short, race) - name: go test (short, race)
run: go test -short -race ./... run: |
go build -o /tmp/testcount ./ci/testcount
{ rc=0; go test -short -race -json ./... || rc=$?; echo "$rc" > /tmp/go-test-rc; } | /tmp/testcount
exit "$(cat /tmp/go-test-rc 2>/dev/null || echo 1)"
# Full `go test -race` against an ephemeral Postgres. # Full `go test -race` against an ephemeral Postgres.
# #
@@ -273,16 +276,29 @@ jobs:
fi fi
# Apply embedded migrations to the fresh test DB, then run the # Apply embedded migrations to the fresh test DB, then run the
# full suite (no -short → integration tests execute). -p 1: # packages that hold database tests (no -short, so they execute).
# every integration package TRUNCATEs the one shared test DB; # The `go` lane already runs every unit test; packages with no
# concurrent package binaries → TRUNCATE deadlocks. Serialize # database test are left to it (ci/db-test-packages.sh).
# package execution (the documented local invocation too). #
# -timeout 20m: internal/api alone takes several minutes under # -p 1: every database package TRUNCATEs the one shared test DB,
# -race on an idle runner, and a dev and a main run sharing the # and concurrent package binaries deadlock on TRUNCATE. -p also
# runner can push it past go test's default 10m with nothing # bounds compiling, so the test binaries are built first with
# hung. # full parallelism (-run '^$' runs no test), and the serial pass
# reuses the build cache.
#
# -timeout 20m: internal/api alone takes minutes under -race on a
# busy runner, and a dev and a main run sharing the runner can
# push it past go test's default 10m with nothing hung.
MINSTREL_DATABASE_URL="$MINSTREL_TEST_DATABASE_URL" go run ./cmd/minstrel migrate MINSTREL_DATABASE_URL="$MINSTREL_TEST_DATABASE_URL" go run ./cmd/minstrel migrate
go test -p 1 -race -timeout 20m ./... PKGS=$(sh ci/db-test-packages.sh)
echo "database test packages: $(echo "$PKGS" | wc -l)"
go test -race -run '^$' $PKGS
# ci/testcount prints the usual go test output plus how many tests
# ran; the step exits with go test's own status (no pipefail, and
# `|| rc=$?` so -e cannot end the group before the status is kept).
go build -o /tmp/testcount ./ci/testcount
{ rc=0; go test -p 1 -race -timeout 20m -json $PKGS || rc=$?; echo "$rc" > /tmp/go-test-rc; } | /tmp/testcount
exit "$(cat /tmp/go-test-rc 2>/dev/null || echo 1)"
web: web:
runs-on: go-ci runs-on: go-ci
@@ -359,6 +375,25 @@ jobs:
- name: Unit tests - name: Unit tests
run: ./gradlew testDebugUnitTest run: ./gradlew testDebugUnitTest
# How many tests ran, summed from Gradle's JUnit reports. Runs after a
# failure too, so a red run still says how much of the suite it reached.
- name: Test count
if: always()
run: |
set -- app/build/test-results/testDebugUnitTest/*.xml
if [ ! -e "$1" ]; then echo "no unit test reports"; exit 0; fi
awk '/<testsuite / {
for (i = 1; i <= NF; i++)
if (match($i, /^(tests|skipped|failures|errors)="[0-9]+"/)) {
split($i, kv, "\"")
n[substr($i, 1, index($i, "=") - 1)] += kv[2]
}
}
END {
printf "tests: %d passed, %d failed, %d skipped\n",
n["tests"] - n["failures"] - n["errors"] - n["skipped"], n["failures"] + n["errors"], n["skipped"]
}' "$@"
# No debug APK is built or uploaded here: a debug build is signed by a # No debug APK is built or uploaded here: a debug build is signed by a
# key regenerated in every container, which no install can update. # key regenerated in every container, which no install can update.
# Phones get builds from android-release, signed with the one release # Phones get builds from android-release, signed with the one release
@@ -400,11 +435,12 @@ jobs:
# ------------------------------------------------------------ artifacts -- # ------------------------------------------------------------ artifacts --
android-release: android-release:
name: Build signed APK (releases and dev) name: Build signed APK
# Also builds on `dev`, which is what makes a test channel possible at # Builds on both branches, so each channel's image carries the app from
# all: without it the only way to get a build onto a phone is to cut a # its own commit: `dev` for the test channel, `main` for stable phones.
# release, which quietly turns `main` into the staging area. if: >-
if: startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/dev' github.ref == 'refs/heads/dev'
|| github.ref == 'refs/heads/main'
runs-on: flutter-ci runs-on: flutter-ci
container: container:
image: git.fabledsword.com/bvandeusen/ci-android:36 image: git.fabledsword.com/bvandeusen/ci-android:36
@@ -452,7 +488,7 @@ jobs:
# The derivation lives in ci/version.sh, not here, so it can be # The derivation lives in ci/version.sh, not here, so it can be
# executed by a test on every push. Anything inline in this file is # executed by a test on every push. Anything inline in this file is
# unverifiable until a release is already running. # unverifiable until a release is already running.
out="$(ci/version.sh HEAD)" out="$(ci/version.sh --apk HEAD)"
printf '%s\n' "${out}" >> "$GITHUB_OUTPUT" printf '%s\n' "${out}" >> "$GITHUB_OUTPUT"
# The channel is a property of the LANE, not of the commit, which is # The channel is a property of the LANE, not of the commit, which is
@@ -467,32 +503,6 @@ jobs:
echo "channel=${channel}" >> "$GITHUB_OUTPUT" echo "channel=${channel}" >> "$GITHUB_OUTPUT"
echo "::notice::APK $(printf '%s' "${out}" | tr '\n' ' ') channel=${channel}" echo "::notice::APK $(printf '%s' "${out}" | tr '\n' ' ') channel=${channel}"
# Checked BEFORE the expensive work, not after it. "Attach APK to gitea
# Release" below resolves the release by tag and fails if it is absent —
# but that is the final step, so a tag pushed without a release would
# build an APK for several minutes first and only then find it has
# nowhere to put it. Same check, seconds in instead of minutes.
#
# Releases are normally created through the API (which creates the tag and
# the release together, so this passes). A bare `git push origin vX` is the
# case this catches.
- name: Release must exist for this tag
if: startsWith(github.ref, 'refs/tags/v')
shell: bash
working-directory: ${{ github.workspace }}
env:
CI_TOKEN: ${{ secrets.CI_TOKEN }}
run: |
set -euo pipefail
TAG="${GITHUB_REF#refs/tags/}"
if ! curl -fsSL -o /dev/null \
-H "Authorization: token ${CI_TOKEN}" \
"https://git.fabledsword.com/api/v1/repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}"; then
echo "::error::no release exists for ${TAG}. Create the release (which creates the tag) rather than pushing a bare tag — otherwise there is nothing to attach the APK to."
exit 1
fi
echo "::notice::release found for ${TAG}"
- name: Cache Gradle dirs - name: Cache Gradle dirs
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
@@ -573,104 +583,26 @@ jobs:
# artifact existing, so an empty upload must fail here, not there. # artifact existing, so an empty upload must fail here, not there.
if-no-files-found: error if-no-files-found: error
# Publishes the signed APK and its version sidecar on the tag's Release. # The image, and on main the public release.
# Split out of android-release so the APK can be BUILT in parallel with the #
# lanes while being PUBLISHED only once they have all passed. # Every push builds its image FROM THE EXPORT, `git archive` of this commit,
release-assets: # and runs the changelog and the leak gate on it first. So a dev push is the
name: Attach APK to the Release (tag releases only) # public release's dry run: an export that leaks or does not build is red the
needs: [go, integration, web, android, govulncheck, android-release] # day it lands, not at the merge.
if: >- #
${{ # A push to main is also the PUBLIC release, after the private push:
!cancelled() # 1. the export becomes one commit on github.com/Fabled-Sword/minstrel's
&& needs.go.result == 'success' # main, tagged v<name>, authored by AmateurDungeoneer and dated in UTC;
&& needs.integration.result == 'success' # 2. that tree is built into ghcr.io/fabled-sword/minstrel :<name> and
&& needs.web.result == 'success' # :latest, labelled with the public repository and commit;
&& needs.android.result == 'success' # 3. a GitHub Release with the public changelog, and a release on this forge
&& needs.govulncheck.result == 'success' # with the private one, both v<name>, both naming the image.
&& needs.android-release.result == 'success' # <name> is YYYY.MM.DD.HHMM from the merge commit's time.
&& startsWith(github.ref, 'refs/tags/v') }}
runs-on: go-ci
container:
image: git.fabledsword.com/bvandeusen/ci-go:1.26
steps:
- name: Download signed APK artifact
uses: actions/download-artifact@v8
with:
name: minstrel-apk
path: release-apk/
- name: Attach APK to gitea Release
# Tag releases only. A dev build has no Release to hang assets on and
# does not need one — the :dev image bundles the APK, and the server
# serves it from /api/client/apk like any other.
shell: bash
env:
CI_TOKEN: ${{ secrets.CI_TOKEN }}
VERSION_NAME: ${{ needs.android-release.outputs.version_name }}
VERSION_CODE: ${{ needs.android-release.outputs.version_code }}
run: |
set -euxo pipefail
TAG="${GITHUB_REF#refs/tags/}"
REPO="${GITHUB_REPOSITORY}"
APK_PATH="release-apk/app-release.apk"
ls -lh "${APK_PATH}"
# Publish the version sidecar as a release asset next to the APK.
#
# This is what lets a later :latest build stop RECONSTRUCTING the
# bundled APK's version and simply read what was recorded. The
# ordering key in particular cannot be re-derived after the fact —
# it is build-time minutes, so once this job ends the value exists
# nowhere else. Reconstruction could only ever recover the name,
# and only by duplicating a formula that then has to be kept in
# step across two files.
SIDECAR_PATH="/tmp/minstrel.apk.version"
printf '{"name":"%s","code":%s,"channel":"stable"}\n' \
"${VERSION_NAME}" "${VERSION_CODE}" > "${SIDECAR_PATH}"
cat "${SIDECAR_PATH}"
RELEASE_JSON="$(curl -fsSL \
-H "Authorization: token ${CI_TOKEN}" \
"https://git.fabledsword.com/api/v1/repos/${REPO}/releases/tags/${TAG}")"
RELEASE_ID="$(printf '%s' "${RELEASE_JSON}" | grep -oP '"id":\s*\K[0-9]+' | head -1)"
if [ -z "${RELEASE_ID}" ]; then
echo "::error::release for ${TAG} not found"; exit 1
fi
echo "release_id=${RELEASE_ID}"
UPLOAD_HTTP=$(curl -sS -L -o /tmp/upload.out -w '%{http_code}' \
-H "Authorization: token ${CI_TOKEN}" \
-F "attachment=@${APK_PATH}" \
"https://git.fabledsword.com/api/v1/repos/${REPO}/releases/${RELEASE_ID}/assets?name=minstrel-${TAG}.apk")
echo "upload_http=${UPLOAD_HTTP}"
cat /tmp/upload.out || true
echo
if [ "${UPLOAD_HTTP}" -lt 200 ] || [ "${UPLOAD_HTTP}" -ge 300 ]; then
echo "::error::APK upload returned HTTP ${UPLOAD_HTTP}"
exit 1
fi
# Same treatment for the sidecar. Named `.apk.version` so the
# downloader's `\.apk$` match cannot pick it up by mistake.
SIDECAR_HTTP=$(curl -sS -L -o /tmp/upload-sidecar.out -w '%{http_code}' \
-H "Authorization: token ${CI_TOKEN}" \
-F "attachment=@${SIDECAR_PATH}" \
"https://git.fabledsword.com/api/v1/repos/${REPO}/releases/${RELEASE_ID}/assets?name=minstrel-${TAG}.apk.version")
echo "sidecar_upload_http=${SIDECAR_HTTP}"
cat /tmp/upload-sidecar.out || true
echo
if [ "${SIDECAR_HTTP}" -lt 200 ] || [ "${SIDECAR_HTTP}" -ge 300 ]; then
echo "::error::version sidecar upload returned HTTP ${SIDECAR_HTTP}"
exit 1
fi
image-release: image-release:
name: Build + push container image name: Build + push container image
# Every lane must have SUCCEEDED, each named here. Then the # Every lane must have SUCCEEDED, each named here, and so must the APK
# APK: tag and dev pushes build one and it must have succeeded; main # build: every ref bundles the APK built from its own commit, so an
# pushes skip android-release and bundle the latest release's APK # image without one would move a channel with no app for phones to take.
# instead, so for main alone a skipped android-release is expected.
needs: [go, integration, web, android, govulncheck, android-release] needs: [go, integration, web, android, govulncheck, android-release]
if: >- if: >-
${{ ${{
@@ -680,42 +612,29 @@ jobs:
&& needs.web.result == 'success' && needs.web.result == 'success'
&& needs.android.result == 'success' && needs.android.result == 'success'
&& needs.govulncheck.result == 'success' && needs.govulncheck.result == 'success'
&& (needs.android-release.result == 'success' && needs.android-release.result == 'success' }}
|| (needs.android-release.result == 'skipped' && github.ref == 'refs/heads/main')) }}
runs-on: go-ci runs-on: go-ci
container: container:
image: git.fabledsword.com/bvandeusen/ci-go:1.26 image: git.fabledsword.com/bvandeusen/ci-go:1.26
env: env:
IMAGE: git.fabledsword.com/bvandeusen/minstrel IMAGE: git.fabledsword.com/bvandeusen/minstrel
PUBLIC_REPO: Fabled-Sword/minstrel
PUBLIC_IMAGE: ghcr.io/fabled-sword/minstrel
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
with: with:
# Full history: any job that DERIVES the version name needs it, # Full history and its tags: any job that DERIVES the version name
# because a shallow clone changes what git-derived values resolve to # needs it, because a shallow clone changes what git-derived values
# WITHOUT failing — a too-low value, silently, with every lane green. # resolve to WITHOUT failing — a too-low value, silently, with every
# # lane green. The changelog lists the commits since the previous
# This job runs ci/version.sh itself: with no :<version> image tags, # release's tag, so it needs them too.
# the server's self-reported version is the only thing that says which
# build an image is.
fetch-depth: 0 fetch-depth: 0
- name: Detect buildable project
id: guard
shell: bash
run: |
if [ -f Dockerfile ] && [ -f go.mod ]; then
echo "ready=true" >> "$GITHUB_OUTPUT"
else
echo "ready=false" >> "$GITHUB_OUTPUT"
echo "::notice::No Dockerfile + go.mod yet — release build skipped"
fi
- name: Compute image tags - name: Compute image tags
id: tags id: tags
if: steps.guard.outputs.ready == 'true'
shell: bash shell: bash
run: | run: |
set -euo pipefail set -euo pipefail
@@ -723,10 +642,10 @@ jobs:
# THE VERSION, and it is derived the same way on every ref — the # THE VERSION, and it is derived the same way on every ref — the
# branch decides the CHANNEL, never the version. # branch decides the CHANNEL, never the version.
# #
# A per-ref string ("main", "dev", the tag name) would not order, and # A per-ref string ("main", "dev") would not order, and "dev" would be
# "dev" would be the same string forever — two dev images eight weeks # the same string forever — two dev images eight weeks apart
# apart indistinguishable in the UI. With no version image tags, this # indistinguishable in the UI. The server's self-reported version is
# is how an admin tells which build a container is running. # how an admin tells which build a private image is.
# #
# `sed -n s///p` rather than `grep`: it exits 0 when nothing matches, # `sed -n s///p` rather than `grep`: it exits 0 when nothing matches,
# so the empty check below is actually reachable. A grep here would # so the empty check below is actually reachable. A grep here would
@@ -737,23 +656,7 @@ jobs:
exit 1 exit 1
fi fi
if [[ "${GITHUB_REF}" == refs/tags/v* ]]; then if [[ "${GITHUB_REF}" == "refs/heads/dev" ]]; then
# A release refreshes the CHANNEL and mints nothing else.
#
# The tag build exists to produce the signed APK and attach it to
# the release; the image it rebuilds is the SAME SOURCE as the main
# build minutes earlier, differing only in which APK is baked in.
# When the same source is rebuilt with different contents,
# publish the moving channel tag and never a commit-addressable
# one.
#
# :latest must move here rather than waiting for the next main
# push, or the channel would carry the PREVIOUS release's APK
# indefinitely — a channel that cannot refresh itself.
CHANNEL=stable
echo "args=-t ${IMAGE}:latest" >> "$GITHUB_OUTPUT"
echo "::notice::Release build ${VERSION}: refreshing :latest around the new APK"
elif [[ "${GITHUB_REF}" == "refs/heads/dev" ]]; then
# The rolling test channel, and :dev ALONE — deliberately no # The rolling test channel, and :dev ALONE — deliberately no
# per-commit tag. A rolling channel is rolling by definition, so a # per-commit tag. A rolling channel is rolling by definition, so a
# commit-addressable image here would be a rollback target nobody # commit-addressable image here would be a rollback target nobody
@@ -774,20 +677,79 @@ jobs:
echo "version=${VERSION}" >> "$GITHUB_OUTPUT" echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
echo "channel=${CHANNEL}" >> "$GITHUB_OUTPUT" echo "channel=${CHANNEL}" >> "$GITHUB_OUTPUT"
# The public release's name, and whether this run makes the release.
# Only a PUSH to main does: a dispatch on main rebuilds the private
# channel and publishes nothing outside this forge.
{
echo "EXPORT=${RUNNER_TEMP}/export"
echo "NAME=$(date -u -d "@$(git log -1 --format=%ct HEAD)" +%Y.%m.%d.%H%M)"
if [ "${GITHUB_EVENT_NAME}" = "push" ] && [ "${GITHUB_REF}" = "refs/heads/main" ]; then
echo "PUBLIC=true"
else
echo "PUBLIC=false"
fi
} >> "$GITHUB_ENV"
# What a release would publish: the export, and its changelog. Neither
# may carry a banned word or a private record id (ci/leakgate.sh), and the
# export carries no CI file.
- name: Export, changelog and leak gate
shell: bash
run: |
set -euo pipefail
rm -rf "${EXPORT}"
mkdir -p "${EXPORT}"
git archive HEAD | tar -x -C "${EXPORT}"
for private in .gitea .forgejo .github ci ci-requirements.md .gitattributes renovate.json; do
if [ -e "${EXPORT}/${private}" ]; then
echo "::error::the export carries ${private}; .gitattributes export-ignore no longer covers it"
exit 1
fi
done
bash ci/changelog.sh "${RUNNER_TEMP}/changelog"
echo "--- the public changelog of v${NAME} ---"
cat "${RUNNER_TEMP}/changelog/public.md"
echo "---"
bash ci/leakgate.sh "${EXPORT}" "${RUNNER_TEMP}/changelog/public.md"
# The secrets the public half needs, checked before anything is pushed
# anywhere. A dev push warns about one that is missing or refused; a main
# push stops. Nothing here writes: the push token reads the public
# repository, and the forge token updates a release that does not exist.
- name: Public release secrets
shell: bash
env:
PUBLIC_PUSH_TOKEN: ${{ secrets.PUBLIC_PUSH_TOKEN }}
GHCR_USER: ${{ vars.GHCR_USER || secrets.GHCR_USER }}
GHCR_TOKEN: ${{ secrets.GHCR_TOKEN }}
FORGE_TOKEN: ${{ secrets.CI_TOKEN }}
run: |
set -u
bad=""
say() { bad="yes"; if [ "${PUBLIC}" = "true" ]; then echo "::error::$1"; else echo "::warning::$1"; fi; }
[ -n "${GHCR_USER}" ] || say "GHCR_USER is empty or unset (an Actions variable or secret)"
[ -n "${GHCR_TOKEN}" ] || say "the GHCR_TOKEN secret is empty or unset"
if [ -z "${PUBLIC_PUSH_TOKEN}" ]; then
say "the PUBLIC_PUSH_TOKEN secret is empty or unset"
else
auth="$(printf 'x-access-token:%s' "${PUBLIC_PUSH_TOKEN}" | base64 -w0)"
echo "::add-mask::${auth}"
git -c http.https://github.com/.extraheader="AUTHORIZATION: basic ${auth}" \
ls-remote "https://github.com/${PUBLIC_REPO}.git" >/dev/null \
|| say "PUBLIC_PUSH_TOKEN cannot read github.com/${PUBLIC_REPO}"
fi
node ci/releases.mjs forge-probe || say "CI_TOKEN may not write this repository's releases"
if [ -n "${bad}" ] && [ "${PUBLIC}" = "true" ]; then exit 1; fi
exit 0
- name: Registry login - name: Registry login
if: steps.guard.outputs.ready == 'true'
shell: bash shell: bash
run: | run: |
echo "${{ secrets.CI_TOKEN }}" \ echo "${{ secrets.CI_TOKEN }}" \
| docker login git.fabledsword.com -u "${{ github.actor }}" --password-stdin | docker login git.fabledsword.com -u "${{ github.actor }}" --password-stdin
- name: Download signed APK artifact - name: Download signed APK artifact
# Tag and dev pushes — android-release just produced this. Only `main` # android-release just produced this, on every ref.
# takes the "Bundle latest release APK" path below, because it is the
# one ref that moves a channel without building an APK of its own.
if: >-
steps.guard.outputs.ready == 'true' &&
(startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/dev')
# Consuming half of the pair: stock download-artifact, which works here for # Consuming half of the pair: stock download-artifact, which works here for
# the same reason as the upload (gitea/runner 3.x edits the GHES refusal # the same reason as the upload (gitea/runner 3.x edits the GHES refusal
# out of the bundle). v8 runs on node24, which every CI-runner image # out of the bundle). v8 runs on node24, which every CI-runner image
@@ -797,10 +759,8 @@ jobs:
name: minstrel-apk name: minstrel-apk
path: client/ path: client/
# Into the export, which is what the image is built from.
- name: Stage bundled APK + version sidecar - name: Stage bundled APK + version sidecar
if: >-
steps.guard.outputs.ready == 'true' &&
(startsWith(github.ref, 'refs/tags/v') || github.ref == 'refs/heads/dev')
shell: bash shell: bash
env: env:
# All three pulled from android-release's outputs so the sidecar the # All three pulled from android-release's outputs so the sidecar the
@@ -814,74 +774,15 @@ jobs:
# The artifact lands as `app-release.apk` (the original Gradle # The artifact lands as `app-release.apk` (the original Gradle
# output name). The Dockerfile COPYs client/* into /app/client/ # output name). The Dockerfile COPYs client/* into /app/client/
# and the server reads minstrel.apk + minstrel.apk.version. # and the server reads minstrel.apk + minstrel.apk.version.
mv client/app-release.apk client/minstrel.apk mv client/app-release.apk "${EXPORT}/client/minstrel.apk"
printf '{"name":"%s","code":%s,"channel":"%s"}\n' \ printf '{"name":"%s","code":%s,"channel":"%s"}\n' \
"${APK_VERSION_NAME}" "${APK_VERSION_CODE}" "${APK_CHANNEL}" \ "${APK_VERSION_NAME}" "${APK_VERSION_CODE}" "${APK_CHANNEL}" \
> client/minstrel.apk.version > "${EXPORT}/client/minstrel.apk.version"
cat client/minstrel.apk.version cat "${EXPORT}/client/minstrel.apk.version"
ls -lh client/ ls -lh "${EXPORT}/client/"
- name: Bundle latest release APK (non-tag :latest builds)
# Main pushes don't build an APK, but they DO move :latest — so
# without this the in-app update channel would vanish from :latest
# until the next tag. Pull the most-recent release's signed APK and
# the sidecar published beside it, so what the server reports is what
# that build actually recorded rather than something re-derived here.
# Degrades to an empty client/ (404 update channel) — never a wrong
# version — if no release or APK asset can be resolved. That
# degradation only actually works because the greps below carry
# `|| true`; under the runner's default pipefail a non-matching grep
# kills the step instead of falling through to the empty-case branch.
if: steps.guard.outputs.ready == 'true' && github.ref == 'refs/heads/main'
shell: bash
env:
CI_TOKEN: ${{ secrets.CI_TOKEN }}
run: |
set -eu
REPO="${GITHUB_REPOSITORY}"
REL_JSON="$(curl -fsSL -H "Authorization: token ${CI_TOKEN}" \
"https://git.fabledsword.com/api/v1/repos/${REPO}/releases/latest" || true)"
if [ -z "${REL_JSON}" ]; then
echo "::notice::no published release — image ships without bundled APK"; exit 0
fi
# `|| true` on every one of these, and it is load-bearing rather
# than defensive habit. The runner already invokes this shell as
# `bash -e -o pipefail`, so a pipeline whose grep matches NOTHING
# exits non-zero even though `head` succeeded — and the step dies at
# the assignment, before ever reaching the `if` written to handle the
# empty case. Every "degrades gracefully" branch below is unreachable
# without this.
TAG="$(printf '%s' "${REL_JSON}" | grep -oP '"tag_name":\s*"\K[^"]+' | head -1)" || true
APK_URL="$(printf '%s' "${REL_JSON}" | grep -oP '"browser_download_url":\s*"\K[^"]+' | grep -E '\.apk$' | head -1)" || true
if [ -z "${TAG}" ] || [ -z "${APK_URL}" ]; then
echo "::notice::latest release '${TAG:-?}' has no APK asset — image ships without bundled APK"; exit 0
fi
curl -fsSL -H "Authorization: token ${CI_TOKEN}" -o client/minstrel.apk "${APK_URL}"
# Take the version the release RECORDED rather than recomputing it.
# Re-deriving it from the tagged commit would keep the formula in two
# files that must stay in step, and could only ever recover the name —
# the ordering key is build-time minutes and exists nowhere after that
# build ends.
SIDECAR_URL="$(printf '%s' "${REL_JSON}" | grep -oP '"browser_download_url":\s*"\K[^"]+' | grep -E '\.apk\.version$' | head -1)" || true
if [ -n "${SIDECAR_URL}" ]; then
curl -fsSL -H "Authorization: token ${CI_TOKEN}" -o client/minstrel.apk.version "${SIDECAR_URL}"
cat client/minstrel.apk.version
else
# Releases published before sidecars were attached. Their name is
# still recoverable from the tag, but their ordering key genuinely
# is not — so it is reported ABSENT rather than guessed. A wrong
# key is an install the platform refuses; an absent one just tells
# the client to fall back to comparing names, which is exactly
# what those builds already do.
echo "::notice::release ${TAG} predates the version sidecar — bundling with name only, no ordering key"
printf '{"name":"%s","code":null,"channel":"stable"}\n' "${TAG#v}" > client/minstrel.apk.version
fi
echo "::notice::bundled release APK from ${TAG}"
ls -lh client/
- name: Build and push - name: Build and push
if: steps.guard.outputs.ready == 'true' shell: bash
# --pull: the Dockerfile's base images are floating tags (golang:1.26, # --pull: the Dockerfile's base images are floating tags (golang:1.26,
# debian:bookworm-slim). Without it the runner's daemon reuses # debian:bookworm-slim). Without it the runner's daemon reuses
# whatever it cached, and the shipped binary can sit on a Go patch # whatever it cached, and the shipped binary can sit on a Go patch
@@ -891,83 +792,127 @@ jobs:
docker buildx build --pull \ docker buildx build --pull \
--build-arg MINSTREL_VERSION="${{ steps.tags.outputs.version }}" \ --build-arg MINSTREL_VERSION="${{ steps.tags.outputs.version }}" \
--build-arg MINSTREL_CHANNEL="${{ steps.tags.outputs.channel }}" \ --build-arg MINSTREL_CHANNEL="${{ steps.tags.outputs.channel }}" \
--push ${{ steps.tags.outputs.args }} . --push ${{ steps.tags.outputs.args }} "${EXPORT}"
# Verifies a tag release actually ended up complete, and names the specific # THE PUBLIC RELEASE, a push to main only. The export becomes one commit
# thing that's missing if not. # on the public repository's main, replacing its whole tree so removed
# # files go too, tagged v<name>. Author, committer and tagger are the
# A release can be incomplete while looking fine. If android-release never # project's public identity, dated at this commit's time in UTC.
# starts (a runner failing to launch), its steps all report `failure` with #
# none executed and image-release shows `skipped`. The run is red, but the # A re-run finds v<name> already there: on the same tree it goes on to the
# release page renders and main's own push build has already moved # image and the releases, on a different tree it stops. A published tag
# `:latest`, so a release missing its APK and its image is easy to skim # is never moved.
# past. - name: Public commit and tag
# if: env.PUBLIC == 'true'
# This job cannot prevent that; it turns an incomplete release into an
# explicit, named error instead of a row of mystery step failures.
#
# `if: always()` is the whole point: it has to report precisely when the jobs
# above did NOT succeed.
verify-release:
name: Verify release artifacts (tag releases only)
needs: [android-release, release-assets, image-release]
if: ${{ always() && startsWith(github.ref, 'refs/tags/v') }}
runs-on: go-ci
container:
image: git.fabledsword.com/bvandeusen/ci-go:1.26
steps:
- name: Release must have an APK attached
shell: bash shell: bash
env: env:
CI_TOKEN: ${{ secrets.CI_TOKEN }} PUBLIC_PUSH_TOKEN: ${{ secrets.PUBLIC_PUSH_TOKEN }}
run: | run: |
set -euo pipefail set -euo pipefail
TAG="${GITHUB_REF#refs/tags/}" auth="$(printf 'x-access-token:%s' "${PUBLIC_PUSH_TOKEN}" | base64 -w0)"
REPO="${GITHUB_REPOSITORY}" echo "::add-mask::${auth}"
pub="${RUNNER_TEMP}/public"
REL_JSON="$(curl -fsSL \ rm -rf "${pub}"
-H "Authorization: token ${CI_TOKEN}" \ git init -q -b main "${pub}"
"https://git.fabledsword.com/api/v1/repos/${REPO}/releases/tags/${TAG}" || true)" cd "${pub}"
if [ -z "${REL_JSON}" ]; then git config http.https://github.com/.extraheader "AUTHORIZATION: basic ${auth}"
echo "::error::no release found for ${TAG} — the tag exists but nothing was published" git remote add origin "https://github.com/${PUBLIC_REPO}.git"
exit 1 # An empty repository has no main yet, and its first release starts it.
if [ -n "$(git ls-remote --heads origin main)" ]; then
git fetch -q --depth 1 origin main
git checkout -q -B main FETCH_HEAD
fi fi
find . -mindepth 1 -maxdepth 1 ! -name .git -exec rm -rf {} +
APK="$(printf '%s' "${REL_JSON}" \ # A fresh archive, not the build context, which also holds the app.
| grep -oP '"browser_download_url":\s*"\K[^"]+' \ git -C "${GITHUB_WORKSPACE}" archive HEAD | tar -xf -
| grep -E '\.apk$' | head -1 || true)" # -f: the export exactly, a tracked file a .gitignore matches
if [ -z "${APK}" ]; then # (the generated token CSS) included.
echo "::error::release ${TAG} has NO APK attached — in-app update will offer nothing, and the bundled-APK path on future :latest builds has no source." git add -A -f
echo "::error::Fix by RE-RUNNING this workflow run. Do NOT delete and re-create the tag; if it fails again the runner never started the container, and the evidence is in act_runner on the host (Gitea will hold no job log)." tree="$(git write-tree)"
exit 1 when="@$(git -C "${GITHUB_WORKSPACE}" log -1 --format=%ct HEAD) +0000"
if [ -n "$(git ls-remote --tags origin "refs/tags/v${NAME}")" ]; then
git fetch -q --depth 1 origin "refs/tags/v${NAME}:refs/tags/v${NAME}"
if [ "$(git rev-parse "v${NAME}^{tree}")" != "${tree}" ]; then
echo "::error::the public tag v${NAME} holds another tree; a published tag is never moved"
exit 1
fi
echo "::notice::v${NAME} is already published with this tree"
else
export GIT_AUTHOR_NAME=AmateurDungeoneer GIT_AUTHOR_EMAIL=amateurdungeoneer@fabledsword.com
export GIT_COMMITTER_NAME=AmateurDungeoneer GIT_COMMITTER_EMAIL=amateurdungeoneer@fabledsword.com
export GIT_AUTHOR_DATE="${when}" GIT_COMMITTER_DATE="${when}"
git commit -q -m "Release ${NAME}"
git tag -a "v${NAME}" -m "Release ${NAME}"
git push -q origin main "refs/tags/v${NAME}"
fi fi
echo "REVISION=$(git rev-parse "v${NAME}^{commit}")" >> "$GITHUB_ENV"
echo "::notice::APK attached: ${APK}" # The same export, built again with the release's name and labels that
# point at the public repository and commit, so nothing in the image
# points back here. Every layer but the stamped binary comes from the
# build above. --provenance=false and no SBOM: an attestation would carry
# this workbench's build details into a public registry.
- name: Public image
if: env.PUBLIC == 'true'
shell: bash
env:
GHCR_USER: ${{ vars.GHCR_USER || secrets.GHCR_USER }}
GHCR_TOKEN: ${{ secrets.GHCR_TOKEN }}
run: |
set -euo pipefail
docker build --provenance=false \
--build-arg MINSTREL_VERSION="${NAME}" \
--build-arg MINSTREL_CHANNEL=stable \
--label "org.opencontainers.image.source=https://github.com/${PUBLIC_REPO}" \
--label "org.opencontainers.image.revision=${REVISION}" \
--label "org.opencontainers.image.version=${NAME}" \
-t "${PUBLIC_IMAGE}:${NAME}" "${EXPORT}"
labelled="$(docker inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' "${PUBLIC_IMAGE}:${NAME}")"
test "${labelled}" = "${REVISION}" || { echo "::error::the image names commit ${labelled}, not ${REVISION}"; exit 1; }
printf '%s' "${GHCR_TOKEN}" | docker login ghcr.io -u "${GHCR_USER}" --password-stdin
# :<name> is never re-pushed, so a re-run only moves :latest.
if docker manifest inspect "${PUBLIC_IMAGE}:${NAME}" >/dev/null 2>&1; then
echo "::notice::${PUBLIC_IMAGE}:${NAME} is already published; only :latest moves"
else
docker push "${PUBLIC_IMAGE}:${NAME}"
fi
docker tag "${PUBLIC_IMAGE}:${NAME}" "${PUBLIC_IMAGE}:latest"
docker push "${PUBLIC_IMAGE}:latest"
echo "DIGEST=$(docker inspect --format '{{ index .RepoDigests 0 }}' "${PUBLIC_IMAGE}:${NAME}")" >> "$GITHUB_ENV"
# The other half. Checking only the APK would report success on a release # The release pages, each created or updated in place: GitHub's with the
# whose image push failed. `always()` on this job means it runs even when # public changelog, this forge's with the private one, tagging this
# image-release failed, so without this the guard would cheerfully verify # commit. Both name the image. No files are attached: the app ships
# an incomplete release. # inside the image.
# - name: Public and private releases
# The image checked is the :<sha> rollback target, which main's own build if: env.PUBLIC == 'true'
# published for this same commit before the tag was cut (there are no shell: bash
# version image tags). It catches an image push that silently did not env:
# happen, and it proves the ORDERING — a tag cut on a commit whose main PUBLIC_PUSH_TOKEN: ${{ secrets.PUBLIC_PUSH_TOKEN }}
# build never completed has no rollback target, and that is worth failing FORGE_TOKEN: ${{ secrets.CI_TOKEN }}
# on rather than discovering during an incident. run: |
- name: Rollback image must exist for the tagged commit set -euo pipefail
cl="${RUNNER_TEMP}/changelog"
for side in public private; do
{
cat "${cl}/${side}.md"
printf '\nImage: `%s:%s`\n' "${PUBLIC_IMAGE}" "${NAME}"
} > "${cl}/${side}-body.md"
done
echo "GITHUB_RELEASE=$(node ci/releases.mjs github "v${NAME}" "${cl}/public-body.md")" >> "$GITHUB_ENV"
echo "FORGE_RELEASE=$(node ci/releases.mjs forge "v${NAME}" "${cl}/private-body.md" "${GITHUB_SHA}")" >> "$GITHUB_ENV"
# The record the release task keeps.
- name: Published
shell: bash shell: bash
run: | run: |
set -euo pipefail echo "pushed ${{ steps.tags.outputs.args }}"
IMAGE="git.fabledsword.com/bvandeusen/minstrel" if [ "${PUBLIC}" = "true" ]; then
echo "release v${NAME} of workbench ${GITHUB_SHA}"
echo "${{ secrets.CI_TOKEN }}" \ echo "public commit ${REVISION}"
| docker login git.fabledsword.com -u "${{ github.actor }}" --password-stdin echo "image ${DIGEST}"
echo "GitHub release ${GITHUB_RELEASE}"
if ! docker manifest inspect "${IMAGE}:${GITHUB_SHA}" > /dev/null 2>&1; then echo "forge release ${FORGE_RELEASE}"
echo "::error::image ${IMAGE}:${GITHUB_SHA} does not exist — this commit has no rollback target." else
echo "::error::That image is published by the MAIN build of this commit, not by the tag build. If main's build never ran or failed, fix that first; a release whose commit cannot be rolled back to is the thing this check exists to refuse." echo "dry run of release v${NAME}: export, changelog and leak gate passed, image built from the export"
exit 1
fi fi
echo "::notice::rollback target verified: ${IMAGE}:${GITHUB_SHA}"
+5 -5
View File
@@ -54,7 +54,7 @@ GEMINI.md
.windsurfrules .windsurfrules
.aider.conf.yml .aider.conf.yml
# Native Android (Kotlin/Compose) — M8 rewrite # Native Android (Kotlin/Compose)
android/.gradle/ android/.gradle/
android/.kotlin/ android/.kotlin/
android/.idea/ android/.idea/
@@ -63,11 +63,11 @@ android/app/build/
android/local.properties android/local.properties
android/*.iml android/*.iml
android/app/*.iml android/app/*.iml
# Release signing material — keystore + extracted credentials live local # Release signing material: a keystore never belongs in the repo.
# only; the canonical copy is the Gitea repo secret (ANDROID_KEYSTORE_B64
# + the alias/password secrets). Losing the local file is fine; losing
# the secret means rebuilding the keystore + reinstalling all clients.
android/*.keystore android/*.keystore
android/*.keystore.* android/*.keystore.*
android/*.jks android/*.jks
android/keystore.properties android/keystore.properties
# Python bytecode from the tools/ scripts
__pycache__/
+5 -6
View File
@@ -15,7 +15,7 @@ COPY . .
# Overwrite the committed placeholder with the freshly-built SPA assets. # Overwrite the committed placeholder with the freshly-built SPA assets.
COPY --from=web /web/build ./web/build COPY --from=web /web/build ./web/build
ENV CGO_ENABLED=0 ENV CGO_ENABLED=0
# Version stamping. release.yml passes the DERIVED version name # Version stamping. The release build passes the DERIVED version name
# (YYYY.MM.DD.HHMM) and the lane's channel; a local `docker build` falls back # (YYYY.MM.DD.HHMM) and the lane's channel; a local `docker build` falls back
# to "dev"/"local". Both are surfaced at /healthz. # to "dev"/"local". Both are surfaced at /healthz.
# #
@@ -27,8 +27,8 @@ ARG MINSTREL_VERSION=dev
ARG MINSTREL_CHANNEL=local ARG MINSTREL_CHANNEL=local
RUN go build -trimpath \ RUN go build -trimpath \
-ldflags="-s -w \ -ldflags="-s -w \
-X 'git.fabledsword.com/bvandeusen/minstrel/internal/buildinfo.Version=${MINSTREL_VERSION}' \ -X 'github.com/Fabled-Sword/minstrel/internal/buildinfo.Version=${MINSTREL_VERSION}' \
-X 'git.fabledsword.com/bvandeusen/minstrel/internal/buildinfo.Channel=${MINSTREL_CHANNEL}'" \ -X 'github.com/Fabled-Sword/minstrel/internal/buildinfo.Channel=${MINSTREL_CHANNEL}'" \
-o /out/minstrel ./cmd/minstrel -o /out/minstrel ./cmd/minstrel
FROM debian:bookworm-slim FROM debian:bookworm-slim
@@ -57,9 +57,8 @@ RUN mkdir -p /app/data /app/client && chown -R minstrel:minstrel /app
WORKDIR /app WORKDIR /app
# In-app update channel. client/ in the build context holds # In-app update channel. client/ in the build context holds
# minstrel.apk + minstrel.apk.version, which release.yml fills on every # minstrel.apk + minstrel.apk.version, which the release build fills; a
# build (dev and tag pushes bundle their own APK, main bundles the latest # local build has only .gitkeep + README. Endpoints return
# release's); a local build has only .gitkeep + README. Endpoints return
# 404 when the APK files aren't present, so such an image degrades # 404 when the APK files aren't present, so such an image degrades
# gracefully. # gracefully.
COPY --chown=minstrel:minstrel client/ /app/client/ COPY --chown=minstrel:minstrel client/ /app/client/
+657 -5
View File
@@ -1,9 +1,661 @@
MIT License GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (c) 2026 bvandeusen Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: Preamble
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+6 -5
View File
@@ -7,8 +7,8 @@ SQLC_VERSION := 1.31.1
generate: generate:
docker run --rm -v "$(CURDIR):/src" -w /src sqlc/sqlc:$(SQLC_VERSION) generate docker run --rm -v "$(CURDIR):/src" -w /src sqlc/sqlc:$(SQLC_VERSION) generate
# Same codegen, run as a Go tool instead of a container. This is the CI path: # Same codegen, run as a Go tool instead of a container, for a machine that
# the ci-go image already has Go, so it avoids docker-in-docker. Pinned to the # has Go but no Docker. Pinned to the
# SAME version as `generate` above so both routes emit identical output. # SAME version as `generate` above so both routes emit identical output.
generate-go: generate-go:
go run github.com/sqlc-dev/sqlc/cmd/sqlc@v$(SQLC_VERSION) generate go run github.com/sqlc-dev/sqlc/cmd/sqlc@v$(SQLC_VERSION) generate
@@ -38,9 +38,10 @@ test-short:
test-integration: test-integration:
docker compose up -d postgres docker compose up -d postgres
-docker compose exec -T postgres createdb -U minstrel minstrel_test -docker compose exec -T postgres createdb -U minstrel minstrel_test
# -p 1: integration packages share one test DB and each TRUNCATEs it; # Only packages with database tests; test-short covers the rest.
# concurrent package binaries deadlock on TRUNCATE. Serialize packages. # -p 1: they share one test DB and each TRUNCATEs it; concurrent
MINSTREL_TEST_DATABASE_URL=postgres://minstrel:minstrel@localhost:5432/minstrel_test?sslmode=disable go test -p 1 -race ./... # package binaries deadlock on TRUNCATE. Serialize packages.
MINSTREL_TEST_DATABASE_URL=postgres://minstrel:minstrel@localhost:5432/minstrel_test?sslmode=disable go test -p 1 -race $$(sh ci/db-test-packages.sh)
lint: lint:
golangci-lint run ./... golangci-lint run ./...
+29 -28
View File
@@ -1,12 +1,19 @@
<p align="center"><img src="web/static/brand/mark.svg" width="120" alt="Minstrel logo"></p> <p align="center"><img src="web/static/brand/mark.svg" width="120" alt="Fabled Minstrel logo"></p>
<h1 align="center">Minstrel</h1> <h1 align="center">Fabled Minstrel</h1>
<p align="center">A self-hosted music server that picks what to play next.</p> <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. Fabled Minstrel serves your music library to the web, to its own Android app, and to Subsonic apps. Shuffle, radio, likes and play history are worked out on the server, so the web app, the Android app and Subsonic apps get the same mixes and the same history, and what you like and play in a Subsonic app counts too. 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> <a href="docs/screenshots/home.png"><img src="docs/screenshots/home.png" width="820" alt="Minstrel's Home: daily mixes, Songs like, and genre mixes ordered by what you play most"></a>
<p>
<a href="docs/screenshots/now-playing.png"><img src="docs/screenshots/now-playing.png" width="560" alt="Now playing, with the queue beside it"></a>
<a href="docs/screenshots/home-phone.png"><img src="docs/screenshots/home-phone.png" width="200" alt="Home on a phone"></a>
</p>
<sub>The music in these screenshots is invented: every artist, album, cover and song was generated for them (<a href="tools/demo-library">tools/demo-library</a>).</sub>
## Quick start ## Quick start
@@ -14,7 +21,7 @@ Minstrel serves your music library to the web, to its own Android app, and to an
# compose.yaml # compose.yaml
services: services:
minstrel: minstrel:
image: git.fabledsword.com/bvandeusen/minstrel:latest image: ghcr.io/fabled-sword/minstrel:latest
ports: ['4533:4533'] ports: ['4533:4533']
volumes: volumes:
- ./music:/music # your library; must be writable by uid 1000 - ./music:/music # your library; must be writable by uid 1000
@@ -48,10 +55,10 @@ 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. 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. 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**.
<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> **On an iPhone** there is no Minstrel app; use a Subsonic app such as play:Sub or Amperfy. Make a password for it in **Settings › Connections › Subsonic apps**, and give the app your server's address, your username and that password. Subsonic apps can browse, search, play, like and scrobble, and make and edit playlists. Minstrel's daily mixes appear in them as playlists, and when an app asks the server for random songs or an instant mix it gets Minstrel's smart shuffle and radio. An app that shuffles on the phone instead shuffles at random.
3. **Invite the household.** In **Admin › Users** (`/admin/users`), make an invite token for each person; an invite is the only way to an account. Each person gets their own likes, history and recommendations.
4. **Optional: connect ListenBrainz.** Each person adds their own ListenBrainz token in **Settings › Connections**.
## Configuration ## Configuration
@@ -64,11 +71,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_BRANDING_APP_NAME` | The name shown in the header, the browser tab and link previews. |
| `MINSTREL_LOG_LEVEL` | `debug`, `info`, `warn` or `error`. | | `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 ## 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 only when an admin asks it to, such as merging duplicates. It never adds, moves, renames or retags files there (album art it finds or fetches is kept in its own data folder), so a tagger or download manager can keep filing into the same folder. 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. - **`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). - **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).
@@ -80,11 +87,10 @@ docker compose pull && docker compose up -d
Database migrations run at startup. Image tags: Database migrations run at startup. Image tags:
- `:latest`: the stable release. Most people should run this. - `:latest`: the newest release. Most people should run this.
- `:<commit-sha>`: one fixed build. Pin one to stop updates, or to roll back. - `:<version>`, such as `:2026.12.04.1530`: one release, which never changes. Pin one to stop updates, or to roll back. The [releases page](https://github.com/Fabled-Sword/minstrel/releases) lists each one with what changed.
- `:dev`: the test channel, rebuilt on every change. It may break, and the fix is the next build.
Every image carries a signed Android app, all with the same key, so a phone can move between channels without reinstalling. Rolling back a SHA tag rolls back the app it carries too. Every image carries a signed Android app, all with the same key, so a phone can move between versions without reinstalling. Rolling back to an older version rolls back the app it carries too.
**Back up the Postgres volume** with `pg_dump`. It holds accounts, likes, play history, playlists and settings, and a migration can only be undone by restoring a dump. The `minstrel-data` volume holds artwork and caches that Minstrel rebuilds if lost. **Back up the Postgres volume** with `pg_dump`. It holds accounts, likes, play history, playlists and settings, and a migration can only be undone by restoring a dump. The `minstrel-data` volume holds artwork and caches that Minstrel rebuilds if lost.
@@ -103,37 +109,32 @@ 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. - 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. - 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** **Clients and accounts**
- A full web app, built into the server. - 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. - 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.
- OpenSubsonic-compatible, so existing clients such as DSub, Symfonium and play:Sub connect as they are. - OpenSubsonic-compatible, so Subsonic apps such as Symfonium, DSub, play:Sub and Amperfy can browse by artist, album, genre or folder, search, play, like and scrobble, carry a play queue from one device to another, show lyrics (from a `.lrc` file beside the song, or the song's own tags), see the daily mixes, make and edit your playlists, and get Minstrel's smart shuffle and radio when they ask for random songs or similar songs.
- Separate accounts for each person, with invites, and an inbox for what happened while you were away. - Separate accounts for each person, with invites, and an inbox for what happened while you were away.
## Scope and responsible use ## 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 or Subsonic.
Minstrel is not affiliated with or endorsed by ListenBrainz, MusicBrainz, Prowlarr, qBittorrent or Subsonic.
## Development ## Development
- **Backend:** `docker compose up` in this repo runs Postgres and Minstrel on `:4533`. - **Backend:** `docker compose up` in this repo runs Postgres and Minstrel on `:4533`.
- **Web:** `cd web && npm install && npm run dev` starts Vite on `:5173`. It proxies `/api/*` and `/rest/*` to `:4533`. - **Web:** `cd web && npm install && npm run dev` starts Vite on `:5173`. It proxies `/api/*` and `/rest/*` to `:4533`.
- **Tests:** `make test-short` runs the unit tests. `make test-integration` also runs the database tests, against a separate `minstrel_test` database so your dev data is never truncated. - **Tests:** `make test-short` runs the unit tests. `make test-integration` runs the database tests, against a separate `minstrel_test` database so your dev data is never truncated.
- **Image:** `docker build -t minstrel .` builds the web app and embeds it in the server binary. - **Image:** `docker build -t minstrel .` builds the web app and embeds it in the server binary.
- **Branches:** work lands on `dev`; `main` changes through pull requests from `dev`. - **Branches:** work lands on `dev`; `main` changes through pull requests from `dev`.
How accounts and sessions are protected: [docs/security.md](docs/security.md). How accounts and sessions are protected, and which outside services Minstrel contacts: [docs/security.md](docs/security.md).
## License ## License
MIT. See [LICENSE](./LICENSE). GNU Affero General Public License v3.0. See [LICENSE](./LICENSE).
You can run, change and share Minstrel freely. If you run a changed copy that other people use over a network, you must offer those people the source of your changes.
-3
View File
@@ -1,3 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
-1
View File
@@ -1 +0,0 @@
Minstrel
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AndroidProjectSystem">
<option name="providerId" value="com.android.tools.idea.GradleProjectSystem" />
</component>
</project>
File diff suppressed because it is too large Load Diff
-123
View File
@@ -1,123 +0,0 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<JetCodeStyleSettings>
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</JetCodeStyleSettings>
<codeStyleSettings language="XML">
<option name="FORCE_REARRANGE_MODE" value="1" />
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
<arrangement>
<rules>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:android</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:id</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>style</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
<order>ANDROID_ATTRIBUTE_ORDER</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>.*</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
</rules>
</arrangement>
</codeStyleSettings>
<codeStyleSettings language="kotlin">
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</codeStyleSettings>
</code_scheme>
</component>
-5
View File
@@ -1,5 +0,0 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="21" />
</component>
</project>
-11
View File
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="deploymentTargetSelector">
<selectionStates>
<SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" />
<DialogSelection />
</SelectionState>
</selectionStates>
</component>
</project>
-13
View File
@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DeviceTable">
<option name="columnSorters">
<list>
<ColumnSorterState>
<option name="column" value="Name" />
<option name="order" value="ASCENDING" />
</ColumnSorterState>
</list>
</option>
</component>
</project>
-19
View File
@@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="CHOOSE_PER_TEST" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="#GRADLE_LOCAL_JAVA_HOME" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>
-10
View File
@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectMigrations">
<option name="MigrateToGradleLocalJavaHome">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</component>
</project>
-9
View File
@@ -1,9 +0,0 @@
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>
-17
View File
@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="com.intellij.execution.junit.AbstractAllInDirectoryConfigurationProducer" />
<option value="com.intellij.execution.junit.AllInPackageConfigurationProducer" />
<option value="com.intellij.execution.junit.PatternConfigurationProducer" />
<option value="com.intellij.execution.junit.TestInClassConfigurationProducer" />
<option value="com.intellij.execution.junit.UniqueIdConfigurationProducer" />
<option value="com.intellij.execution.junit.testDiscovery.JUnitTestDiscoveryConfigurationProducer" />
<option value="org.jetbrains.kotlin.idea.junit.KotlinJUnitRunConfigurationProducer" />
<option value="org.jetbrains.kotlin.idea.junit.KotlinPatternConfigurationProducer" />
</set>
</option>
</component>
</project>
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>
+38
View File
@@ -100,6 +100,42 @@ android {
} }
} }
// The app's error messages are the web app's: web/src/lib/styles holds the
// copy for each server error code (error-copy.json) and the codes whose
// server message is appended (error-detail-codes.json). Both are copied in as
// Java resources, which ErrorCopy reads, so the two clients say the same thing
// and a new code is added once.
abstract class CopySharedCopyTask : DefaultTask() {
@get:InputFiles
@get:PathSensitive(PathSensitivity.NAME_ONLY)
abstract val sources: ConfigurableFileCollection
@get:OutputDirectory
abstract val outputDir: DirectoryProperty
@TaskAction
fun copy() {
val out = outputDir.get().asFile
out.deleteRecursively()
out.mkdirs()
sources.forEach { it.copyTo(File(out, it.name), overwrite = true) }
}
}
val copySharedCopy =
tasks.register<CopySharedCopyTask>("copySharedCopy") {
sources.from(
rootProject.file("../web/src/lib/styles/error-copy.json"),
rootProject.file("../web/src/lib/styles/error-detail-codes.json"),
)
}
androidComponents {
onVariants { variant ->
variant.sources.resources?.addGeneratedSourceDirectory(copySharedCopy, CopySharedCopyTask::outputDir)
}
}
// Kotlin 2.x: `kotlinOptions { ... }` inside `android { }` is gone; the // Kotlin 2.x: `kotlinOptions { ... }` inside `android { }` is gone; the
// modern shape is the top-level `kotlin { compilerOptions { ... } }` block, // modern shape is the top-level `kotlin { compilerOptions { ... } }` block,
// which works whether Kotlin comes from AGP 9's built-in path or an // which works whether Kotlin comes from AGP 9's built-in path or an
@@ -196,6 +232,8 @@ dependencies {
testImplementation(libs.mockk) testImplementation(libs.mockk)
testImplementation(libs.kotlinx.coroutines.test) testImplementation(libs.kotlinx.coroutines.test)
testImplementation(libs.okhttp.mockwebserver) testImplementation(libs.okhttp.mockwebserver)
// HeldCertificate: a test-only CA, so the server probe can be driven over real TLS.
testImplementation(libs.okhttp.tls)
// kxml2 — provides an org.xmlpull.v1 impl on the JVM unit-test // kxml2 — provides an org.xmlpull.v1 impl on the JVM unit-test
// classpath. Android's stock XmlPullParserFactory resolves to the // classpath. Android's stock XmlPullParserFactory resolves to the
// android.jar Stub on JVM tests; kxml2 is picked up via service- // android.jar Stub on JVM tests; kxml2 is picked up via service-
@@ -24,6 +24,7 @@ import androidx.core.content.ContextCompat
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController import androidx.navigation.compose.rememberNavController
import com.fabledsword.minstrel.auth.AuthStore import com.fabledsword.minstrel.auth.AuthStore
import com.fabledsword.minstrel.auth.ui.AuthGateViewModel 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.connectivity.NetworkStatusController
import com.fabledsword.minstrel.nav.DetailSeedCache import com.fabledsword.minstrel.nav.DetailSeedCache
import com.fabledsword.minstrel.nav.LocalDetailSeedCache import com.fabledsword.minstrel.nav.LocalDetailSeedCache
import com.fabledsword.minstrel.nav.Login
import com.fabledsword.minstrel.nav.MinstrelNavGraph import com.fabledsword.minstrel.nav.MinstrelNavGraph
import com.fabledsword.minstrel.nav.Notifications import com.fabledsword.minstrel.nav.Notifications
import com.fabledsword.minstrel.nav.NowPlaying import com.fabledsword.minstrel.nav.NowPlaying
@@ -177,6 +179,7 @@ private fun App(
navController.navigate(route) { launchSingleTop = true } navController.navigate(route) { launchSingleTop = true }
onOpenedRoute() onOpenedRoute()
} }
SignInWhenSessionRejected(gate, navController)
MinstrelNavGraph( MinstrelNavGraph(
navController = navController, navController = navController,
startDestination = resolved, 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 @Composable
private fun BootSplash() { private fun BootSplash() {
Surface( Surface(
@@ -24,7 +24,6 @@ import com.fabledsword.minstrel.player.LikedAudioPinner
import com.fabledsword.minstrel.player.PlayEventsReporter import com.fabledsword.minstrel.player.PlayEventsReporter
import com.fabledsword.minstrel.player.PlaybackErrorReporter import com.fabledsword.minstrel.player.PlaybackErrorReporter
import com.fabledsword.minstrel.player.ResumeController import com.fabledsword.minstrel.player.ResumeController
import com.fabledsword.minstrel.update.data.UpdateBannerController
import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.NetworkStatusController
import dagger.hilt.android.HiltAndroidApp import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
@@ -155,14 +154,6 @@ class MinstrelApplication :
*/ */
@Suppress("unused") @Inject lateinit var networkStatusController: NetworkStatusController @Suppress("unused") @Inject lateinit var networkStatusController: NetworkStatusController
/**
* Same construct-the-singleton trick — UpdateBannerController polls
* /api/client/version at launch + every 24h and drives the shell's
* soft "update available" banner. Without this @Inject the poll
* loop would never start and the banner would never surface.
*/
@Suppress("unused") @Inject lateinit var updateBannerController: UpdateBannerController
/** /**
* Same construct-the-singleton trick — FreshnessSweeper's init * Same construct-the-singleton trick — FreshnessSweeper's init
* block starts a 30-min sweep loop that re-fetches cached * block starts a 30-min sweep loop that re-fetches cached
@@ -11,9 +11,10 @@ import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
/** /**
* Read-through accessor for the admin quarantine queue. No Room cache — * Read-through accessor for the admin Reports queue. No Room cache: it is an
* same rationale as AdminRequests. Three resolution actions all delete * admin's live work list, read fresh each time, and its actions go straight
* the row from the queue once the server accepts them. * to the server, so offline they fail with the reason rather than queueing.
* Each action takes the row off the queue once the server accepts it.
*/ */
@Singleton @Singleton
class AdminQuarantineRepository @Inject constructor( class AdminQuarantineRepository @Inject constructor(
@@ -25,6 +26,8 @@ class AdminQuarantineRepository @Inject constructor(
suspend fun resolve(trackId: String) = api.resolve(trackId) suspend fun resolve(trackId: String) = api.resolve(trackId)
suspend fun removeFile(trackId: String) = api.removeFile(trackId)
suspend fun deleteFile(trackId: String) = api.deleteFile(trackId) suspend fun deleteFile(trackId: String) = api.deleteFile(trackId)
} }
@@ -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.AdminUsersApi
import com.fabledsword.minstrel.api.endpoints.ResetPasswordBody import com.fabledsword.minstrel.api.endpoints.ResetPasswordBody
import com.fabledsword.minstrel.api.endpoints.SetAdminBody 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.AdminUserRef
import com.fabledsword.minstrel.models.wire.AdminUserWire import com.fabledsword.minstrel.models.wire.AdminUserWire
import retrofit2.Retrofit import retrofit2.Retrofit
@@ -27,9 +26,6 @@ class AdminUsersRepository @Inject constructor(
suspend fun setAdmin(id: String, isAdmin: Boolean) = suspend fun setAdmin(id: String, isAdmin: Boolean) =
api.setAdmin(id, SetAdminBody(isAdmin)) api.setAdmin(id, SetAdminBody(isAdmin))
suspend fun setAutoApprove(id: String, autoApprove: Boolean) =
api.setAutoApprove(id, SetAutoApproveBody(autoApprove))
suspend fun resetPassword(id: String, newPassword: String) = suspend fun resetPassword(id: String, newPassword: String) =
api.resetPassword(id, ResetPasswordBody(newPassword)) api.resetPassword(id, ResetPasswordBody(newPassword))
@@ -41,6 +37,5 @@ private fun AdminUserWire.toDomain(): AdminUserRef = AdminUserRef(
username = username, username = username,
displayName = displayName, displayName = displayName,
isAdmin = isAdmin, isAdmin = isAdmin,
autoApproveRequests = autoApproveRequests,
createdAt = createdAt, createdAt = createdAt,
) )
@@ -26,21 +26,19 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import com.composables.icons.lucide.Inbox
import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Music import com.composables.icons.lucide.Music
import com.composables.icons.lucide.TriangleAlert import com.composables.icons.lucide.TriangleAlert
import com.composables.icons.lucide.Users import com.composables.icons.lucide.Users
import com.fabledsword.minstrel.admin.data.AdminQuarantineRepository 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.AdminTagSourcesRepository
import com.fabledsword.minstrel.admin.data.AdminUsersRepository import com.fabledsword.minstrel.admin.data.AdminUsersRepository
import com.fabledsword.minstrel.api.ErrorCopy
import com.fabledsword.minstrel.nav.Admin import com.fabledsword.minstrel.nav.Admin
import com.fabledsword.minstrel.nav.AdminQuarantine import com.fabledsword.minstrel.nav.AdminQuarantine
import com.fabledsword.minstrel.nav.AdminRequests
import com.fabledsword.minstrel.nav.AdminTagSources import com.fabledsword.minstrel.nav.AdminTagSources
import com.fabledsword.minstrel.nav.AdminUsers import com.fabledsword.minstrel.nav.AdminUsers
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.loadUiState
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.LoadingCentered
@@ -58,25 +56,21 @@ import javax.inject.Inject
// ─── State ─────────────────────────────────────────────────────────── // ─── 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 { /** The admin landing's counts, as the shared [UiState] (never Empty: it always has counts). */
data object Loading : AdminLandingUiState typealias AdminLandingUiState = UiState<AdminCounts>
data class Success(val counts: AdminCounts) : AdminLandingUiState
data class Error(val message: String) : AdminLandingUiState
}
// ─── ViewModel ─────────────────────────────────────────────────────── // ─── ViewModel ───────────────────────────────────────────────────────
@HiltViewModel @HiltViewModel
class AdminLandingViewModel @Inject constructor( class AdminLandingViewModel @Inject constructor(
private val requestsRepo: AdminRequestsRepository,
private val quarantineRepo: AdminQuarantineRepository, private val quarantineRepo: AdminQuarantineRepository,
private val usersRepo: AdminUsersRepository, private val usersRepo: AdminUsersRepository,
private val tagSourcesRepo: AdminTagSourcesRepository, private val tagSourcesRepo: AdminTagSourcesRepository,
) : ViewModel() { ) : ViewModel() {
private val internal = MutableStateFlow<AdminLandingUiState>(AdminLandingUiState.Loading) private val internal = MutableStateFlow<AdminLandingUiState>(UiState.Loading)
val uiState: StateFlow<AdminLandingUiState> = internal.asStateFlow() val uiState: StateFlow<AdminLandingUiState> = internal.asStateFlow()
init { init {
@@ -84,22 +78,14 @@ class AdminLandingViewModel @Inject constructor(
} }
fun refresh(): Job = viewModelScope.launch { fun refresh(): Job = viewModelScope.launch {
internal.value = AdminLandingUiState.Loading internal.value = UiState.Loading
try { internal.value = loadUiState {
val counts = coroutineScope { coroutineScope {
val req = async { requestsRepo.list().size }
val qua = async { quarantineRepo.list().size } val qua = async { quarantineRepo.list().size }
val usr = async { usersRepo.list().size } val usr = async { usersRepo.list().size }
val tag = async { tagSourcesRepo.list().count { it.enabled } } val tag = async { tagSourcesRepo.list().count { it.enabled } }
AdminCounts(req.await(), qua.await(), usr.await(), tag.await()) UiState.Success(AdminCounts(qua.await(), usr.await(), tag.await()))
} }
internal.value = AdminLandingUiState.Success(counts)
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = AdminLandingUiState.Error(
ErrorCopy.fromThrowable(e),
)
} }
} }
} }
@@ -129,13 +115,13 @@ fun AdminLandingScreen(
modifier = Modifier.fillMaxSize().padding(inner), modifier = Modifier.fillMaxSize().padding(inner),
) { ) {
when (val s = state) { when (val s = state) {
AdminLandingUiState.Loading -> LoadingCentered() UiState.Loading, UiState.Empty -> LoadingCentered()
is AdminLandingUiState.Error -> EmptyState( is UiState.Error -> EmptyState(
title = "Couldn't load admin counts", title = "Couldn't load admin counts",
body = s.message, body = s.message,
) )
is AdminLandingUiState.Success -> SectionList( is UiState.Success -> SectionList(
counts = s.counts, counts = s.data,
navController = navController, navController = navController,
) )
} }
@@ -150,20 +136,11 @@ private fun SectionList(counts: AdminCounts, navController: NavHostController) {
contentPadding = PaddingValues(16.dp), contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(12.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 { item {
SectionCard( SectionCard(
icon = Lucide.TriangleAlert, icon = Lucide.TriangleAlert,
title = "Quarantine", title = "Reports",
subtitle = "Resolve scan failures", subtitle = "Tracks listeners flagged",
count = counts.quarantine, count = counts.quarantine,
onClick = { navController.navigate(AdminQuarantine) }, onClick = { navController.navigate(AdminQuarantine) },
) )
@@ -21,7 +21,9 @@ import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
@@ -31,6 +33,8 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import com.fabledsword.minstrel.models.AdminQuarantineItemRef import com.fabledsword.minstrel.models.AdminQuarantineItemRef
import com.fabledsword.minstrel.nav.AdminQuarantine import com.fabledsword.minstrel.nav.AdminQuarantine
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.ErrorRetry
@@ -56,7 +60,7 @@ fun AdminQuarantineScreen(
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
topBar = { topBar = {
MinstrelTopAppBar( MinstrelTopAppBar(
title = "Admin · Quarantine", title = "Admin · Reports",
navController = navController, navController = navController,
currentRouteName = AdminQuarantine::class.qualifiedName, currentRouteName = AdminQuarantine::class.qualifiedName,
onBack = { navController.popBackStack() }, onBack = { navController.popBackStack() },
@@ -69,20 +73,21 @@ fun AdminQuarantineScreen(
modifier = Modifier.fillMaxSize().padding(inner), modifier = Modifier.fillMaxSize().padding(inner),
) { ) {
when (val s = state) { when (val s = state) {
AdminQuarantineUiState.Loading -> LoadingCentered() UiState.Loading -> LoadingCentered()
AdminQuarantineUiState.Empty -> EmptyState( UiState.Empty -> EmptyState(
title = "Queue is empty", title = "No reports",
body = "When users flag tracks as bad rips, wrong tags, or " + body = "When listeners flag a track as a bad rip, wrong tags or " +
"duplicates, their reports get aggregated and surfaced here.", "a duplicate, their reports gather here.",
) )
is AdminQuarantineUiState.Error -> ErrorRetry( is UiState.Error -> ErrorRetry(
title = "Couldn't load queue", title = "Couldn't load queue",
message = s.message, message = s.message,
onRetry = { viewModel.refresh() }, onRetry = { viewModel.refresh() },
) )
is AdminQuarantineUiState.Success -> QueueList( is UiState.Success -> QueueList(
rows = s.rows, rows = s.data,
onResolve = viewModel::resolve, onResolve = viewModel::resolve,
onRemoveFile = viewModel::removeFile,
onDeleteFile = viewModel::deleteFile, onDeleteFile = viewModel::deleteFile,
) )
} }
@@ -90,28 +95,85 @@ fun AdminQuarantineScreen(
} }
} }
/** A confirm asked of the admin before a removal: which one, and of which track. */
private enum class Removal { File, Library }
private data class PendingRemoval(val row: AdminQuarantineItemRef, val kind: Removal)
@Composable @Composable
private fun QueueList( private fun QueueList(
rows: List<AdminQuarantineItemRef>, rows: List<AdminQuarantineItemRef>,
onResolve: (String) -> Unit, onResolve: (String) -> Unit,
onRemoveFile: (String) -> Unit,
onDeleteFile: (String) -> Unit, onDeleteFile: (String) -> Unit,
) { ) {
var pending by remember { mutableStateOf<PendingRemoval?>(null) }
LazyColumn(modifier = Modifier.fillMaxSize()) { LazyColumn(modifier = Modifier.fillMaxSize()) {
items(items = rows, key = { it.trackId }) { row -> items(items = rows, key = { it.trackId }) { row ->
QuarantineRow( QuarantineRow(
row = row, row = row,
onResolve = { onResolve(row.trackId) }, onResolve = { onResolve(row.trackId) },
onDeleteFile = { onDeleteFile(row.trackId) }, onRemoveFile = { pending = PendingRemoval(row, Removal.File) },
onDeleteFile = { pending = PendingRemoval(row, Removal.Library) },
) )
HorizontalDivider() HorizontalDivider()
} }
} }
pending?.let { p ->
RemovalConfirm(
pending = p,
onConfirm = {
pending = null
when (p.kind) {
Removal.File -> onRemoveFile(p.row.trackId)
Removal.Library -> onDeleteFile(p.row.trackId)
}
},
onDismiss = { pending = null },
)
}
}
/**
* Both removals delete the file, so each asks first. Remove the file keeps the
* track waiting for a good copy, with its likes and plays; Remove from library
* takes the track and its history too.
*/
@Composable
private fun RemovalConfirm(
pending: PendingRemoval,
onConfirm: () -> Unit,
onDismiss: () -> Unit,
) {
val title = pending.row.trackTitle
val (heading, body, action) = when (pending.kind) {
Removal.File -> Triple(
"Remove the file?",
"Delete the file of \u201c$title\u201d and keep the track. It waits, with its likes " +
"and plays, and takes over a good copy when one is in the library. Its reports are cleared.",
"Remove the file",
)
Removal.Library -> Triple(
"Remove from library?",
"Remove \u201c$title\u201d and its file for good, with its likes, plays and playlist " +
"places. To keep the track for a good copy, remove the file instead.",
"Remove from library",
)
}
ConfirmDestructiveDialog(
title = heading,
text = body,
confirmLabel = action,
onConfirm = onConfirm,
onDismiss = onDismiss,
)
} }
@Composable @Composable
private fun QuarantineRow( private fun QuarantineRow(
row: AdminQuarantineItemRef, row: AdminQuarantineItemRef,
onResolve: () -> Unit, onResolve: () -> Unit,
onRemoveFile: () -> Unit,
onDeleteFile: () -> Unit, onDeleteFile: () -> Unit,
) { ) {
Column( Column(
@@ -160,6 +222,7 @@ private fun QuarantineRow(
} }
ActionButtons( ActionButtons(
onResolve = onResolve, onResolve = onResolve,
onRemoveFile = onRemoveFile,
onDeleteFile = onDeleteFile, onDeleteFile = onDeleteFile,
) )
} }
@@ -168,6 +231,7 @@ private fun QuarantineRow(
@Composable @Composable
private fun ActionButtons( private fun ActionButtons(
onResolve: () -> Unit, onResolve: () -> Unit,
onRemoveFile: () -> Unit,
onDeleteFile: () -> Unit, onDeleteFile: () -> Unit,
) { ) {
Row( Row(
@@ -175,6 +239,7 @@ private fun ActionButtons(
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
) { ) {
TextButton(onClick = onResolve) { Text("Resolve") } TextButton(onClick = onResolve) { Text("Resolve") }
OutlinedButton(onClick = onDeleteFile) { Text("Delete file") } TextButton(onClick = onDeleteFile) { Text("Remove from library") }
OutlinedButton(onClick = onRemoveFile) { Text("Remove the file") }
} }
} }
@@ -8,6 +8,9 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.connectivity.recoveries
import com.fabledsword.minstrel.events.EventsStream import com.fabledsword.minstrel.events.EventsStream
import com.fabledsword.minstrel.models.AdminQuarantineItemRef import com.fabledsword.minstrel.models.AdminQuarantineItemRef
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.loadUiState
import com.fabledsword.minstrel.shared.toListState
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
@@ -20,12 +23,8 @@ import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import javax.inject.Inject import javax.inject.Inject
sealed interface AdminQuarantineUiState { /** The Reports queue, as the shared [UiState]. */
data object Loading : AdminQuarantineUiState typealias AdminQuarantineUiState = UiState<List<AdminQuarantineItemRef>>
data object Empty : AdminQuarantineUiState
data class Success(val rows: List<AdminQuarantineItemRef>) : AdminQuarantineUiState
data class Error(val message: String) : AdminQuarantineUiState
}
@HiltViewModel @HiltViewModel
class AdminQuarantineViewModel @Inject constructor( class AdminQuarantineViewModel @Inject constructor(
@@ -34,14 +33,13 @@ class AdminQuarantineViewModel @Inject constructor(
networkStatus: NetworkStatusController, networkStatus: NetworkStatusController,
) : ViewModel() { ) : ViewModel() {
private val internal = MutableStateFlow<AdminQuarantineUiState>(AdminQuarantineUiState.Loading) private val internal = MutableStateFlow<AdminQuarantineUiState>(UiState.Loading)
val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow() val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow()
/** /**
* One-shot messages for the screen's snackbar. A failed action has to say * One-shot messages for the screen's snackbar. A failed action has to say
* why: the row quietly reappearing reads as a glitch, and for a Delete * why: the row quietly reappearing reads as a glitch, and for a removal
* file refused by a read-only library it hides the one thing an * refused by a read-only library it hides the one thing an admin can fix.
* admin can fix.
*/ */
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED) private val transientMessagesChannel = Channel<String>(Channel.BUFFERED)
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow() val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
@@ -57,41 +55,24 @@ class AdminQuarantineViewModel @Inject constructor(
// when server health returns instead of waiting for a manual pull. // when server health returns instead of waiting for a manual pull.
viewModelScope.launch { viewModelScope.launch {
networkStatus.recoveries().collect { networkStatus.recoveries().collect {
if (internal.value is AdminQuarantineUiState.Error) refresh() if (internal.value is UiState.Error) refresh()
} }
} }
} }
fun refresh(): Job = viewModelScope.launch { fun refresh(): Job = viewModelScope.launch {
internal.value = AdminQuarantineUiState.Loading internal.value = UiState.Loading
try { internal.value = loadUiState { repository.list().toListState() }
val rows = repository.list()
internal.value = if (rows.isEmpty()) {
AdminQuarantineUiState.Empty
} else {
AdminQuarantineUiState.Success(rows)
}
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = AdminQuarantineUiState.Error(
ErrorCopy.fromThrowable(e),
)
}
} }
fun resolve(trackId: String) = act(trackId) { repository.resolve(it) } fun resolve(trackId: String) = act(trackId) { repository.resolve(it) }
fun removeFile(trackId: String) = act(trackId) { repository.removeFile(it) }
fun deleteFile(trackId: String) = act(trackId) { repository.deleteFile(it) } fun deleteFile(trackId: String) = act(trackId) { repository.deleteFile(it) }
private fun act(trackId: String, action: suspend (String) -> Unit) { private fun act(trackId: String, action: suspend (String) -> Unit) {
val before = internal.value val before = internal.value
if (before is AdminQuarantineUiState.Success) { if (before is UiState.Success) {
val filtered = before.rows.filterNot { it.trackId == trackId } internal.value = before.data.filterNot { it.trackId == trackId }.toListState()
internal.value = if (filtered.isEmpty()) {
AdminQuarantineUiState.Empty
} else {
AdminQuarantineUiState.Success(filtered)
}
} }
viewModelScope.launch { viewModelScope.launch {
try { try {
@@ -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()
}
}
}
}
@@ -35,6 +35,7 @@ import androidx.navigation.NavHostController
import com.fabledsword.minstrel.models.AdminTagSourceRef import com.fabledsword.minstrel.models.AdminTagSourceRef
import com.fabledsword.minstrel.models.TagSourceTestResult import com.fabledsword.minstrel.models.TagSourceTestResult
import com.fabledsword.minstrel.nav.AdminTagSources import com.fabledsword.minstrel.nav.AdminTagSources
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.ErrorRetry
@@ -66,19 +67,19 @@ fun AdminTagSourcesScreen(
modifier = Modifier.fillMaxSize().padding(inner), modifier = Modifier.fillMaxSize().padding(inner),
) { ) {
when (val s = state) { when (val s = state) {
AdminTagSourcesUiState.Loading -> LoadingCentered() UiState.Loading -> LoadingCentered()
AdminTagSourcesUiState.Empty -> EmptyState( UiState.Empty -> EmptyState(
title = "No tag sources", title = "No tag sources",
body = "Tag-enrichment providers register on the server; none are available.", body = "Tag-enrichment providers register on the server; none are available.",
) )
is AdminTagSourcesUiState.Error -> ErrorRetry( is UiState.Error -> ErrorRetry(
title = "Couldn't load tag sources", title = "Couldn't load tag sources",
message = s.message, message = s.message,
onRetry = { viewModel.refresh() }, onRetry = { viewModel.refresh() },
) )
is AdminTagSourcesUiState.Success -> TagSourceList( is UiState.Success -> TagSourceList(
providers = s.providers, providers = s.data.providers,
testResults = s.testResults, testResults = s.data.testResults,
onToggle = viewModel::setEnabled, onToggle = viewModel::setEnabled,
onSaveKey = viewModel::saveApiKey, onSaveKey = viewModel::saveApiKey,
onTest = viewModel::test, onTest = viewModel::test,
@@ -8,6 +8,8 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.connectivity.recoveries
import com.fabledsword.minstrel.models.AdminTagSourceRef import com.fabledsword.minstrel.models.AdminTagSourceRef
import com.fabledsword.minstrel.models.TagSourceTestResult import com.fabledsword.minstrel.models.TagSourceTestResult
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.loadUiState
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@@ -16,15 +18,14 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import javax.inject.Inject import javax.inject.Inject
sealed interface AdminTagSourcesUiState { /** The tag sources and the last Test answer for each, by provider id. */
data object Loading : AdminTagSourcesUiState data class AdminTagSources(
data object Empty : AdminTagSourcesUiState val providers: List<AdminTagSourceRef>,
data class Success( val testResults: Map<String, TagSourceTestResult> = emptyMap(),
val providers: List<AdminTagSourceRef>, )
val testResults: Map<String, TagSourceTestResult>,
) : AdminTagSourcesUiState /** The Tag sources screen, as the shared [UiState]. */
data class Error(val message: String) : AdminTagSourcesUiState typealias AdminTagSourcesUiState = UiState<AdminTagSources>
}
@HiltViewModel @HiltViewModel
class AdminTagSourcesViewModel @Inject constructor( class AdminTagSourcesViewModel @Inject constructor(
@@ -32,7 +33,7 @@ class AdminTagSourcesViewModel @Inject constructor(
networkStatus: NetworkStatusController, networkStatus: NetworkStatusController,
) : ViewModel() { ) : ViewModel() {
private val internal = MutableStateFlow<AdminTagSourcesUiState>(AdminTagSourcesUiState.Loading) private val internal = MutableStateFlow<AdminTagSourcesUiState>(UiState.Loading)
val uiState: StateFlow<AdminTagSourcesUiState> = internal.asStateFlow() val uiState: StateFlow<AdminTagSourcesUiState> = internal.asStateFlow()
init { init {
@@ -41,34 +42,28 @@ class AdminTagSourcesViewModel @Inject constructor(
// health returns instead of waiting for a manual pull. // health returns instead of waiting for a manual pull.
viewModelScope.launch { viewModelScope.launch {
networkStatus.recoveries().collect { networkStatus.recoveries().collect {
if (internal.value is AdminTagSourcesUiState.Error) refresh() if (internal.value is UiState.Error) refresh()
} }
} }
} }
fun refresh(): Job = viewModelScope.launch { fun refresh(): Job = viewModelScope.launch {
internal.value = AdminTagSourcesUiState.Loading internal.value = UiState.Loading
try { internal.value = loadUiState {
val providers = repository.list() val providers = repository.list()
internal.value = if (providers.isEmpty()) { if (providers.isEmpty()) UiState.Empty else UiState.Success(AdminTagSources(providers))
AdminTagSourcesUiState.Empty
} else {
AdminTagSourcesUiState.Success(providers, emptyMap())
}
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = AdminTagSourcesUiState.Error(ErrorCopy.fromThrowable(e))
} }
} }
fun setEnabled(id: String, enabled: Boolean) { fun setEnabled(id: String, enabled: Boolean) {
val before = internal.value as? AdminTagSourcesUiState.Success ?: return val before = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
// Optimistic toggle; reconcile via refresh() if the server rejects. // Optimistic toggle; reconcile via refresh() if the server rejects.
internal.value = before.copy( internal.value = UiState.Success(
providers = before.providers.map { before.copy(
if (it.id == id) it.copy(enabled = enabled) else it providers = before.providers.map {
}, if (it.id == id) it.copy(enabled = enabled) else it
},
),
) )
viewModelScope.launch { viewModelScope.launch {
try { try {
@@ -102,15 +97,17 @@ class AdminTagSourcesViewModel @Inject constructor(
) { ) {
TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e)) TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e))
} }
val current = internal.value as? AdminTagSourcesUiState.Success ?: return@launch val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return@launch
internal.value = current.copy(testResults = current.testResults + (id to result)) internal.value = UiState.Success(current.copy(testResults = current.testResults + (id to result)))
} }
} }
private fun replaceProvider(updated: AdminTagSourceRef) { private fun replaceProvider(updated: AdminTagSourceRef) {
val current = internal.value as? AdminTagSourcesUiState.Success ?: return val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
internal.value = current.copy( internal.value = UiState.Success(
providers = current.providers.map { if (it.id == updated.id) updated else it }, current.copy(
providers = current.providers.map { if (it.id == updated.id) updated else it },
),
) )
} }
} }
@@ -31,6 +31,7 @@ import androidx.compose.material3.TextButton
import android.content.ClipData import android.content.ClipData
import androidx.compose.ui.platform.ClipEntry import androidx.compose.ui.platform.ClipEntry
import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.platform.LocalClipboard
import com.fabledsword.minstrel.auth.PasswordRules
import com.fabledsword.minstrel.models.Invite import com.fabledsword.minstrel.models.Invite
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
@@ -49,6 +50,8 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import com.fabledsword.minstrel.models.AdminUserRef import com.fabledsword.minstrel.models.AdminUserRef
import com.fabledsword.minstrel.nav.AdminUsers import com.fabledsword.minstrel.nav.AdminUsers
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
@@ -81,7 +84,6 @@ fun AdminUsersScreen(
invitesViewModel.refresh() invitesViewModel.refresh()
}, },
onSetAdmin = viewModel::setAdmin, onSetAdmin = viewModel::setAdmin,
onSetAutoApprove = viewModel::setAutoApprove,
onAskResetPassword = { resetPasswordFor = it }, onAskResetPassword = { resetPasswordFor = it },
onAskDelete = { deleteCandidate = it }, onAskDelete = { deleteCandidate = it },
onAskGenerateInvite = { showGenerateInvite = true }, onAskGenerateInvite = { showGenerateInvite = true },
@@ -121,7 +123,6 @@ private fun AdminUsersScaffold(
invitesState: AdminInvitesUiState, invitesState: AdminInvitesUiState,
onRefresh: suspend () -> Unit, onRefresh: suspend () -> Unit,
onSetAdmin: (String, Boolean) -> Unit, onSetAdmin: (String, Boolean) -> Unit,
onSetAutoApprove: (String, Boolean) -> Unit,
onAskResetPassword: (AdminUserRef) -> Unit, onAskResetPassword: (AdminUserRef) -> Unit,
onAskDelete: (AdminUserRef) -> Unit, onAskDelete: (AdminUserRef) -> Unit,
onAskGenerateInvite: () -> Unit, onAskGenerateInvite: () -> Unit,
@@ -148,7 +149,6 @@ private fun AdminUsersScaffold(
usersSection( usersSection(
state = usersState, state = usersState,
onSetAdmin = onSetAdmin, onSetAdmin = onSetAdmin,
onSetAutoApprove = onSetAutoApprove,
onAskResetPassword = onAskResetPassword, onAskResetPassword = onAskResetPassword,
onAskDelete = onAskDelete, onAskDelete = onAskDelete,
) )
@@ -195,19 +195,17 @@ private fun SectionHeader(label: String, trailing: (@Composable () -> Unit)? = n
private fun androidx.compose.foundation.lazy.LazyListScope.usersSection( private fun androidx.compose.foundation.lazy.LazyListScope.usersSection(
state: AdminUsersUiState, state: AdminUsersUiState,
onSetAdmin: (String, Boolean) -> Unit, onSetAdmin: (String, Boolean) -> Unit,
onSetAutoApprove: (String, Boolean) -> Unit,
onAskResetPassword: (AdminUserRef) -> Unit, onAskResetPassword: (AdminUserRef) -> Unit,
onAskDelete: (AdminUserRef) -> Unit, onAskDelete: (AdminUserRef) -> Unit,
) { ) {
when (state) { when (state) {
AdminUsersUiState.Loading -> item { CenteredHint("Loading users…") } UiState.Loading -> item { CenteredHint("Loading users…") }
AdminUsersUiState.Empty -> item { CenteredHint("No registered users.") } UiState.Empty -> item { CenteredHint("No registered users.") }
is AdminUsersUiState.Error -> item { CenteredHint(state.message) } is UiState.Error -> item { CenteredHint(state.message) }
is AdminUsersUiState.Success -> items(items = state.users, key = { it.id }) { user -> is UiState.Success -> items(items = state.data, key = { it.id }) { user ->
UserRow( UserRow(
user = user, user = user,
onSetAdmin = { onSetAdmin(user.id, it) }, onSetAdmin = { onSetAdmin(user.id, it) },
onSetAutoApprove = { onSetAutoApprove(user.id, it) },
onResetPassword = { onAskResetPassword(user) }, onResetPassword = { onAskResetPassword(user) },
onDelete = { onAskDelete(user) }, onDelete = { onAskDelete(user) },
) )
@@ -397,7 +395,6 @@ private fun PendingDialogs(
private fun UserRow( private fun UserRow(
user: AdminUserRef, user: AdminUserRef,
onSetAdmin: (Boolean) -> Unit, onSetAdmin: (Boolean) -> Unit,
onSetAutoApprove: (Boolean) -> Unit,
onResetPassword: () -> Unit, onResetPassword: () -> Unit,
onDelete: () -> Unit, onDelete: () -> Unit,
) { ) {
@@ -420,11 +417,6 @@ private fun UserRow(
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
ToggleRow(label = "Admin", checked = user.isAdmin, onChange = onSetAdmin) ToggleRow(label = "Admin", checked = user.isAdmin, onChange = onSetAdmin)
ToggleRow(
label = "Auto-approve requests",
checked = user.autoApproveRequests,
onChange = onSetAutoApprove,
)
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.End), horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.End),
@@ -480,6 +472,7 @@ private fun ResetPasswordDialog(
value = newPassword, value = newPassword,
onValueChange = { newPassword = it }, onValueChange = { newPassword = it },
label = { Text("New password") }, label = { Text("New password") },
supportingText = { Text(PasswordRules.HINT) },
singleLine = true, singleLine = true,
visualTransformation = PasswordVisualTransformation(), visualTransformation = PasswordVisualTransformation(),
) )
@@ -488,7 +481,7 @@ private fun ResetPasswordDialog(
confirmButton = { confirmButton = {
TextButton( TextButton(
onClick = { onConfirm(newPassword) }, onClick = { onConfirm(newPassword) },
enabled = newPassword.isNotEmpty(), enabled = PasswordRules.isLongEnough(newPassword),
) { Text("Reset") } ) { Text("Reset") }
}, },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
@@ -501,39 +494,14 @@ private fun DeleteConfirmDialog(
onDismiss: () -> Unit, onDismiss: () -> Unit,
onConfirm: () -> Unit, onConfirm: () -> Unit,
) { ) {
var typed by remember { mutableStateOf("") } ConfirmDestructiveDialog(
val confirmed = typed.trim().equals(DELETE_CONFIRM_WORD, ignoreCase = true) title = "Delete user?",
AlertDialog( text = "Delete @${user.username}? This removes the account and all " +
onDismissRequest = onDismiss, "their data. Type $DELETE_CONFIRM_WORD to confirm.",
title = { Text("Delete user?") }, confirmLabel = "Delete",
text = { onConfirm = onConfirm,
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { onDismiss = onDismiss,
Text( confirmWord = DELETE_CONFIRM_WORD,
"Delete @${user.username}? This removes the account and all " +
"their data. Type $DELETE_CONFIRM_WORD to confirm.",
)
OutlinedTextField(
value = typed,
onValueChange = { typed = it },
label = { Text("Type $DELETE_CONFIRM_WORD") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
}
},
confirmButton = {
TextButton(onClick = onConfirm, enabled = confirmed) {
Text(
"Delete",
color = if (confirmed) {
MaterialTheme.colorScheme.error
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
)
}
},
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
) )
} }
@@ -3,10 +3,12 @@ package com.fabledsword.minstrel.admin.ui
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.fabledsword.minstrel.admin.data.AdminUsersRepository import com.fabledsword.minstrel.admin.data.AdminUsersRepository
import com.fabledsword.minstrel.api.ErrorCopy
import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.connectivity.recoveries
import com.fabledsword.minstrel.models.AdminUserRef import com.fabledsword.minstrel.models.AdminUserRef
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.loadUiState
import com.fabledsword.minstrel.shared.toListState
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@@ -15,12 +17,8 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import javax.inject.Inject import javax.inject.Inject
sealed interface AdminUsersUiState { /** The Users screen's list, as the shared [UiState]. */
data object Loading : AdminUsersUiState typealias AdminUsersUiState = UiState<List<AdminUserRef>>
data object Empty : AdminUsersUiState
data class Success(val users: List<AdminUserRef>) : AdminUsersUiState
data class Error(val message: String) : AdminUsersUiState
}
@HiltViewModel @HiltViewModel
class AdminUsersViewModel @Inject constructor( class AdminUsersViewModel @Inject constructor(
@@ -28,7 +26,7 @@ class AdminUsersViewModel @Inject constructor(
networkStatus: NetworkStatusController, networkStatus: NetworkStatusController,
) : ViewModel() { ) : ViewModel() {
private val internal = MutableStateFlow<AdminUsersUiState>(AdminUsersUiState.Loading) private val internal = MutableStateFlow<AdminUsersUiState>(UiState.Loading)
val uiState: StateFlow<AdminUsersUiState> = internal.asStateFlow() val uiState: StateFlow<AdminUsersUiState> = internal.asStateFlow()
init { init {
@@ -37,36 +35,20 @@ class AdminUsersViewModel @Inject constructor(
// when server health returns instead of waiting for a manual pull. // when server health returns instead of waiting for a manual pull.
viewModelScope.launch { viewModelScope.launch {
networkStatus.recoveries().collect { networkStatus.recoveries().collect {
if (internal.value is AdminUsersUiState.Error) refresh() if (internal.value is UiState.Error) refresh()
} }
} }
} }
fun refresh(): Job = viewModelScope.launch { fun refresh(): Job = viewModelScope.launch {
internal.value = AdminUsersUiState.Loading internal.value = UiState.Loading
try { internal.value = loadUiState { repository.list().toListState() }
val users = repository.list()
internal.value = if (users.isEmpty()) {
AdminUsersUiState.Empty
} else {
AdminUsersUiState.Success(users)
}
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = AdminUsersUiState.Error(ErrorCopy.fromThrowable(e))
}
} }
fun setAdmin(id: String, isAdmin: Boolean) = patch(id, { it.copy(isAdmin = isAdmin) }) { fun setAdmin(id: String, isAdmin: Boolean) = patch(id, { it.copy(isAdmin = isAdmin) }) {
repository.setAdmin(it, isAdmin) 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) { fun resetPassword(id: String, newPassword: String) {
viewModelScope.launch { viewModelScope.launch {
runCatching { repository.resetPassword(id, newPassword) } runCatching { repository.resetPassword(id, newPassword) }
@@ -75,13 +57,8 @@ class AdminUsersViewModel @Inject constructor(
fun delete(id: String) { fun delete(id: String) {
val before = internal.value val before = internal.value
if (before is AdminUsersUiState.Success) { if (before is UiState.Success) {
val filtered = before.users.filterNot { it.id == id } internal.value = before.data.filterNot { it.id == id }.toListState()
internal.value = if (filtered.isEmpty()) {
AdminUsersUiState.Empty
} else {
AdminUsersUiState.Success(filtered)
}
} }
viewModelScope.launch { viewModelScope.launch {
try { try {
@@ -100,9 +77,9 @@ class AdminUsersViewModel @Inject constructor(
action: suspend (String) -> Unit, action: suspend (String) -> Unit,
) { ) {
val before = internal.value val before = internal.value
if (before is AdminUsersUiState.Success) { if (before is UiState.Success) {
internal.value = AdminUsersUiState.Success( internal.value = UiState.Success(
before.users.map { if (it.id == id) mutate(it) else it }, before.data.map { if (it.id == id) mutate(it) else it },
) )
} }
viewModelScope.launch { viewModelScope.launch {
@@ -8,9 +8,9 @@ import javax.inject.Singleton
/** /**
* Attaches the session cookie from [AuthStore] to Minstrel-server * Attaches the session cookie from [AuthStore] to Minstrel-server
* requests, captures Set-Cookie from successful responses (login * requests (waiting for the stored one to load at launch), captures
* flow), and clears the store on 401 so downstream code can react * Set-Cookie from successful responses (login flow), and signs out when
* to logout. * the server refuses the cookie a request carried.
* *
* Scoped to the [BaseUrlInterceptor.PLACEHOLDER_HOST] sentinel host * Scoped to the [BaseUrlInterceptor.PLACEHOLDER_HOST] sentinel host
* the same way BaseUrlInterceptor is. The shared OkHttpClient also * the same way BaseUrlInterceptor is. The shared OkHttpClient also
@@ -32,7 +32,7 @@ class AuthCookieInterceptor @Inject constructor(
// session. Pass through untouched. // session. Pass through untouched.
return chain.proceed(original) return chain.proceed(original)
} }
val cookie = authStore.sessionCookie.value val cookie = authStore.sessionCookieForRequest()
val request = original.newBuilder().apply { val request = original.newBuilder().apply {
if (!cookie.isNullOrEmpty()) header("Cookie", cookie) if (!cookie.isNullOrEmpty()) header("Cookie", cookie)
}.build() }.build()
@@ -40,7 +40,11 @@ class AuthCookieInterceptor @Inject constructor(
val response = chain.proceed(request) val response = chain.proceed(request)
if (response.code == HTTP_UNAUTHORIZED) { 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) { } else if (response.isSuccessful) {
// Capture the first Set-Cookie pair on login; subsequent // Capture the first Set-Cookie pair on login; subsequent
// responses that include Set-Cookie keep the store fresh. // responses that include Set-Cookie keep the store fresh.
@@ -24,7 +24,7 @@ import javax.inject.Singleton
* rewritten. Absolute external URLs — artwork from * rewritten. Absolute external URLs — artwork from
* artwork.musicbrainz.org / coverartarchive.org, for example — must * artwork.musicbrainz.org / coverartarchive.org, for example — must
* reach their authored host unchanged: rewritten to the Minstrel host * 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 * No-op when the stored base URL is unparseable (falls through to
* whatever Retrofit had) — that case shows up as a transport-level * whatever Retrofit had) — that case shows up as a transport-level
@@ -44,13 +44,15 @@ object ErrorCopy {
} }
/** /**
* Codes whose server message carries specifics an admin needs in * Codes whose server message carries specifics an admin needs in order
* order to act — which directory, which uid — that fixed copy cannot say. * to act (which directory, which uid) that fixed copy cannot say. For
* For these the message follows the copy. Kept to a named set on * these the message follows the copy. Kept to a named set on purpose:
* purpose: most server messages are internal detail. Mirrors web's * most server messages are internal detail. The set is the web app's
* errors.ts. * error-detail-codes.json.
*/ */
private val DETAIL_CODES = setOf("library_not_writable", "file_delete_failed") private val DETAIL_CODES: Set<String> by lazy {
json.decodeFromString<List<String>>(sharedResource("error-detail-codes.json")).toSet()
}
private fun fromHttp(e: HttpException): String { private fun fromHttp(e: HttpException): String {
val body = bodyFromHttp(e) val body = bodyFromHttp(e)
@@ -69,53 +71,17 @@ object ErrorCopy {
.getOrNull() ?: Body() .getOrNull() ?: Body()
} }
private val TABLE: Map<String, String> = mapOf( /**
"unknown" to "Something went wrong.", * The copy for each error code: the web app's error-copy.json, copied
"unauthenticated" to "Your session has ended. Please sign in again.", * into the app's resources at build time (app/build.gradle.kts,
"auth_required" to "You need to sign in to do that.", * copySharedCopy), so both clients word every error the same way.
"forbidden" to "You don't have permission to do that.", */
"not_authorized" to "You don't have permission to do that.", private val TABLE: Map<String, String> by lazy {
"invalid_credentials" to "Wrong username or password.", json.decodeFromString<Map<String, String>>(sharedResource("error-copy.json"))
"rate_limited" to "Too many attempts. Wait a few minutes and try again.", }
"wrong_password" to "Current password is incorrect.",
"password_too_short" to "Password must be at least 8 characters.", private fun sharedResource(name: String): String =
"username_invalid" to "That username isn't valid.", checkNotNull(ErrorCopy::class.java.getResourceAsStream("/$name")) {
"username_taken" to "That username is already taken.", "$name is missing from the app's resources (copySharedCopy in app/build.gradle.kts)"
"email_invalid" to "Enter a valid email address.", }.use { it.reader().readText() }
"email_taken" to "That email is already in use.",
"invalid_token" to "That link has expired or already been used. Request a new one.",
"invite_invalid" to "That invite has expired or already been used.",
"invite_required" to "An invite is required to register on this server.",
"last_admin" to "Can't demote or delete the last admin.",
"no_email_on_file" to "No email is associated with that account.",
"not_configured" to "This integration isn't set up yet.",
"validation" to "Some fields aren't valid. Check and try again.",
"missing_fields" to "Required fields are missing.",
"missing_query" to "Search needs at least one keyword.",
"invalid_id" to "Invalid identifier.",
"invalid_body" to "Couldn't read the request.",
"bad_request" to "Invalid request.",
"bad_body" to "Couldn't read the request.",
"bad_kind" to "Invalid request type.",
"bad_paging" to "Invalid page size or offset.",
"bad_reason" to "Invalid quarantine reason.",
"mbid_required" to "An MBID is required for this lookup.",
"system_playlist_readonly" to "System playlists can't be edited directly.",
"connection_refused" to "Couldn't reach the server. Check the URL and try again.",
"cleartext_public" to
"This server is on the internet, so its URL must start with https://. " +
"Plain http:// only works on your home network.",
"request_not_pending" to "This request is no longer pending.",
"request_not_found" to "That request no longer exists.",
"not_followable" to "Various Artists and MusicBrainz placeholders can't be followed.",
"profile_not_found" to "That release-type profile no longer exists.",
"track_not_found" to "That track no longer exists.",
"library_not_writable" to "The music library isn't writable by the server.",
"file_delete_failed" to "The file couldn't be deleted.",
"album_not_found" to "That album no longer exists.",
"artist_not_found" to "That artist no longer exists.",
"playlist_not_found" to "That playlist no longer exists.",
"user_not_found" to "That user no longer exists.",
"not_found" to "That no longer exists.",
)
} }
@@ -8,9 +8,11 @@ import retrofit2.http.Path
/** /**
* Retrofit interface for `/api/admin/quarantine`. * Retrofit interface for `/api/admin/quarantine`.
* *
* Two resolution endpoints: * Three resolution endpoints:
* - `resolve` → admin reviewed, no action taken (clears flags). * - `resolve` → admin reviewed, no action taken (clears the reports).
* - `delete-file` → delete the track's file and row. * - `remove-file` → delete the track's file and keep the track, which waits
* for a good copy with its likes and plays.
* - `delete-file` → remove the track from the library, file and history.
*/ */
interface AdminQuarantineApi { interface AdminQuarantineApi {
@GET("api/admin/quarantine") @GET("api/admin/quarantine")
@@ -19,6 +21,9 @@ interface AdminQuarantineApi {
@POST("api/admin/quarantine/{trackId}/resolve") @POST("api/admin/quarantine/{trackId}/resolve")
suspend fun resolve(@Path("trackId") trackId: String) suspend fun resolve(@Path("trackId") trackId: String)
@POST("api/admin/quarantine/{trackId}/remove-file")
suspend fun removeFile(@Path("trackId") trackId: String)
@POST("api/admin/quarantine/{trackId}/delete-file") @POST("api/admin/quarantine/{trackId}/delete-file")
suspend fun deleteFile(@Path("trackId") trackId: String) suspend fun deleteFile(@Path("trackId") trackId: String)
} }
@@ -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.PUT
import retrofit2.http.Path import retrofit2.http.Path
/** /** Retrofit interface for `/api/admin/users`. */
* 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).
*/
interface AdminUsersApi { interface AdminUsersApi {
@GET("api/admin/users") @GET("api/admin/users")
suspend fun list(): AdminUsersListWire suspend fun list(): AdminUsersListWire
@@ -24,9 +17,6 @@ interface AdminUsersApi {
@PUT("api/admin/users/{id}/admin") @PUT("api/admin/users/{id}/admin")
suspend fun setAdmin(@Path("id") id: String, @Body body: SetAdminBody) 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") @POST("api/admin/users/{id}/reset-password")
suspend fun resetPassword(@Path("id") id: String, @Body body: ResetPasswordBody) 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, @kotlinx.serialization.SerialName("is_admin") val isAdmin: Boolean,
) )
@Serializable
data class SetAutoApproveBody(
@kotlinx.serialization.SerialName("auto_approve") val autoApprove: Boolean,
)
@Serializable @Serializable
data class ResetPasswordBody(val password: String) 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>
}
@@ -82,12 +82,15 @@ data class UpdateProfileRequest(
) )
/** /**
* Body for `PUT /api/me/password`. Both fields required. * Body for `PUT /api/me/password`. Both passwords required.
* [signOutSubsonic] also ends every Subsonic app's access: the API token and
* Subsonic password stop working.
*/ */
@Serializable @Serializable
data class ChangePasswordRequest( data class ChangePasswordRequest(
@SerialName("current_password") val currentPassword: String, @SerialName("current_password") val currentPassword: String,
@SerialName("new_password") val newPassword: String, @SerialName("new_password") val newPassword: String,
@SerialName("sign_out_subsonic") val signOutSubsonic: Boolean = false,
) )
/** /**
@@ -5,8 +5,11 @@ import com.fabledsword.minstrel.models.wire.PlaylistsListWire
import kotlinx.serialization.SerialName import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import retrofit2.http.Body import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET import retrofit2.http.GET
import retrofit2.http.PATCH
import retrofit2.http.POST import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.Path import retrofit2.http.Path
import retrofit2.http.Query import retrofit2.http.Query
@@ -27,11 +30,41 @@ interface PlaylistsApi {
suspend fun get(@Path("id") id: String): PlaylistDetailWire suspend fun get(@Path("id") id: String): PlaylistDetailWire
/** /**
* POST /api/playlists/{id}/tracks — append the given track IDs to * POST /api/playlists — make a playlist under the id the app chose,
* the owner's playlist. Server is idempotent at the (playlist_id, * so a create queued offline and sent again finds the same list.
* track_id) pair level; re-firing the same payload yields no
* duplicates.
*/ */
@POST("api/playlists")
suspend fun create(@Body body: CreatePlaylistRequest)
/** PATCH /api/playlists/{id} — rename, or make public or private. Null fields stay as they are. */
@PATCH("api/playlists/{id}")
suspend fun update(@Path("id") id: String, @Body body: UpdatePlaylistRequest)
@DELETE("api/playlists/{id}")
suspend fun delete(@Path("id") id: String)
/**
* DELETE /api/playlists/{id}/tracks/{position}. [trackId] is the song
* expected there; if another song has moved into that place the server
* removes nothing and answers 409, so a removal sent twice takes out
* one song, not two.
*/
@DELETE("api/playlists/{id}/tracks/{position}")
suspend fun removeTrack(
@Path("id") id: String,
@Path("position") position: Int,
@Query("track_id") trackId: String?,
)
/**
* PUT /api/playlists/{id}/tracks with the songs in their new order.
* Entries not named keep their places, and the same order sent twice
* changes nothing the second time.
*/
@PUT("api/playlists/{id}/tracks")
suspend fun reorder(@Path("id") id: String, @Body body: ReorderTracksRequest)
/** POST /api/playlists/{id}/tracks — append the given track IDs to the owner's playlist. */
@POST("api/playlists/{id}/tracks") @POST("api/playlists/{id}/tracks")
suspend fun appendTracks( suspend fun appendTracks(
@Path("id") playlistId: String, @Path("id") playlistId: String,
@@ -60,12 +93,14 @@ interface PlaylistsApi {
} }
/** /**
* POST /api/playlists/{id}/tracks body. The server expects snake_case * POST /api/playlists/{id}/tracks body. [requestId] names the append: the
* `track_ids`. * server applies an id once per playlist, so sending it again after a lost
* reply adds nothing more.
*/ */
@Serializable @Serializable
data class AppendTracksRequest( data class AppendTracksRequest(
@SerialName("track_ids") val trackIds: List<String>, @SerialName("track_ids") val trackIds: List<String>,
@SerialName("request_id") val requestId: String? = null,
) )
/** /**
@@ -77,3 +112,22 @@ data class AppendTracksRequest(
data class RefreshSystemResponse( data class RefreshSystemResponse(
@SerialName("playlist_id") val playlistId: String? = null, @SerialName("playlist_id") val playlistId: String? = null,
) )
@Serializable
data class CreatePlaylistRequest(
val id: String,
val name: String,
@SerialName("is_public") val isPublic: Boolean = false,
)
/** PATCH body; a null field is left out, so the server leaves it alone. */
@Serializable
data class UpdatePlaylistRequest(
val name: String? = null,
@SerialName("is_public") val isPublic: Boolean? = null,
)
@Serializable
data class ReorderTracksRequest(
@SerialName("track_ids") val trackIds: List<String>,
)
@@ -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
}
@@ -10,6 +10,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import retrofit2.Retrofit import retrofit2.Retrofit
import retrofit2.create import retrofit2.create
@@ -89,8 +90,11 @@ class AuthController @Inject constructor(
* + persisted userJson. Carries account-level flags (debug mode) * + persisted userJson. Carries account-level flags (debug mode)
* that aren't in the login response. Best-effort: a network failure * that aren't in the login response. Best-effort: a network failure
* leaves the cached identity untouched. No-op when signed out. * 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() { suspend fun refreshProfile() {
authStore.awaitSessionHydrated()
if (!isSignedIn) return if (!isSignedIn) return
val p = runCatching { meApi.getProfile() }.getOrNull() ?: return val p = runCatching { meApi.getProfile() }.getOrNull() ?: return
val user = UserRef( val user = UserRef(
@@ -104,18 +108,35 @@ class AuthController @Inject constructor(
} }
/** /**
* Clears the local session immediately and best-effort hits * Signs out here at once and ends the session on the server too.
* `/api/auth/logout` so the server can drop its session row. *
* Network errors are swallowed — the user is already locally * The app shows signed-out straight away, then calls
* signed out and a stale server session times out on its own. * `/api/auth/logout` while the session cookie is still set: the cookie
* is what tells the server which session to drop, so the call has to go
* before the cookie is cleared. The call waits at most
* [LOGOUT_TIMEOUT_MS]; offline, or on an error, the cookie is cleared
* anyway and the server session expires on its own. It runs in the
* application scope, so the screen that asked closing as the app shows
* signed-out can't cancel it halfway.
*/ */
suspend fun signOut() { suspend fun signOut() {
currentUserState.value = null currentUserState.value = null
authStore.setSessionCookie(null)
authStore.setUserJson(null) authStore.setUserJson(null)
runCatching { api.logout() } scope.launch {
try {
withTimeoutOrNull(LOGOUT_TIMEOUT_MS) { runCatching { api.logout() } }
} finally {
authStore.setSessionCookie(null)
}
}.join()
} }
private fun decodeUser(raw: String): UserRef? = private fun decodeUser(raw: String): UserRef? =
runCatching { json.decodeFromString(UserRef.serializer(), raw) }.getOrNull() runCatching { json.decodeFromString(UserRef.serializer(), raw) }.getOrNull()
private companion object {
// Long enough for a logout on a slow connection, short enough that
// signing out offline doesn't seem to hang.
const val LOGOUT_TIMEOUT_MS = 5_000L
}
} }
@@ -12,6 +12,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.withTimeoutOrNull
@@ -87,6 +88,17 @@ class AuthStore @Inject constructor(
private val backgroundDeliveryState = MutableStateFlow(true) private val backgroundDeliveryState = MutableStateFlow(true)
val backgroundDelivery: StateFlow<Boolean> = backgroundDeliveryState.asStateFlow() val backgroundDelivery: StateFlow<Boolean> = backgroundDeliveryState.asStateFlow()
// The account the cached data belongs to (AuthSessionEntity.cacheOwnerUserId).
// Null while the stored row is still loading, and before any account
// has been adopted; [settingsLoaded] tells the two apart.
private val cacheOwnerState = MutableStateFlow<String?>(null)
val cacheOwnerUserId: StateFlow<String?> = cacheOwnerState.asStateFlow()
private val settingsLoadedState = MutableStateFlow(false)
/** True once the stored settings row has been read at least once. */
val settingsLoaded: StateFlow<Boolean> = settingsLoadedState.asStateFlow()
private val json = Json { ignoreUnknownKeys = true } private val json = Json { ignoreUnknownKeys = true }
// Serialises every cookie persist with the one-time hydration, so a // Serialises every cookie persist with the one-time hydration, so a
@@ -111,6 +123,8 @@ class AuthStore @Inject constructor(
diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false
normalizationState.value = decodeNormalization(row?.normalizationJson) normalizationState.value = decodeNormalization(row?.normalizationJson)
backgroundDeliveryState.value = row?.backgroundDelivery ?: true backgroundDeliveryState.value = row?.backgroundDelivery ?: true
cacheOwnerState.value = row?.cacheOwnerUserId
settingsLoadedState.value = true
} }
} }
} }
@@ -148,6 +162,49 @@ class AuthStore @Inject constructor(
scope.launch { cookieLock.withLock { storeCookie(value) } } 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 { private suspend fun hydrateSessionCookie() = cookieLock.withLock {
val legacy = runCatching { dao.get()?.sessionCookie }.getOrNull() val legacy = runCatching { dao.get()?.sessionCookie }.getOrNull()
if (cookieTouched) return@withLock if (cookieTouched) return@withLock
@@ -223,6 +280,25 @@ class AuthStore @Inject constructor(
} }
} }
/**
* Records which account the cached data now belongs to. Suspends until
* it is stored, so a caller that has just cleared the old account's
* data can't have the adoption lost to a crash in between.
*/
suspend fun setCacheOwnerUserId(value: String?) {
cacheOwnerState.value = value
if (dao.get() == null) {
dao.upsert(currentEntity().copy(cacheOwnerUserId = value))
} else {
dao.setCacheOwnerUserId(value)
}
}
/** Forgets the newest notice announced, so the next account starts fresh. */
suspend fun clearNotifiedUpTo() {
if (dao.get() != null) dao.setNotifiedUpTo(null)
}
private suspend fun persistLegacyCookie(value: String?) { private suspend fun persistLegacyCookie(value: String?) {
if (dao.get() == null) { if (dao.get() == null) {
dao.upsert(currentEntity().copy(sessionCookie = value)) dao.upsert(currentEntity().copy(sessionCookie = value))
@@ -306,6 +382,7 @@ class AuthStore @Inject constructor(
normalizationState.value, normalizationState.value,
), ),
backgroundDelivery = backgroundDeliveryState.value, backgroundDelivery = backgroundDeliveryState.value,
cacheOwnerUserId = cacheOwnerState.value,
) )
companion object { companion object {
@@ -0,0 +1,24 @@
package com.fabledsword.minstrel.auth
import com.fabledsword.minstrel.api.ErrorCopy
/**
* The rules every new-password field shares (Settings › Password, an admin
* resetting someone's password), worded as the web app words them
* (web/src/lib/auth/password.ts). The server enforces the same minimum and
* answers password_too_short; checking here only saves the round trip.
*/
object PasswordRules {
const val MIN_LENGTH = 8
/** The hint under a new-password field. */
const val HINT = "At least $MIN_LENGTH characters."
/** Said when a new password is shorter than [MIN_LENGTH]: the server's own wording for it. */
val TOO_SHORT: String get() = ErrorCopy.messageFor("password_too_short")
/** Said when a password and its confirmation differ. */
const val DIFFER = "Passwords do not match."
fun isLongEnough(password: String): Boolean = password.length >= MIN_LENGTH
}
@@ -0,0 +1,180 @@
package com.fabledsword.minstrel.auth
import com.fabledsword.minstrel.api.CleartextToPublicHostException
import com.fabledsword.minstrel.api.MinstrelServerRequest
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import okhttp3.Call
import okhttp3.Callback
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.net.UnknownHostException
import java.security.GeneralSecurityException
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.net.ssl.SSLPeerUnverifiedException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/**
* Finds the Minstrel server behind an address the user typed.
*
* With no scheme typed it tries `https://` first. It falls back to `http://`
* only when https could not connect at all (refused, timed out, or no TLS on
* that port). A certificate that fails to verify stops the probe instead:
* falling back then would let anyone on the network path force a quiet
* downgrade. A scheme the user typed is used as typed, and still probed, so a
* wrong address fails here rather than at sign-in.
*
* Plain http still passes through [com.fabledsword.minstrel.api.CleartextGuardInterceptor]
* on [client], so the fallback can only succeed on a home-network address.
*/
class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis: Long) {
// Each attempt is short: a probe that stalls holds the sign-in screen.
@Inject constructor(client: OkHttpClient) : this(client, CALL_TIMEOUT_MILLIS)
private val client: OkHttpClient = client.newBuilder()
.connectTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS)
.callTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS)
.build()
sealed interface Result {
/** Minstrel answered at [baseUrl], which includes its scheme. */
data class Found(val baseUrl: String) : Result
data class Failed(val message: String) : Result
}
suspend fun find(input: String): Result {
val address = input.trim().trimEnd('/')
val lower = address.lowercase()
return when {
address.isEmpty() -> Result.Failed("Enter your server's address.")
lower.startsWith("https://") || lower.startsWith("http://") -> probeTyped(address)
"://" in address -> Result.Failed("Only https:// and http:// addresses are supported.")
else -> probeBare(address)
}
}
private suspend fun probeTyped(baseUrl: String): Result =
when (val outcome = attempt(baseUrl)) {
Outcome.Minstrel -> Result.Found(baseUrl)
is Outcome.Stop -> Result.Failed(outcome.message)
is Outcome.Unreachable ->
if (outcome.publicCleartext) {
Result.Failed(
"Plain http:// is only allowed to a server on your home network. " +
"Use https:// for this address.",
)
} else {
Result.Failed("Couldn't reach $baseUrl.")
}
}
private suspend fun probeBare(address: String): Result {
val https = "https://$address"
return when (val secure = attempt(https)) {
Outcome.Minstrel -> Result.Found(https)
is Outcome.Stop -> Result.Failed(secure.message)
is Outcome.Unreachable -> {
val http = "http://$address"
when (val plain = attempt(http)) {
Outcome.Minstrel -> Result.Found(http)
is Outcome.Stop -> Result.Failed(plain.message)
// A public host over plain http: say only that https
// failed, so the message never points the user at http.
is Outcome.Unreachable -> Result.Failed("Couldn't reach $https.")
}
}
}
}
private sealed interface Outcome {
data object Minstrel : Outcome
/** Nothing answered: the next scheme may be tried. */
data class Unreachable(val publicCleartext: Boolean = false) : Outcome
/** Something answered, or TLS failed to verify: stop here. */
data class Stop(val message: String) : Outcome
}
private suspend fun attempt(baseUrl: String): Outcome {
val url = "$baseUrl$SETUP_STATUS_PATH".toHttpUrlOrNull()
?: return Outcome.Stop("That doesn't look like a server address.")
val request = Request.Builder()
.url(url)
// Lets CleartextGuardInterceptor treat the probe as a Minstrel
// server request, as it treats sign-in.
.tag(MinstrelServerRequest::class.java, MinstrelServerRequest)
.build()
return try {
client.newCall(request).await().use { response ->
if (isMinstrel(response)) {
Outcome.Minstrel
} else {
Outcome.Stop("A server answered at $baseUrl, but it isn't Minstrel.")
}
}
} catch (@Suppress("SwallowedException") e: CleartextToPublicHostException) {
Outcome.Unreachable(publicCleartext = true)
} catch (@Suppress("SwallowedException") e: UnknownHostException) {
Outcome.Stop("Couldn't find a server named ${url.host}.")
} catch (e: IOException) {
if (isCertificateFailure(e)) {
Outcome.Stop(
"$baseUrl answered, but its certificate couldn't be verified, " +
"so the app won't connect to it.",
)
} else {
Outcome.Unreachable()
}
}
}
// GET /api/auth/setup-status answers {"setup_required": bool} with no
// sign-in, and only Minstrel answers it that way.
private fun isMinstrel(response: Response): Boolean {
val body = if (response.isSuccessful) response.body?.string() else null
val json = body?.let { runCatching { Json.parseToJsonElement(it) }.getOrNull() } as? JsonObject
return (json?.get("setup_required") as? JsonPrimitive)?.booleanOrNull != null
}
// An unverifiable certificate surfaces as SSLPeerUnverifiedException
// (hostname) or as an SSLHandshakeException caused by a
// CertificateException or CertPathValidatorException (trust). A port
// with no TLS fails the handshake too, but with no such cause.
private fun isCertificateFailure(e: IOException): Boolean =
generateSequence<Throwable>(e) { it.cause }
.take(MAX_CAUSE_DEPTH)
.any { it is SSLPeerUnverifiedException || it is GeneralSecurityException }
private suspend fun Call.await(): Response =
suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation { cancel() }
enqueue(
object : Callback {
override fun onResponse(call: Call, response: Response) {
if (continuation.isActive) continuation.resume(response) else response.close()
}
override fun onFailure(call: Call, e: IOException) {
if (continuation.isActive) continuation.resumeWithException(e)
}
},
)
}
private companion object {
const val SETUP_STATUS_PATH = "/api/auth/setup-status"
const val CALL_TIMEOUT_MILLIS = 8_000L
const val MAX_CAUSE_DEPTH = 8
}
}
@@ -38,6 +38,15 @@ class AuthGateViewModel @Inject constructor(
private val internal = MutableStateFlow<Any?>(null) private val internal = MutableStateFlow<Any?>(null)
val startDestination: StateFlow<Any?> = internal.asStateFlow() 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 { init {
viewModelScope.launch { viewModelScope.launch {
authStore.awaitSessionHydrated() authStore.awaitSessionHydrated()
@@ -5,13 +5,16 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -26,9 +29,11 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import com.fabledsword.minstrel.auth.AuthStore import com.fabledsword.minstrel.auth.AuthStore
import com.fabledsword.minstrel.auth.ServerProbe
import com.fabledsword.minstrel.nav.Login import com.fabledsword.minstrel.nav.Login
import com.fabledsword.minstrel.nav.ServerUrl import com.fabledsword.minstrel.nav.ServerUrl
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
@@ -40,7 +45,7 @@ import javax.inject.Inject
data class ServerUrlFormState( data class ServerUrlFormState(
val url: String = "", val url: String = "",
val saving: Boolean = false, val probing: Boolean = false,
val saved: Boolean = false, val saved: Boolean = false,
val errorMessage: String? = null, val errorMessage: String? = null,
) )
@@ -48,6 +53,7 @@ data class ServerUrlFormState(
@HiltViewModel @HiltViewModel
class ServerUrlViewModel @Inject constructor( class ServerUrlViewModel @Inject constructor(
private val authStore: AuthStore, private val authStore: AuthStore,
private val probe: ServerProbe,
) : ViewModel() { ) : ViewModel() {
private val internal = MutableStateFlow( private val internal = MutableStateFlow(
@@ -55,8 +61,8 @@ class ServerUrlViewModel @Inject constructor(
// the DEFAULT_BASE_URL placeholder (`http://localhost:8080`) is // the DEFAULT_BASE_URL placeholder (`http://localhost:8080`) is
// an internal HTTP-client fallback, not something a user // an internal HTTP-client fallback, not something a user
// typed. Leaving the field empty lets the OutlinedTextField's // typed. Leaving the field empty lets the OutlinedTextField's
// placeholder ("https://minstrel.example.com") show through // placeholder ("minstrel.example.com") show through so the user
// so the user can just type without first having to clear. // can just type without first having to clear.
ServerUrlFormState( ServerUrlFormState(
url = authStore.baseUrl.value url = authStore.baseUrl.value
.takeIf { it != AuthStore.DEFAULT_BASE_URL } .takeIf { it != AuthStore.DEFAULT_BASE_URL }
@@ -65,29 +71,39 @@ class ServerUrlViewModel @Inject constructor(
) )
val state: StateFlow<ServerUrlFormState> = internal.asStateFlow() val state: StateFlow<ServerUrlFormState> = internal.asStateFlow()
private var probeJob: Job? = null
fun setUrl(value: String) { fun setUrl(value: String) {
internal.update { it.copy(url = value, errorMessage = null) } internal.update { it.copy(url = value, errorMessage = null) }
} }
/**
* Looks for Minstrel at the typed address ([ServerProbe]) and saves the
* full URL that answered, scheme included, so every caller of
* [AuthStore.baseUrl] still receives a complete URL.
*/
fun submit() { fun submit() {
val raw = internal.value.url.trim().trimEnd('/') if (internal.value.probing) return
if (raw.isEmpty()) { val typed = internal.value.url
internal.update { it.copy(errorMessage = "Enter a server URL.") } probeJob = viewModelScope.launch {
return internal.update { it.copy(probing = true, errorMessage = null) }
} when (val result = probe.find(typed)) {
if (!raw.startsWith("http://") && !raw.startsWith("https://")) { is ServerProbe.Result.Found -> {
internal.update { authStore.setBaseUrl(result.baseUrl)
it.copy(errorMessage = "URL must start with http:// or https://") internal.update { it.copy(probing = false, saved = true) }
}
is ServerProbe.Result.Failed ->
internal.update { it.copy(probing = false, errorMessage = result.message) }
} }
return
}
viewModelScope.launch {
internal.update { it.copy(saving = true, errorMessage = null) }
authStore.setBaseUrl(raw)
internal.update { it.copy(saving = false, saved = true) }
} }
} }
fun cancelProbe() {
probeJob?.cancel()
probeJob = null
internal.update { it.copy(probing = false) }
}
fun consumeSaved() { fun consumeSaved() {
internal.update { it.copy(saved = false) } internal.update { it.copy(saved = false) }
} }
@@ -120,6 +136,7 @@ fun ServerUrlScreen(
state = state, state = state,
onUrlChange = viewModel::setUrl, onUrlChange = viewModel::setUrl,
onSubmit = viewModel::submit, onSubmit = viewModel::submit,
onCancel = viewModel::cancelProbe,
) )
} }
} }
@@ -129,6 +146,7 @@ private fun ServerUrlForm(
state: ServerUrlFormState, state: ServerUrlFormState,
onUrlChange: (String) -> Unit, onUrlChange: (String) -> Unit,
onSubmit: () -> Unit, onSubmit: () -> Unit,
onCancel: () -> Unit,
) { ) {
Column( Column(
modifier = Modifier modifier = Modifier
@@ -143,7 +161,7 @@ private fun ServerUrlForm(
color = MaterialTheme.colorScheme.onBackground, color = MaterialTheme.colorScheme.onBackground,
) )
Text( Text(
text = "Enter the URL of your Minstrel server.", text = "Enter the address of your Minstrel server.",
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
@@ -151,10 +169,13 @@ private fun ServerUrlForm(
value = state.url, value = state.url,
onValueChange = onUrlChange, onValueChange = onUrlChange,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
label = { Text("Server URL") }, label = { Text("Server address") },
placeholder = { Text("https://minstrel.example.com") }, placeholder = { Text("minstrel.example.com") },
supportingText = {
Text("No need for https://. The app tries https first, then http on your home network.")
},
singleLine = true, singleLine = true,
enabled = !state.saving, enabled = !state.probing,
keyboardOptions = KeyboardOptions( keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Uri, keyboardType = KeyboardType.Uri,
imeAction = ImeAction.Done, imeAction = ImeAction.Done,
@@ -168,10 +189,39 @@ private fun ServerUrlForm(
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
) )
} }
Button( ProbeButtons(
onClick = onSubmit, probing = state.probing,
enabled = !state.saving && state.url.isNotBlank(), canSubmit = state.url.isNotBlank(),
modifier = Modifier.fillMaxWidth(), onSubmit = onSubmit,
) { Text("Continue") } onCancel = onCancel,
)
}
}
/** Continue, which shows progress while the address is probed, and Cancel beside it. */
@Composable
private fun ProbeButtons(
probing: Boolean,
canSubmit: Boolean,
onSubmit: () -> Unit,
onCancel: () -> Unit,
) {
Button(
onClick = onSubmit,
enabled = !probing && canSubmit,
modifier = Modifier.fillMaxWidth(),
) {
if (probing) {
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
color = MaterialTheme.colorScheme.onPrimary,
strokeWidth = 2.dp,
)
} else {
Text("Continue")
}
}
if (probing) {
TextButton(onClick = onCancel) { Text("Cancel") }
} }
} }
@@ -0,0 +1,109 @@
package com.fabledsword.minstrel.cache.account
import com.fabledsword.minstrel.auth.AuthController
import com.fabledsword.minstrel.auth.AuthStore
import com.fabledsword.minstrel.di.ApplicationScope
import com.fabledsword.minstrel.player.PlayerController
import dagger.Lazy
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
/** What [AccountCache] does about the signed-in account and the cache's owner. */
internal enum class OwnerStep {
/** Nobody is signed in, or the stored owner hasn't loaded yet. */
WAIT,
/**
* The cache has no owner yet (a fresh install, or one updated from
* before owners): adopt the account, keeping the data.
*/
ADOPT,
/** Another account's data is cached: clear it, then adopt this account. */
SWITCH,
/** The signed-in account owns the cache. */
OWNED,
}
internal fun ownerStep(loaded: Boolean, signedInUserId: String?, ownerUserId: String?): OwnerStep = when {
!loaded || signedInUserId == null -> OwnerStep.WAIT
ownerUserId == null -> OwnerStep.ADOPT
ownerUserId != signedInUserId -> OwnerStep.SWITCH
else -> OwnerStep.OWNED
}
/**
* Keeps one account's cached data from reaching another account on a
* shared device.
*
* The device caches data that belongs to whoever is signed in: their
* queued offline writes (likes, plays, quarantine flags, playlist adds,
* settings), Home, history, quarantine list, notifications and the queue
* the player resumes. Likes and playlists carry a user id of their own;
* these don't. So the cache has an owner, stored with the device's
* settings. When a different account signs in, that data is cleared and
* the player emptied before the new account is adopted, however the last
* one left: by signing out, or by the server refusing its session.
*
* The same person signing back in keeps everything, queued writes
* included, so a session that expires offline loses nothing.
*
* [ownedBySignedInUser] gates the offline-write replayer: queued writes
* are sent only while their owner is the one signed in, so they never go
* out under another account's session.
*/
@Singleton
class AccountCache @Inject constructor(
private val authStore: AuthStore,
authController: AuthController,
private val tables: AccountTables,
private val player: Lazy<PlayerController>,
@ApplicationScope scope: CoroutineScope,
) {
private val ownedState = MutableStateFlow(false)
/** True while the signed-in account is the one the cached data belongs to. */
val ownedBySignedInUser: StateFlow<Boolean> = ownedState.asStateFlow()
init {
scope.launch {
combine(
authStore.settingsLoaded,
authController.currentUser,
authStore.cacheOwnerUserId,
) { loaded, user, owner -> Triple(loaded, user?.id, owner) }
.distinctUntilChanged()
.collect { (loaded, userId, owner) -> step(ownerStep(loaded, userId, owner), userId) }
}
}
private suspend fun step(step: OwnerStep, userId: String?) {
when (step) {
OwnerStep.WAIT -> ownedState.value = false
// The stored owner changes next, and that emission reports OWNED.
OwnerStep.ADOPT -> authStore.setCacheOwnerUserId(userId)
OwnerStep.SWITCH -> {
ownedState.value = false
clearAccountData()
authStore.setCacheOwnerUserId(userId)
}
OwnerStep.OWNED -> ownedState.value = true
}
}
private suspend fun clearAccountData() {
Timber.i("account cache: another account signed in; clearing the last one's data")
tables.clear()
authStore.clearNotifiedUpTo()
player.get().clearQueue()
}
}
@@ -0,0 +1,28 @@
package com.fabledsword.minstrel.cache.account
import androidx.room.withTransaction
import com.fabledsword.minstrel.cache.db.AppDatabase
import javax.inject.Inject
import javax.inject.Singleton
/**
* The cached tables that hold one account's data and carry no user id of
* their own, cleared together by [AccountCache] when another account signs
* in. A new table of that kind belongs in [clear]; one keyed by user id
* (likes, playlists) or shared by every account (the library) does not.
*/
@Singleton
class AccountTables @Inject constructor(private val db: AppDatabase) {
/** Clears them in one transaction, so a crash can't leave half of them. */
suspend fun clear() {
db.withTransaction {
db.cachedMutationDao().clear()
db.cachedHomeIndexDao().clear()
db.cachedHistorySnapshotDao().clear()
db.cachedQuarantineDao().clear()
db.cachedResumeStateDao().clear()
db.cachedNotificationDao().clear()
db.cachedNotificationDao().clearSettings()
}
}
}
@@ -67,6 +67,14 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
CachedNotificationEntity::class, CachedNotificationEntity::class,
CachedNotificationSettingsEntity::class, CachedNotificationSettingsEntity::class,
], ],
// v15: + auth_session.cacheOwnerUserId, the account the cached data
// belongs to. MIGRATION_14_15 adds it empty; AccountCache adopts the
// signed-in account.
// v14: + cached_playlists.shelfRank, a system mix's place on its Home
// shelf. MIGRATION_13_14 adds it as 0; the next list refresh fills it.
// v13: + cached_playlists.coverAlbumIds and createdAt, the albums Home's
// shelves draw each playlist tile's picture from and when a mix was
// rebuilt. MIGRATION_12_13 adds both empty; the next list refresh fills them.
// v12: + auth_session.backgroundDelivery and notifiedUpTo, the device's // v12: + auth_session.backgroundDelivery and notifiedUpTo, the device's
// background-delivery choice and its shade high-water mark. // background-delivery choice and its shade high-water mark.
// v11: + cached_notifications and cached_notification_settings, the // v11: + cached_notifications and cached_notification_settings, the
@@ -87,7 +95,7 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
// on auth_session. Versions before v8 rebuild destructively, which is // on auth_session. Versions before v8 rebuild destructively, which is
// right for them: the next sync refills every row with the new // right for them: the next sync refills every row with the new
// columns populated, so there is nothing to migrate by hand. // columns populated, so there is nothing to migrate by hand.
version = 12, version = 15,
exportSchema = true, exportSchema = true,
) )
@TypeConverters(MinstrelTypeConverters::class) @TypeConverters(MinstrelTypeConverters::class)
@@ -162,3 +170,35 @@ val MIGRATION_11_12: Migration = object : Migration(11, 12) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN notifiedUpTo INTEGER") db.execSQL("ALTER TABLE auth_session ADD COLUMN notifiedUpTo INTEGER")
} }
} }
/**
* v12 → v13: a playlist's cover albums and creation time. Both start empty;
* Home refreshes the playlist list on open, which fills them.
*/
val MIGRATION_12_13: Migration = object : Migration(12, 13) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN coverAlbumIds TEXT NOT NULL DEFAULT ''")
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN createdAt TEXT NOT NULL DEFAULT ''")
}
}
/**
* v13 → v14: a playlist's place on its Home shelf. Starts at 0 (unranked);
* Home refreshes the playlist list on open, which fills it.
*/
val MIGRATION_13_14: Migration = object : Migration(13, 14) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE cached_playlists ADD COLUMN shelfRank INTEGER NOT NULL DEFAULT 0")
}
}
/**
* v14 → v15: the account the cached data belongs to. Starts empty, and
* AccountCache adopts whoever is signed in without clearing anything, so
* an update keeps the signed-in person's queued writes and cache.
*/
val MIGRATION_14_15: Migration = object : Migration(14, 15) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN cacheOwnerUserId TEXT")
}
}
@@ -37,7 +37,15 @@ object DatabaseModule {
// and rebuilds. The sync controller refills the cache from the // and rebuilds. The sync controller refills the cache from the
// server on first launch, so a rebuild loses only the unsynced // server on first launch, so a rebuild loses only the unsynced
// mutation queue. // mutation queue.
.addMigrations(MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12) .addMigrations(
MIGRATION_8_9,
MIGRATION_9_10,
MIGRATION_10_11,
MIGRATION_11_12,
MIGRATION_12_13,
MIGRATION_13_14,
MIGRATION_14_15,
)
.fallbackToDestructiveMigration(dropAllTables = true) .fallbackToDestructiveMigration(dropAllTables = true)
.build() .build()
@@ -59,4 +59,7 @@ interface AuthSessionDao {
/** Partial update: change only the shade's high-water mark. */ /** Partial update: change only the shade's high-water mark. */
@Query("UPDATE auth_session SET notifiedUpTo = :upTo WHERE id = 0") @Query("UPDATE auth_session SET notifiedUpTo = :upTo WHERE id = 0")
suspend fun setNotifiedUpTo(upTo: Instant?) suspend fun setNotifiedUpTo(upTo: Instant?)
@Query("UPDATE auth_session SET cacheOwnerUserId = :userId WHERE id = 0")
suspend fun setCacheOwnerUserId(userId: String?)
} }
@@ -15,4 +15,7 @@ interface CachedHistorySnapshotDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsert(row: CachedHistorySnapshotEntity) suspend fun upsert(row: CachedHistorySnapshotEntity)
@Query("DELETE FROM cached_history_snapshot")
suspend fun clear()
} }
@@ -48,4 +48,7 @@ interface CachedNotificationDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertSettings(row: CachedNotificationSettingsEntity) suspend fun upsertSettings(row: CachedNotificationSettingsEntity)
@Query("DELETE FROM cached_notification_settings")
suspend fun clearSettings()
} }
@@ -14,12 +14,12 @@ interface CachedPlaylistDao {
@Query("SELECT * FROM cached_playlists ORDER BY name COLLATE NOCASE ASC") @Query("SELECT * FROM cached_playlists ORDER BY name COLLATE NOCASE ASC")
fun observeAll(): Flow<List<CachedPlaylistEntity>> fun observeAll(): Flow<List<CachedPlaylistEntity>>
/** User playlists only (systemVariant IS NULL) — for the add-to-playlist sheet. */ /** [userId]'s own playlists, not mixes: the lists they can add a song to. */
@Query( @Query(
"SELECT * FROM cached_playlists " + "SELECT * FROM cached_playlists " +
"WHERE systemVariant IS NULL ORDER BY name COLLATE NOCASE ASC", "WHERE systemVariant IS NULL AND userId = :userId ORDER BY name COLLATE NOCASE ASC",
) )
fun observeUserPlaylists(): Flow<List<CachedPlaylistEntity>> fun observeOwnedUserPlaylists(userId: String): Flow<List<CachedPlaylistEntity>>
/** System playlists for the home screen. */ /** System playlists for the home screen. */
@Query( @Query(
@@ -61,7 +61,15 @@ data class AuthSessionEntity(
/** /**
* The newest notice this device has announced in the shade. A catch-up * The newest notice this device has announced in the shade. A catch-up
* announces only what is newer, so a reboot or a reconnect never * announces only what is newer, so a reboot or a reconnect never
* re-announces a backlog. Cleared on sign-out. * re-announces a backlog. Cleared when another account signs in.
*/ */
val notifiedUpTo: Instant? = null, val notifiedUpTo: Instant? = null,
/**
* The account the device's cached data belongs to: its queued offline
* writes, Home, history, quarantine list, notifications and resume
* queue. When a different account signs in, AccountCache clears that
* data before adopting the new account, so one person never sees or
* sends another's. Null until an account has been adopted.
*/
val cacheOwnerUserId: String? = null,
) )
@@ -9,7 +9,7 @@ import kotlinx.datetime.Instant
* Cache row for one artist. * Cache row for one artist.
* *
* Column names follow Kotlin idiom (camelCase) — the schema is purely * 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. * with the server and our mappers translate at the boundary.
*/ */
@Entity(tableName = "cached_artists") @Entity(tableName = "cached_artists")
@@ -1,5 +1,6 @@
package com.fabledsword.minstrel.cache.db.entities package com.fabledsword.minstrel.cache.db.entities
import androidx.room.ColumnInfo
import androidx.room.Entity import androidx.room.Entity
import androidx.room.PrimaryKey import androidx.room.PrimaryKey
import kotlinx.datetime.Clock import kotlinx.datetime.Clock
@@ -25,4 +26,16 @@ data class CachedPlaylistEntity(
val durationSec: Int = 0, val durationSec: Int = 0,
val systemVariant: String? = null, val systemVariant: String? = null,
val fetchedAt: Instant = Clock.System.now(), val fetchedAt: Instant = Clock.System.now(),
/**
* The playlist's cover albums, comma-joined (album ids are UUIDs and
* carry no commas). Empty until the list is next refreshed.
*/
@ColumnInfo(defaultValue = "''")
val coverAlbumIds: String = "",
/** ISO-8601 creation time; for a system mix, when it was last rebuilt. */
@ColumnInfo(defaultValue = "''")
val createdAt: String = "",
/** Place on its Home shelf, 1 first; 0 when unranked. */
@ColumnInfo(defaultValue = "0")
val shelfRank: Int = 0,
) )
@@ -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 * Stable mutation kinds the queue knows how to replay. Strings are
* persisted in `cached_mutations.kind` so renaming a variant breaks * 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 { object MutationKind {
const val LIKE_TOGGLE: String = "like_toggle" const val LIKE_TOGGLE: String = "like_toggle"
const val REQUEST_CREATE: String = "request_create"
const val QUARANTINE_UNFLAG: String = "quarantine_unflag" const val QUARANTINE_UNFLAG: String = "quarantine_unflag"
const val PLAYLIST_APPEND: String = "playlist_append" const val PLAYLIST_APPEND: String = "playlist_append"
const val QUARANTINE_FLAG: String = "quarantine_flag" const val QUARANTINE_FLAG: String = "quarantine_flag"
const val PLAY_OFFLINE: String = "play_offline" const val PLAY_OFFLINE: String = "play_offline"
const val REQUEST_CANCEL: String = "request_cancel"
const val PLAYBACK_ERROR_REPORT: String = "playback_error_report" const val PLAYBACK_ERROR_REPORT: String = "playback_error_report"
// Durable close-by-id for a play whose server row is already open // 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. // background would duplicate the open row and leave it orphaned.
const val PLAY_ENDED: String = "play_ended" 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 // Loudness-normalization preference. The payload is the whole
// preference, a target state like the toggles above, so queued changes // 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. // collapse to the last one and an older one can never be replayed last.
@@ -58,6 +51,16 @@ object MutationKind {
// Per-kind notification channel. One row per (kind, channel) target // Per-kind notification channel. One row per (kind, channel) target
// state, collapsed on that pair, so the newest choice is the one sent. // state, collapsed on that pair, so the newest choice is the one sent.
const val NOTIFICATION_SETTING_SET: String = "notification_setting_set" const val NOTIFICATION_SETTING_SET: String = "notification_setting_set"
// A listener's own playlists. Each is safe to send twice: a create
// carries the app's own id for the list, a removal names the song it
// expects at that place, and a reorder is the whole new order (a
// target state, so queued reorders of one list collapse to the last).
const val PLAYLIST_CREATE: String = "playlist_create"
const val PLAYLIST_UPDATE: String = "playlist_update"
const val PLAYLIST_DELETE: String = "playlist_delete"
const val PLAYLIST_REMOVE_TRACK: String = "playlist_remove_track"
const val PLAYLIST_REORDER: String = "playlist_reorder"
} }
/** /**
@@ -73,23 +76,6 @@ data class LikeTogglePayload(
val desiredState: Boolean, 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. * Write side of the offline mutation queue; [MutationReplayer] drains it.
* *
@@ -137,11 +123,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( suspend fun enqueueQuarantineUnflag(trackId: String): Long = insertUserDriven(
MutationKind.QUARANTINE_UNFLAG, MutationKind.QUARANTINE_UNFLAG,
json.encodeToString( json.encodeToString(
@@ -150,17 +131,83 @@ class MutationQueue @Inject constructor(
), ),
) )
suspend fun enqueuePlaylistAppend( suspend fun enqueuePlaylistAppend(payload: PlaylistAppendPayload): Long = insertUserDriven(
playlistId: String,
trackIds: List<String>,
): Long = insertUserDriven(
MutationKind.PLAYLIST_APPEND, MutationKind.PLAYLIST_APPEND,
json.encodeToString( json.encodeToString(PlaylistAppendPayload.serializer(), payload),
PlaylistAppendPayload.serializer(),
PlaylistAppendPayload(playlistId, trackIds),
),
) )
suspend fun enqueuePlaylistCreate(payload: PlaylistCreatePayload): Long = insertUserDriven(
MutationKind.PLAYLIST_CREATE,
json.encodeToString(PlaylistCreatePayload.serializer(), payload),
)
suspend fun enqueuePlaylistUpdate(payload: PlaylistUpdatePayload): Long = insertUserDriven(
MutationKind.PLAYLIST_UPDATE,
json.encodeToString(PlaylistUpdatePayload.serializer(), payload),
)
suspend fun enqueuePlaylistDelete(playlistId: String): Long = insertUserDriven(
MutationKind.PLAYLIST_DELETE,
json.encodeToString(PlaylistDeletePayload.serializer(), PlaylistDeletePayload(playlistId)),
)
suspend fun enqueuePlaylistRemoveTrack(payload: PlaylistRemoveTrackPayload): Long = insertUserDriven(
MutationKind.PLAYLIST_REMOVE_TRACK,
json.encodeToString(PlaylistRemoveTrackPayload.serializer(), payload),
)
suspend fun enqueuePlaylistReorder(payload: PlaylistReorderPayload): Long = insertUserDriven(
MutationKind.PLAYLIST_REORDER,
json.encodeToString(PlaylistReorderPayload.serializer(), payload),
)
/**
* Ids of playlists made on this device that the server hasn't been
* sent yet. A list refresh keeps them, so a playlist made offline
* doesn't vanish before its create goes out.
*/
suspend fun pendingPlaylistCreateIds(): Set<String> = dao.getAll()
.asSequence()
.filter { it.kind == MutationKind.PLAYLIST_CREATE }
.mapNotNull { row ->
runCatching { json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload) }
.getOrNull()?.id
}
.toSet()
/**
* The like state each still-queued like toggle sets, by
* [likeToggleKey], the newest toggle winning. A toggle for an entity
* found here must queue behind it rather than go live, or the older
* one replays after it and undoes it; and a refresh keeps these states
* over the server's, which hasn't seen them yet.
*/
suspend fun pendingLikeStates(): Map<String, Boolean> = buildMap {
dao.getAll().filter { it.kind == MutationKind.LIKE_TOGGLE }.forEach { row ->
runCatching { json.decodeFromString(LikeTogglePayload.serializer(), row.payload) }
.getOrNull()
?.let { put(likeToggleKey(it.entityType, it.entityId), it.desiredState) }
}
}
/**
* Whether each track with a quarantine flag or unflag still queued ends
* up flagged (true) or not, the newest winning. Read for the same two
* reasons as [pendingLikeStates].
*/
suspend fun pendingQuarantineStates(): Map<String, Boolean> = buildMap {
dao.getAll().forEach { row ->
when (row.kind) {
MutationKind.QUARANTINE_FLAG -> runCatching {
json.decodeFromString(QuarantineFlagPayload.serializer(), row.payload)
}.getOrNull()?.let { put(it.trackId, true) }
MutationKind.QUARANTINE_UNFLAG -> runCatching {
json.decodeFromString(QuarantineUnflagPayload.serializer(), row.payload)
}.getOrNull()?.let { put(it.trackId, false) }
}
}
}
suspend fun enqueueQuarantineFlag( suspend fun enqueueQuarantineFlag(
trackId: String, trackId: String,
reason: String, reason: String,
@@ -173,25 +220,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. */ /** Queues the user's whole normalization preference for replay. */
suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long = insertUserDriven( suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long = insertUserDriven(
MutationKind.NORMALIZATION_SET, MutationKind.NORMALIZATION_SET,
@@ -217,14 +245,6 @@ class MutationQueue @Inject constructor(
json.encodeToString(NotificationSettingPayload.serializer(), payload), 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( suspend fun enqueuePlayOffline(payload: PlayOfflinePayload): Long = dao.insert(
CachedMutationEntity( CachedMutationEntity(
kind = MutationKind.PLAY_OFFLINE, kind = MutationKind.PLAY_OFFLINE,
@@ -257,21 +277,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 * Persisted payload for `MutationKind.QUARANTINE_UNFLAG` — the
* `DELETE /api/quarantine/{trackId}` call lost during a connectivity * `DELETE /api/quarantine/{trackId}` call lost during a connectivity
@@ -280,16 +285,60 @@ data class SuggestionSnoozeTogglePayload(
@Serializable @Serializable
data class QuarantineUnflagPayload(val trackId: String) data class QuarantineUnflagPayload(val trackId: String)
/** The key [MutationQueue.pendingLikeStates] files a like toggle under. */
fun likeToggleKey(entityType: String, entityId: String): String = "$entityType:$entityId"
/** /**
* Persisted payload for `MutationKind.PLAYLIST_APPEND`: the track IDs to * Persisted payload for `MutationKind.PLAYLIST_APPEND`: the track IDs to
* append to one playlist. The server is idempotent at the * append to one playlist. [requestId] is the id the live send carried, so
* (playlist_id, track_id) pair level — re-firing the same payload yields * the server can tell a replay of an append it already applied (its reply
* no duplicates. * was lost) from a new one. Rows queued before it existed have none and
* append on every send, as they always did.
*/ */
@Serializable @Serializable
data class PlaylistAppendPayload( data class PlaylistAppendPayload(
val playlistId: String, val playlistId: String,
val trackIds: List<String>, val trackIds: List<String>,
val requestId: String? = null,
)
/** Persisted payload for `MutationKind.PLAYLIST_CREATE`; [id] is the one the app chose. */
@Serializable
data class PlaylistCreatePayload(
val id: String,
val name: String,
val isPublic: Boolean = false,
)
/** Persisted payload for `MutationKind.PLAYLIST_UPDATE`; a null field is left as it is. */
@Serializable
data class PlaylistUpdatePayload(
val playlistId: String,
val name: String? = null,
val isPublic: Boolean? = null,
)
/** Persisted payload for `MutationKind.PLAYLIST_DELETE`. */
@Serializable
data class PlaylistDeletePayload(val playlistId: String)
/**
* Persisted payload for `MutationKind.PLAYLIST_REMOVE_TRACK`. [trackId] is
* the song at [position] when the listener removed it; null for an entry
* whose song has left the library.
*/
@Serializable
data class PlaylistRemoveTrackPayload(
val playlistId: String,
val position: Int,
val trackId: String? = null,
)
/** Persisted payload for `MutationKind.PLAYLIST_REORDER`: the songs in their new order. */
@Serializable
data class PlaylistReorderPayload(
val playlistId: String,
val trackIds: List<String>,
) )
/** /**
@@ -337,15 +386,6 @@ data class PlayEndedPayload(
val durationPlayedMs: Long, 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 * Persisted payload for `MutationKind.PLAYBACK_ERROR_REPORT` — the
* `POST /api/playback-errors` call lost during a connectivity hiccup. * `POST /api/playback-errors` call lost during a connectivity hiccup.
@@ -3,7 +3,7 @@
package com.fabledsword.minstrel.cache.mutations package com.fabledsword.minstrel.cache.mutations
import com.fabledsword.minstrel.api.endpoints.AppendTracksRequest import com.fabledsword.minstrel.api.endpoints.AppendTracksRequest
import com.fabledsword.minstrel.api.endpoints.DiscoverApi import com.fabledsword.minstrel.api.endpoints.CreatePlaylistRequest
import com.fabledsword.minstrel.api.endpoints.EventsApi import com.fabledsword.minstrel.api.endpoints.EventsApi
import com.fabledsword.minstrel.api.endpoints.FlagRequest import com.fabledsword.minstrel.api.endpoints.FlagRequest
import com.fabledsword.minstrel.api.endpoints.LikesApi import com.fabledsword.minstrel.api.endpoints.LikesApi
@@ -15,19 +15,19 @@ import com.fabledsword.minstrel.api.endpoints.PlaybackErrorReportRequest
import com.fabledsword.minstrel.api.endpoints.PlaybackErrorsApi import com.fabledsword.minstrel.api.endpoints.PlaybackErrorsApi
import com.fabledsword.minstrel.api.endpoints.PlaylistsApi import com.fabledsword.minstrel.api.endpoints.PlaylistsApi
import com.fabledsword.minstrel.api.endpoints.QuarantineApi import com.fabledsword.minstrel.api.endpoints.QuarantineApi
import com.fabledsword.minstrel.api.endpoints.RequestsApi import com.fabledsword.minstrel.api.endpoints.ReorderTracksRequest
import com.fabledsword.minstrel.api.endpoints.UpdatePlaylistRequest
import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.models.wire.PlayEndedRequest import com.fabledsword.minstrel.models.wire.PlayEndedRequest
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody
import com.fabledsword.minstrel.auth.AuthStore import com.fabledsword.minstrel.auth.AuthStore
import com.fabledsword.minstrel.cache.account.AccountCache
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
import com.fabledsword.minstrel.di.ApplicationScope import com.fabledsword.minstrel.di.ApplicationScope
import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.likes.data.LikesRepository
import com.fabledsword.minstrel.settings.data.NormalizationPrefs import com.fabledsword.minstrel.settings.data.NormalizationPrefs
import com.fabledsword.minstrel.models.wire.CreateRequestBody
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filter
@@ -56,10 +56,16 @@ import javax.inject.Singleton
* - RETRY — transient (transport, 5xx, 408, 429) → leave queued, bump * - RETRY — transient (transport, 5xx, 408, 429) → leave queued, bump
* attempts, retry on the next trigger. * attempts, retry on the next trigger.
* *
* Queued writes belong to the account that made them, and are sent only
* while [AccountCache] reports that account is the one signed in; when
* another account signs in, AccountCache clears them instead.
*
* Triggered by: * Triggered by:
* - app start (MinstrelApplication @Inject forces the singleton's init) * - app start (MinstrelApplication @Inject forces the singleton's init)
* - AuthStore.sessionCookie transitioning to non-null (sign-in / cold * - AuthStore.sessionCookie transitioning to non-null (sign-in / cold
* start with a persisted cookie) * start with a persisted cookie)
* - AccountCache confirming the signed-in account owns the queue (just
* after a sign-in, once the account is known)
* - NetworkStatusController recovering to Healthy (server reachable again * - NetworkStatusController recovering to Healthy (server reachable again
* mid-session — covers offline→online without needing a cold start) * mid-session — covers offline→online without needing a cold start)
* *
@@ -72,17 +78,16 @@ import javax.inject.Singleton
class MutationReplayer @Inject constructor( class MutationReplayer @Inject constructor(
private val dao: CachedMutationDao, private val dao: CachedMutationDao,
private val authStore: AuthStore, private val authStore: AuthStore,
private val accountCache: AccountCache,
private val json: Json, private val json: Json,
@ApplicationScope private val scope: CoroutineScope, @ApplicationScope private val scope: CoroutineScope,
networkStatus: NetworkStatusController, networkStatus: NetworkStatusController,
retrofit: Retrofit, retrofit: Retrofit,
) { ) {
private val likesApi: LikesApi = retrofit.create() private val likesApi: LikesApi = retrofit.create()
private val discoverApi: DiscoverApi = retrofit.create()
private val quarantineApi: QuarantineApi = retrofit.create() private val quarantineApi: QuarantineApi = retrofit.create()
private val playlistsApi: PlaylistsApi = retrofit.create() private val playlistsApi: PlaylistsApi = retrofit.create()
private val eventsApi: EventsApi = retrofit.create() private val eventsApi: EventsApi = retrofit.create()
private val requestsApi: RequestsApi = retrofit.create()
private val playbackErrorsApi: PlaybackErrorsApi = retrofit.create() private val playbackErrorsApi: PlaybackErrorsApi = retrofit.create()
private val meApi: MeApi = retrofit.create() private val meApi: MeApi = retrofit.create()
private val notificationsApi: NotificationsApi = retrofit.create() private val notificationsApi: NotificationsApi = retrofit.create()
@@ -98,6 +103,11 @@ class MutationReplayer @Inject constructor(
.distinctUntilChanged() .distinctUntilChanged()
.collect { drainSafe() } .collect { drainSafe() }
} }
scope.launch {
accountCache.ownedBySignedInUser
.filter { it }
.collect { drainSafe() }
}
// Server-reachable-again: replay queued writes the moment the // Server-reachable-again: replay queued writes the moment the
// health signal recovers, so an offline→online transition mid- // health signal recovers, so an offline→online transition mid-
// session doesn't wait for the next cold start / re-auth. // session doesn't wait for the next cold start / re-auth.
@@ -121,21 +131,40 @@ class MutationReplayer @Inject constructor(
} }
private suspend fun drain() { private suspend fun drain() {
// Another account's writes must not go out under this session.
if (!accountCache.ownedBySignedInUser.value) return
val rows = dao.getAll() val rows = dao.getAll()
// Collapse superseded toggles (likes, suggestion snoozes): only the // Collapse superseded toggles (likes, settings): only the latest
// latest desired state per entity is replayed; older toggles for the // desired state per entity is replayed; older toggles for the same
// same entity are dropped unsent. Without this, partial-failure + // entity are dropped unsent. Without this, partial-failure +
// differential retry could replay an older toggle last and invert the // 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) val superseded = supersededToggleIds(rows, json)
// A playlist's changes go out in the order they were made: once one
// has to wait, the rest for that list wait behind it, so an add
// never reaches the server before the create of its list.
val waiting = HashSet<String>()
for (row in rows) { for (row in rows) {
if (row.id in superseded) { replayRow(row, superseded = row.id in superseded, waiting = waiting)
dao.delete(row.id) }
continue }
}
when (outcomeFor(row)) { /**
* Sends one row, or drops it when a later row has superseded it, or
* leaves it queued when an earlier change to the same playlist is still
* waiting. A row that has to retry makes its playlist wait in [waiting].
*/
private suspend fun replayRow(row: CachedMutationEntity, superseded: Boolean, waiting: MutableSet<String>) {
val playlistId = playlistIdOf(row, json)
when {
superseded -> dao.delete(row.id)
playlistId != null && playlistId in waiting -> Unit
else -> when (outcomeFor(row)) {
Outcome.SENT, Outcome.DROP -> dao.delete(row.id) Outcome.SENT, Outcome.DROP -> dao.delete(row.id)
Outcome.RETRY -> dao.recordAttempt(row.id, Clock.System.now()) Outcome.RETRY -> {
dao.recordAttempt(row.id, Clock.System.now())
playlistId?.let(waiting::add)
}
} }
} }
} }
@@ -152,10 +181,8 @@ class MutationReplayer @Inject constructor(
Outcome.RETRY Outcome.RETRY
} }
/** 4xx are permanent except the two "retry me" statuses. */ /** A refusal that a replay would only get again ([isRetryableStatus]'s complement). */
private fun isPermanent(code: Int): Boolean = private fun isPermanent(code: Int): Boolean = !isRetryableStatus(code)
code in HTTP_CLIENT_ERR_MIN..HTTP_CLIENT_ERR_MAX &&
code != HTTP_TIMEOUT && code != HTTP_TOO_MANY
/** /**
* Returns the outcome of replaying one row. SENT on a 2xx; DROP for an * Returns the outcome of replaying one row. SENT on a 2xx; DROP for an
@@ -164,15 +191,18 @@ class MutationReplayer @Inject constructor(
*/ */
private suspend fun dispatch(row: CachedMutationEntity): Outcome = when (row.kind) { private suspend fun dispatch(row: CachedMutationEntity): Outcome = when (row.kind) {
MutationKind.LIKE_TOGGLE -> dispatchLikeToggle(row.payload) MutationKind.LIKE_TOGGLE -> dispatchLikeToggle(row.payload)
MutationKind.REQUEST_CREATE -> dispatchRequestCreate(row.payload)
MutationKind.QUARANTINE_UNFLAG -> dispatchQuarantineUnflag(row.payload) MutationKind.QUARANTINE_UNFLAG -> dispatchQuarantineUnflag(row.payload)
MutationKind.PLAYLIST_APPEND -> dispatchPlaylistAppend(row.payload) MutationKind.PLAYLIST_APPEND,
MutationKind.PLAYLIST_CREATE,
MutationKind.PLAYLIST_UPDATE,
MutationKind.PLAYLIST_DELETE,
MutationKind.PLAYLIST_REMOVE_TRACK,
MutationKind.PLAYLIST_REORDER,
-> dispatchPlaylist(row)
MutationKind.QUARANTINE_FLAG -> dispatchQuarantineFlag(row.payload) MutationKind.QUARANTINE_FLAG -> dispatchQuarantineFlag(row.payload)
MutationKind.PLAY_OFFLINE -> dispatchPlayOffline(row.payload) MutationKind.PLAY_OFFLINE -> dispatchPlayOffline(row.payload)
MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload) MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload)
MutationKind.REQUEST_CANCEL -> dispatchRequestCancel(row.payload)
MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload) MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload)
MutationKind.SUGGESTION_SNOOZE_TOGGLE -> dispatchSuggestionSnoozeToggle(row.payload)
MutationKind.NORMALIZATION_SET -> dispatchNormalizationSet(row.payload) MutationKind.NORMALIZATION_SET -> dispatchNormalizationSet(row.payload)
MutationKind.NOTIFICATION_READ, MutationKind.NOTIFICATION_READ,
MutationKind.NOTIFICATIONS_READ_ALL, MutationKind.NOTIFICATIONS_READ_ALL,
@@ -206,34 +236,49 @@ class MutationReplayer @Inject constructor(
return Outcome.SENT 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 { private suspend fun dispatchQuarantineUnflag(payload: String): Outcome {
val decoded = json.decodeFromString(QuarantineUnflagPayload.serializer(), payload) val decoded = json.decodeFromString(QuarantineUnflagPayload.serializer(), payload)
quarantineApi.unflag(decoded.trackId) quarantineApi.unflag(decoded.trackId)
return Outcome.SENT return Outcome.SENT
} }
private suspend fun dispatchPlaylistAppend(payload: String): Outcome { /**
val decoded = json.decodeFromString(PlaylistAppendPayload.serializer(), payload) * A listener's own playlists, split out to keep [dispatch] simple. A
playlistsApi.appendTracks( * 404 or 409 is a 4xx, so DROP: the list is gone, or has changed since,
playlistId = decoded.playlistId, * and nothing is left to do.
body = AppendTracksRequest(trackIds = decoded.trackIds), */
) private suspend fun dispatchPlaylist(row: CachedMutationEntity): Outcome {
val payload = row.payload
when (row.kind) {
MutationKind.PLAYLIST_APPEND -> {
val p = json.decodeFromString(PlaylistAppendPayload.serializer(), payload)
playlistsApi.appendTracks(
p.playlistId,
AppendTracksRequest(trackIds = p.trackIds, requestId = p.requestId),
)
}
MutationKind.PLAYLIST_CREATE -> {
val p = json.decodeFromString(PlaylistCreatePayload.serializer(), payload)
playlistsApi.create(CreatePlaylistRequest(id = p.id, name = p.name, isPublic = p.isPublic))
}
MutationKind.PLAYLIST_UPDATE -> {
val p = json.decodeFromString(PlaylistUpdatePayload.serializer(), payload)
playlistsApi.update(p.playlistId, UpdatePlaylistRequest(name = p.name, isPublic = p.isPublic))
}
MutationKind.PLAYLIST_DELETE -> {
val p = json.decodeFromString(PlaylistDeletePayload.serializer(), payload)
playlistsApi.delete(p.playlistId)
}
MutationKind.PLAYLIST_REMOVE_TRACK -> {
val p = json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), payload)
playlistsApi.removeTrack(p.playlistId, p.position, p.trackId)
}
MutationKind.PLAYLIST_REORDER -> {
val p = json.decodeFromString(PlaylistReorderPayload.serializer(), payload)
playlistsApi.reorder(p.playlistId, ReorderTracksRequest(trackIds = p.trackIds))
}
else -> return Outcome.DROP
}
return Outcome.SENT return Outcome.SENT
} }
@@ -275,30 +320,6 @@ class MutationReplayer @Inject constructor(
return Outcome.SENT 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 * Sends the queued normalization preference. The device already shows
* it, so the server's echo is not written back: a change made since the * it, so the server's echo is not written back: a change made since the
@@ -342,19 +363,12 @@ class MutationReplayer @Inject constructor(
) )
return Outcome.SENT return Outcome.SENT
} }
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
}
} }
/** /**
* Row ids of desired-state toggles superseded by a later toggle for the same * 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 * 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 * normalization preference — because
* replaying a stale one last would invert the final state. * replaying a stale one last would invert the final state.
* *
@@ -388,14 +402,15 @@ private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when (
json.decodeFromString(LikeTogglePayload.serializer(), row.payload) json.decodeFromString(LikeTogglePayload.serializer(), row.payload)
}.getOrNull()?.let { "${row.kind}:${it.entityType}:${it.entityId}" } }.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 { MutationKind.NOTIFICATION_SETTING_SET -> runCatching {
json.decodeFromString(NotificationSettingPayload.serializer(), row.payload) json.decodeFromString(NotificationSettingPayload.serializer(), row.payload)
}.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" } }.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" }
// A reorder is the list's whole new order, so only the last one counts.
MutationKind.PLAYLIST_REORDER -> runCatching {
json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload)
}.getOrNull()?.let { "${row.kind}:${it.playlistId}" }
// One preference per user, so every normalization row shares one key. // One preference per user, so every normalization row shares one key.
MutationKind.NORMALIZATION_SET -> runCatching { MutationKind.NORMALIZATION_SET -> runCatching {
json.decodeFromString(NormalizationPrefs.serializer(), row.payload) json.decodeFromString(NormalizationPrefs.serializer(), row.payload)
@@ -403,3 +418,25 @@ private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when (
else -> null else -> null
} }
/**
* The playlist a queued row changes, or null for a row that isn't a
* playlist change (or won't decode, which its dispatcher then DROPs).
*/
internal fun playlistIdOf(row: CachedMutationEntity, json: Json): String? = runCatching {
when (row.kind) {
MutationKind.PLAYLIST_APPEND ->
json.decodeFromString(PlaylistAppendPayload.serializer(), row.payload).playlistId
MutationKind.PLAYLIST_CREATE ->
json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload).id
MutationKind.PLAYLIST_UPDATE ->
json.decodeFromString(PlaylistUpdatePayload.serializer(), row.payload).playlistId
MutationKind.PLAYLIST_DELETE ->
json.decodeFromString(PlaylistDeletePayload.serializer(), row.payload).playlistId
MutationKind.PLAYLIST_REMOVE_TRACK ->
json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), row.payload).playlistId
MutationKind.PLAYLIST_REORDER ->
json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload).playlistId
else -> null
}
}.getOrNull()
@@ -0,0 +1,58 @@
package com.fabledsword.minstrel.cache.mutations
import kotlinx.coroutines.CancellationException
import retrofit2.HttpException
/** Whether a write reached the server, waits in the offline queue, or was refused. */
enum class WriteOutcome { Synced, Queued, Refused }
private const val HTTP_CLIENT_ERR_MIN = 400
private const val HTTP_CLIENT_ERR_MAX = 499
private const val HTTP_TIMEOUT = 408
private const val HTTP_TOO_MANY = 429
/**
* Whether a server's HTTP error is worth trying again later: a 5xx (the
* server's trouble), 408 (timed out) or 429 (too many requests). Any other
* 4xx is the server saying no, and asking again gets the same answer.
* The replayer and [sendOrQueue] both decide by this.
*/
fun isRetryableStatus(code: Int): Boolean =
code !in HTTP_CLIENT_ERR_MIN..HTTP_CLIENT_ERR_MAX || code == HTTP_TIMEOUT || code == HTTP_TOO_MANY
/**
* Sends a write now, or queues it for the replayer when the server can't
* take it yet. The one rule every offline-first repository write follows:
*
* - The server took it: [WriteOutcome.Synced].
* - No answer (offline, a dropped connection), or an error worth retrying
* ([isRetryableStatus]): [queue] runs and the result is Queued.
* - The server refused it (any other 4xx): nothing is queued, since a
* replay would be refused too. [onRefused] decides what the caller sees;
* by default the refusal is thrown, so the caller can say why.
*
* Cancellation passes through.
*/
suspend fun sendOrQueue(
send: suspend () -> Unit,
queue: suspend () -> Unit,
onRefused: (HttpException) -> WriteOutcome = { throw it },
): WriteOutcome =
try {
send()
WriteOutcome.Synced
} catch (e: CancellationException) {
throw e
} catch (e: HttpException) {
if (isRetryableStatus(e.code())) {
queue()
WriteOutcome.Queued
} else {
onRefused(e)
}
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
queue()
WriteOutcome.Queued
}
@@ -70,6 +70,9 @@ class DiagnosticsUploader @Inject constructor(
/** Coalesces concurrent triggers via tryLock — a drain in flight wins. */ /** Coalesces concurrent triggers via tryLock — a drain in flight wins. */
private suspend fun drainSafe() { 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 val clientId = authStore.clientId.value
// Signed out / no client id yet → nothing to do. Single guard keeps // Signed out / no client id yet → nothing to do. Single guard keeps
// the return count within the detekt gate. // 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) }
}
}
@@ -36,7 +36,6 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHost
@@ -50,24 +49,25 @@ import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController import androidx.navigation.NavHostController
import coil3.compose.AsyncImage
import com.composables.icons.lucide.Heart import com.composables.icons.lucide.Heart
import com.composables.icons.lucide.History import com.composables.icons.lucide.History
import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Music
import com.fabledsword.minstrel.api.ErrorCopy import com.fabledsword.minstrel.api.ErrorCopy
import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.connectivity.recoveries
import com.fabledsword.minstrel.home.data.HomeRepository import com.fabledsword.minstrel.home.data.HomeRepository
import com.fabledsword.minstrel.library.data.LibraryRepository import com.fabledsword.minstrel.library.data.LibraryRepository
import com.fabledsword.minstrel.library.data.playAlbumFromStart
import com.fabledsword.minstrel.library.data.shufflePlayArtist
import com.fabledsword.minstrel.library.widgets.AlbumCard import com.fabledsword.minstrel.library.widgets.AlbumCard
import com.fabledsword.minstrel.library.widgets.ArtistCard import com.fabledsword.minstrel.library.widgets.ArtistCard
import com.fabledsword.minstrel.models.AlbumRef import com.fabledsword.minstrel.models.AlbumRef
@@ -80,11 +80,18 @@ import com.fabledsword.minstrel.nav.AlbumDetail
import com.fabledsword.minstrel.nav.ArtistDetail import com.fabledsword.minstrel.nav.ArtistDetail
import com.fabledsword.minstrel.nav.Home import com.fabledsword.minstrel.nav.Home
import com.fabledsword.minstrel.nav.PlaylistDetail import com.fabledsword.minstrel.nav.PlaylistDetail
import com.fabledsword.minstrel.playlists.assignShelfCovers
import com.fabledsword.minstrel.playlists.byShelfRank
import com.fabledsword.minstrel.playlists.data.PlaylistsRepository import com.fabledsword.minstrel.playlists.data.PlaylistsRepository
import com.fabledsword.minstrel.playlists.data.playPlaylistShuffled import com.fabledsword.minstrel.playlists.data.playPlaylistShuffled
import com.fabledsword.minstrel.playlists.shelfMeta
import com.fabledsword.minstrel.playlists.widgets.OfflinePoolCard import com.fabledsword.minstrel.playlists.widgets.OfflinePoolCard
import com.fabledsword.minstrel.playlists.widgets.PlaylistCard import com.fabledsword.minstrel.playlists.widgets.GenreBandCard
import com.fabledsword.minstrel.playlists.widgets.PlaceholderShape
import com.fabledsword.minstrel.playlists.widgets.PlaylistPlaceholderCard import com.fabledsword.minstrel.playlists.widgets.PlaylistPlaceholderCard
import com.fabledsword.minstrel.playlists.widgets.SongsLikeCard
import com.fabledsword.minstrel.playlists.widgets.TallPlaylistCard
import com.fabledsword.minstrel.playlists.widgets.WidePlaylistCard
import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.UpdateVeilController import com.fabledsword.minstrel.shared.UpdateVeilController
import com.fabledsword.minstrel.shared.VeilOutcome import com.fabledsword.minstrel.shared.VeilOutcome
@@ -102,6 +109,9 @@ import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile
import com.fabledsword.minstrel.shared.widgets.SkeletonArtistTile import com.fabledsword.minstrel.shared.widgets.SkeletonArtistTile
import com.fabledsword.minstrel.shared.widgets.SkeletonSectionHeader import com.fabledsword.minstrel.shared.widgets.SkeletonSectionHeader
import com.fabledsword.minstrel.shared.widgets.TrackCoverThumb
import com.fabledsword.minstrel.update.ui.UpdateNotices
import com.fabledsword.minstrel.update.ui.UpdateViewModel
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.async import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
@@ -266,44 +276,18 @@ class HomeViewModel @Inject constructor(
*/ */
suspend fun playAlbum(albumId: String) { suspend fun playAlbum(albumId: String) {
viewModelScope.launch { viewModelScope.launch {
try { playAlbumFromStart(albumId, libraryRepository, player) { snackbarMessages.trySend(it) }
val detail = libraryRepository.refreshAlbumDetail(albumId)
if (detail.tracks.isEmpty()) {
snackbarMessages.trySend("This album has no tracks to play.")
} else {
player.setQueue(detail.tracks, initialIndex = 0, source = "album:$albumId")
}
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
snackbarMessages.trySend(
"Couldn't start playback: ${ErrorCopy.fromThrowable(e)}",
)
}
}.join() }.join()
} }
/** /**
* Tap the artist play-button overlay: fetch every track across the * Tap the artist play-button overlay: fetch every track across the
* artist's albums, Fisher-Yates shuffle, play from index 0. Empty + * artist's albums, shuffle, play from index 0 (shufflePlayArtist, as
* error semantics follow [playAlbum]. * the Artist page's Play does).
*/ */
suspend fun playArtistShuffled(artistId: String) { suspend fun playArtistShuffled(artistId: String) {
viewModelScope.launch { viewModelScope.launch {
try { shufflePlayArtist(artistId, libraryRepository, player) { snackbarMessages.trySend(it) }
val tracks = libraryRepository.fetchArtistTracks(artistId).shuffled()
if (tracks.isEmpty()) {
snackbarMessages.trySend("This artist has no tracks to play.")
} else {
player.setQueue(tracks, initialIndex = 0, source = "artist:$artistId")
}
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
snackbarMessages.trySend(
"Couldn't start playback: ${ErrorCopy.fromThrowable(e)}",
)
}
}.join() }.join()
} }
@@ -553,6 +537,7 @@ class HomeViewModel @Inject constructor(
fun HomeScreen( fun HomeScreen(
navController: NavHostController, navController: NavHostController,
viewModel: HomeViewModel = hiltViewModel(), viewModel: HomeViewModel = hiltViewModel(),
updates: UpdateViewModel = hiltViewModel(),
) { ) {
val snackbarHostState = remember { SnackbarHostState() } val snackbarHostState = remember { SnackbarHostState() }
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
@@ -575,7 +560,11 @@ fun HomeScreen(
val offline by viewModel.offline.collectAsStateWithLifecycle() val offline by viewModel.offline.collectAsStateWithLifecycle()
val updating by viewModel.isUpdating.collectAsStateWithLifecycle() val updating by viewModel.isUpdating.collectAsStateWithLifecycle()
PullToRefreshScaffold( PullToRefreshScaffold(
onRefresh = { viewModel.refreshFromPull() }, onRefresh = {
// A pull asks about a newer app too, so one shows up at once.
updates.check()
viewModel.refreshFromPull()
},
modifier = Modifier.fillMaxSize().padding(inner), modifier = Modifier.fillMaxSize().padding(inner),
) { ) {
Box(Modifier.fillMaxSize()) { Box(Modifier.fillMaxSize()) {
@@ -590,6 +579,7 @@ fun HomeScreen(
// hide behind an "Updating your mixes…" wipe that stays up // hide behind an "Updating your mixes…" wipe that stays up
// until the screen has actually stopped moving. // until the screen has actually stopped moving.
UpdatingVeil(visible = updating) UpdatingVeil(visible = updating)
UpdateNotices(updates)
} }
} }
} }
@@ -755,6 +745,7 @@ private fun HomeSuccessContent(
// pool cards lead the row. Songs-like has its own row below. // pool cards lead the row. Songs-like has its own row below.
PlaylistsRow( PlaylistsRow(
title = "Playlists", title = "Playlists",
shape = ShelfShape.WIDE,
rowItems = buildPlaylistsRow(sections.playlists, systemStatus, offline), rowItems = buildPlaylistsRow(sections.playlists, systemStatus, offline),
offline = offline, offline = offline,
onPlaylistClick = onPlaylistClick, onPlaylistClick = onPlaylistClick,
@@ -773,6 +764,13 @@ private fun HomeSuccessContent(
onPlayPool = onPlayPool, onPlayPool = onPlayPool,
onPlayPlaylist = onPlayPlaylist, onPlayPlaylist = onPlayPlaylist,
) )
genreMixSection(
playlists = sections.playlists,
offline = offline,
onPlaylistClick = onPlaylistClick,
onPlayPool = onPlayPool,
onPlayPlaylist = onPlayPlaylist,
)
youMightLikeSection( youMightLikeSection(
albums = sections.youMightLikeAlbums, albums = sections.youMightLikeAlbums,
artists = sections.youMightLikeArtists, artists = sections.youMightLikeArtists,
@@ -816,6 +814,33 @@ private fun LazyListScope.songsLikeSection(
item { item {
PlaylistsRow( PlaylistsRow(
title = "Songs like…", title = "Songs like…",
shape = ShelfShape.ROUND,
rowItems = rowItems,
offline = offline,
onPlaylistClick = onPlaylistClick,
onPlayPool = onPlayPool,
onPlayPlaylist = onPlayPlaylist,
)
}
}
/**
* 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",
shape = ShelfShape.BAND,
rowItems = rowItems, rowItems = rowItems,
offline = offline, offline = offline,
onPlaylistClick = onPlaylistClick, onPlaylistClick = onPlaylistClick,
@@ -1080,28 +1105,41 @@ private fun AlbumsRow(
items(items = albums, key = { it.id }) { tile -> items(items = albums, key = { it.id }) { tile ->
val album = tile.value val album = tile.value
if (album == null) { if (album == null) {
SkeletonAlbumTile() SkeletonAlbumTile(artSize = SECONDARY_ALBUM_ART)
} else { } else {
AlbumCard( AlbumCard(
album = album, album = album,
onClick = { onAlbumClick(album.id) }, onClick = { onAlbumClick(album.id) },
onPlay = { onPlayAlbum(album.id) }, onPlay = { onPlayAlbum(album.id) },
artSize = SECONDARY_ALBUM_ART,
) )
} }
} }
} }
} }
/**
* A shelf of playlist tiles in one [shape]. Each tile gets cover albums no
* tile before it already shows (assignShelfCovers), and the size and refresh
* time the shelf's mixes share go beside the title once (shelfMeta).
*/
@Composable @Composable
private fun PlaylistsRow( private fun PlaylistsRow(
title: String, title: String,
shape: ShelfShape,
rowItems: List<PlaylistRowItem>, rowItems: List<PlaylistRowItem>,
offline: Boolean, offline: Boolean,
onPlaylistClick: (String) -> Unit, onPlaylistClick: (String) -> Unit,
onPlayPool: (OfflinePoolKind) -> Unit, onPlayPool: (OfflinePoolKind) -> Unit,
onPlayPlaylist: suspend (PlaylistRef) -> Unit, onPlayPlaylist: suspend (PlaylistRef) -> Unit,
) { ) {
HorizontalScrollRow(title = title) { val reals = rowItems.filterIsInstance<PlaylistRowItem.Real>().map { it.playlist }
val covers = remember(reals, shape) {
reals.map { it.id }.zip(assignShelfCovers(reals, shape.coversPerTile)).toMap()
}
val meta = remember(reals) { shelfMeta(reals) }
val tallWidth = tallCardWidth(shape)
HorizontalScrollRow(title = title, meta = meta) {
itemsIndexed(items = rowItems) { _, item -> itemsIndexed(items = rowItems) { _, item ->
when (item) { when (item) {
is PlaylistRowItem.OfflinePool -> OfflinePoolCard( is PlaylistRowItem.OfflinePool -> OfflinePoolCard(
@@ -1109,28 +1147,78 @@ private fun PlaylistsRow(
icon = iconForPool(item.kind), icon = iconForPool(item.kind),
onClick = { onPlayPool(item.kind) }, onClick = { onPlayPool(item.kind) },
) )
is PlaylistRowItem.Real -> { is PlaylistRowItem.Real -> ShelfTile(
shape = shape,
tallWidth = tallWidth,
playlist = item.playlist,
covers = covers[item.playlist.id].orEmpty(),
// Greyed offline when the tile needs the live server or // Greyed offline when the tile needs the live server or
// isn't fully cached — dimmed but still tappable into the // isn't fully cached — dimmed but still tappable into the
// detail to shuffle whatever subset is cached. // detail to shuffle whatever subset is cached.
val greyed = offline && item.playlist.unavailableOffline greyed = offline && item.playlist.unavailableOffline,
PlaylistCard( onClick = { onPlaylistClick(item.playlist.id) },
playlist = item.playlist, onPlay = { onPlayPlaylist(item.playlist) },
onClick = { onPlaylistClick(item.playlist.id) }, )
onPlay = { onPlayPlaylist(item.playlist) },
playEnabled = item.playlist.trackCount > 0 && !greyed,
greyed = greyed,
)
}
is PlaylistRowItem.Placeholder -> PlaylistPlaceholderCard( is PlaylistRowItem.Placeholder -> PlaylistPlaceholderCard(
label = item.label, label = item.label,
variant = item.variant, variant = item.variant,
shape = if (tallWidth != null) PlaceholderShape.TALL else shape.placeholder,
modifier = if (tallWidth != null) Modifier.width(tallWidth) else Modifier,
) )
} }
} }
} }
} }
/**
* On a narrow screen (a phone held upright) the wide shelf would leave one
* playlist in view, so it switches to tall cards sized for two whole cards
* and a glimpse of the third. Null keeps the shelf's own shape.
*/
@Composable
private fun tallCardWidth(shape: ShelfShape): Dp? {
val screen = LocalConfiguration.current.screenWidthDp.dp
return if (shape == ShelfShape.WIDE && screen < COMPACT_WIDTH) {
// Row padding at the start, two gaps between cards, the third's glimpse.
(screen - ROW_EDGE - ROW_GAP * 2 - NEXT_CARD_GLIMPSE) / 2
} else {
null
}
}
/** One playlist tile in its shelf's shape; a wide one turns tall at [tallWidth]. */
@Composable
private fun ShelfTile(
shape: ShelfShape,
tallWidth: Dp?,
playlist: PlaylistRef,
covers: List<String>,
greyed: Boolean,
onClick: () -> Unit,
onPlay: suspend () -> Unit,
) {
val playEnabled = playlist.trackCount > 0
when {
tallWidth != null -> TallPlaylistCard(playlist, covers, tallWidth, onClick, onPlay, playEnabled, greyed)
shape == ShelfShape.WIDE -> WidePlaylistCard(playlist, covers, onClick, onPlay, playEnabled, greyed)
shape == ShelfShape.ROUND -> SongsLikeCard(playlist, covers, onClick, onPlay, playEnabled, greyed)
else -> GenreBandCard(playlist, covers, onClick, onPlay, playEnabled, greyed)
}
}
/**
* The tile shape a Home playlist shelf uses, so shelves read apart at a
* glance: wide cards for the main mixes and playlists, circles for Songs
* like (the shape artists have everywhere), colour bands with a fan of
* covers for genres. [coversPerTile] is how many distinct covers a tile
* shows; [placeholder] is the shape a not-yet-built mix takes on the shelf.
*/
internal enum class ShelfShape(val coversPerTile: Int, val placeholder: PlaceholderShape) {
WIDE(coversPerTile = 1, placeholder = PlaceholderShape.WIDE),
ROUND(coversPerTile = 1, placeholder = PlaceholderShape.ROUND),
BAND(coversPerTile = 3, placeholder = PlaceholderShape.SQUARE),
}
private fun iconForPool(kind: OfflinePoolKind) = when (kind) { private fun iconForPool(kind: OfflinePoolKind) = when (kind) {
OfflinePoolKind.RECENTLY_PLAYED -> Lucide.History OfflinePoolKind.RECENTLY_PLAYED -> Lucide.History
OfflinePoolKind.LIKED -> Lucide.Heart OfflinePoolKind.LIKED -> Lucide.Heart
@@ -1225,6 +1313,25 @@ internal fun buildSongsLikeRow(
} }
} }
/**
* Builds the "Your genres" row: every genre mix, the genres the listener
* plays most first ([byShelfRank], the server's shelf_rank). 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" }
.sortedWith(byShelfRank)
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). * Curated real-playlist order (system primaries, then secondary, then user).
* Must mirror [buildOnlineRow]'s slot order — the offline row reuses this and * Must mirror [buildOnlineRow]'s slot order — the offline row reuses this and
@@ -1255,6 +1362,20 @@ private fun variantFor(slot: String, s: SystemPlaylistsStatus): String = when {
// once generated, are shown in full, uncapped. // once generated, are shown in full, uncapped.
private const val SONGS_LIKE_PLACEHOLDER_SLOTS = 3 private const val SONGS_LIKE_PLACEHOLDER_SLOTS = 3
// Below this width (a phone held upright) the Playlists shelf uses tall
// cards; the 600dp line is Material's compact width class.
private val COMPACT_WIDTH = 600.dp
private val ROW_EDGE = 16.dp
private val ROW_GAP = 8.dp
private val NEXT_CARD_GLIMPSE = 20.dp
// Home's shelves step down in size below the playlists, as on web: Recently
// added keeps the full 144dp album cover, the You might like and Rediscover
// album shelves are smaller, and artist shelves smaller again. The ratios
// follow web's 176 / 144 / 128px minimum tile widths.
private val SECONDARY_ALBUM_ART = 120.dp
private val ARTIST_ART = 104.dp
/** /**
* The 5 system playlist kinds the server generates that aren't pinned * The 5 system playlist kinds the server generates that aren't pinned
* to Home's primary slots. Order matches `systemPlaylistRegistry` in * to Home's primary slots. Order matches `systemPlaylistRegistry` in
@@ -1279,12 +1400,13 @@ private fun ArtistsRow(
items(items = artists, key = { it.id }) { tile -> items(items = artists, key = { it.id }) { tile ->
val artist = tile.value val artist = tile.value
if (artist == null) { if (artist == null) {
SkeletonArtistTile() SkeletonArtistTile(artSize = ARTIST_ART)
} else { } else {
ArtistCard( ArtistCard(
artist = artist, artist = artist,
onClick = { onArtistClick(artist.id) }, onClick = { onArtistClick(artist.id) },
onPlay = { onPlayArtist(artist.id) }, onPlay = { onPlayArtist(artist.id) },
artSize = ARTIST_ART,
) )
} }
} }
@@ -1393,29 +1515,11 @@ private fun CompactTrackTile(
.padding(horizontal = 8.dp, vertical = 4.dp), .padding(horizontal = 8.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
) { ) {
Box( TrackCoverThumb(
modifier = Modifier coverUrl = track.coverUrl,
.size(MOST_PLAYED_COVER_DP.dp) contentDescription = track.title,
.clip(RoundedCornerShape(4.dp)) size = MOST_PLAYED_COVER_DP.dp,
.background(MaterialTheme.colorScheme.surfaceVariant), )
contentAlignment = Alignment.Center,
) {
if (track.coverUrl.isEmpty()) {
Icon(
imageVector = Lucide.Music,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(20.dp),
)
} else {
AsyncImage(
model = track.coverUrl,
contentDescription = track.title,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
)
}
}
Spacer(Modifier.width(8.dp)) Spacer(Modifier.width(8.dp))
Column( Column(
modifier = Modifier modifier = Modifier
@@ -6,6 +6,7 @@ import com.fabledsword.minstrel.cache.db.entities.CachedTrackEntity
import com.fabledsword.minstrel.models.AlbumRef import com.fabledsword.minstrel.models.AlbumRef
import com.fabledsword.minstrel.models.ArtistRef import com.fabledsword.minstrel.models.ArtistRef
import com.fabledsword.minstrel.models.TrackRef import com.fabledsword.minstrel.models.TrackRef
import com.fabledsword.minstrel.models.artistImagePath
import com.fabledsword.minstrel.models.wire.AlbumDetailWire import com.fabledsword.minstrel.models.wire.AlbumDetailWire
import com.fabledsword.minstrel.models.wire.AlbumWire import com.fabledsword.minstrel.models.wire.AlbumWire
import com.fabledsword.minstrel.models.wire.ArtistDetailWire import com.fabledsword.minstrel.models.wire.ArtistDetailWire
@@ -66,11 +67,14 @@ fun AlbumDetailWire.toAlbumEntity(): CachedAlbumEntity =
// source of truth for cache-first reads; mapping to a domain type here // source of truth for cache-first reads; mapping to a domain type here
// keeps Room types out of the UI layer. // keeps Room types out of the UI layer.
// An artist whose picture the server fetched shows it; the rest fall back
// to an album cover through [coverAlbumId].
fun CachedArtistEntity.toDomain(coverAlbumId: String = ""): ArtistRef = fun CachedArtistEntity.toDomain(coverAlbumId: String = ""): ArtistRef =
ArtistRef( ArtistRef(
id = id, id = id,
name = name, name = name,
sortName = sortName, sortName = sortName,
coverUrl = if (artistThumbPath.isNullOrEmpty()) "" else artistImagePath(id),
coverAlbumId = coverAlbumId, coverAlbumId = coverAlbumId,
) )
@@ -0,0 +1,58 @@
package com.fabledsword.minstrel.library.data
import com.fabledsword.minstrel.api.ErrorCopy
import com.fabledsword.minstrel.player.PlayerController
import kotlinx.coroutines.CancellationException
/**
* Fetch an artist's tracks across all their albums and play them shuffled.
* Pressing Play on an artist means "shuffle this artist", not "play album
* by album in tracklist order". Home's artist tiles and the Artist page's
* Play button both start here, so they behave and word their messages
* the same.
*
* An empty artist or a failed fetch reaches [onMessage] for the caller to
* show as a snackbar.
*/
suspend fun shufflePlayArtist(
artistId: String,
repository: LibraryRepository,
player: PlayerController,
onMessage: (String) -> Unit,
) = playOrSay(onMessage, empty = "This artist has no tracks to play.") {
val tracks = repository.fetchArtistTracks(artistId).shuffled()
if (tracks.isNotEmpty()) player.setQueue(tracks, initialIndex = 0, source = "artist:$artistId")
tracks.isNotEmpty()
}
/**
* Fetch an album and play it from its first track, in tracklist order.
* For an album tile's play button, where the album isn't loaded yet.
*/
suspend fun playAlbumFromStart(
albumId: String,
repository: LibraryRepository,
player: PlayerController,
onMessage: (String) -> Unit,
) = playOrSay(onMessage, empty = "This album has no tracks to play.") {
val tracks = repository.refreshAlbumDetail(albumId).tracks
if (tracks.isNotEmpty()) player.setQueue(tracks, initialIndex = 0, source = "album:$albumId")
tracks.isNotEmpty()
}
/** Runs [start]; says [empty] when it found nothing to play, and why when it failed. */
private suspend fun playOrSay(
onMessage: (String) -> Unit,
empty: String,
start: suspend () -> Boolean,
) {
try {
if (!start()) onMessage(empty)
} catch (e: CancellationException) {
throw e
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
onMessage("Couldn't start playback: ${ErrorCopy.fromThrowable(e)}")
}
}
@@ -4,7 +4,6 @@ package com.fabledsword.minstrel.library.ui
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
@@ -17,7 +16,6 @@ import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
@@ -34,7 +32,6 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
@@ -51,15 +48,16 @@ import com.fabledsword.minstrel.models.TrackRef
import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.AlbumDetail
import com.fabledsword.minstrel.nav.ArtistDetail import com.fabledsword.minstrel.nav.ArtistDetail
import com.fabledsword.minstrel.shared.formatDuration import com.fabledsword.minstrel.shared.formatDuration
import com.fabledsword.minstrel.shared.plural
import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon
import com.fabledsword.minstrel.shared.widgets.CoverTile
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.TrackRow
import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LikeButton import com.fabledsword.minstrel.shared.widgets.LikeButton
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ServerImage
import com.fabledsword.minstrel.shared.widgets.SkeletonTrackRow import com.fabledsword.minstrel.shared.widgets.SkeletonTrackRow
import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton
import com.fabledsword.minstrel.theme.FabledSwordFlatTokens
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -267,32 +265,17 @@ private fun AlbumHeader(
@Composable @Composable
private fun AlbumCover(album: AlbumRef) { private fun AlbumCover(album: AlbumRef) {
Box( CoverTile(
modifier = Modifier url = album.displayCoverUrl,
.size(120.dp) contentDescription = album.title,
.clip(RoundedCornerShape(FabledSwordFlatTokens.radiusSm)) size = 120.dp,
.background(MaterialTheme.colorScheme.surfaceVariant), background = MaterialTheme.colorScheme.surfaceVariant,
contentAlignment = Alignment.Center, fallback = { CoverFallbackIcon(Lucide.Disc3) },
) { )
if (album.id.isEmpty()) {
Icon(
imageVector = Lucide.Disc3,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(56.dp),
)
} else {
ServerImage(
url = album.displayCoverUrl,
contentDescription = album.title,
modifier = Modifier.fillMaxSize(),
)
}
}
} }
private fun trackCountLine(album: AlbumRef): String { private fun trackCountLine(album: AlbumRef): String {
val tracks = if (album.trackCount == 1) "1 track" else "${album.trackCount} tracks" val tracks = plural(album.trackCount, "track", "tracks")
return if (album.year != null) "$tracks · ${album.year}" else tracks return if (album.year != null) "$tracks · ${album.year}" else tracks
} }
@@ -9,6 +9,7 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.connectivity.recoveries
import com.fabledsword.minstrel.library.data.LibraryRepository import com.fabledsword.minstrel.library.data.LibraryRepository
import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.likes.data.LikesRepository
import com.fabledsword.minstrel.likes.data.toggleTrackLike
import com.fabledsword.minstrel.models.AlbumDetailRef import com.fabledsword.minstrel.models.AlbumDetailRef
import com.fabledsword.minstrel.models.AlbumRef import com.fabledsword.minstrel.models.AlbumRef
import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.AlbumDetail
@@ -133,9 +134,6 @@ class AlbumDetailViewModel @Inject constructor(
} }
fun toggleLikeTrack(trackId: String) { fun toggleLikeTrack(trackId: String) {
val desired = trackId !in likedTrackIds.value viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) }
viewModelScope.launch {
likes.toggleLike(LikesRepository.ENTITY_TRACK, trackId, desired)
}
} }
} }
@@ -56,6 +56,8 @@ import com.fabledsword.minstrel.models.albumCoverPath
import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.AlbumDetail
import com.fabledsword.minstrel.nav.ArtistDetail import com.fabledsword.minstrel.nav.ArtistDetail
import com.fabledsword.minstrel.shared.formatDuration import com.fabledsword.minstrel.shared.formatDuration
import com.fabledsword.minstrel.shared.plural
import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow
@@ -329,19 +331,12 @@ private fun ArtistAvatar(artist: ArtistRef, fallbackAlbumId: String? = null) {
url = model, url = model,
contentDescription = artist.name, contentDescription = artist.name,
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
) { ) { CoverFallbackIcon(Lucide.User, size = 40.dp) }
Icon(
imageVector = Lucide.User,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(40.dp),
)
}
} }
} }
private fun albumCountLine(artist: ArtistRef): String = private fun albumCountLine(artist: ArtistRef): String =
if (artist.albumCount == 1) "1 album" else "${artist.albumCount} albums" plural(artist.albumCount, "album", "albums")
@Composable @Composable
private fun EmptyAlbumsHint() { private fun EmptyAlbumsHint() {
@@ -8,6 +8,7 @@ import com.fabledsword.minstrel.api.ErrorCopy
import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.connectivity.recoveries
import com.fabledsword.minstrel.library.data.LibraryRepository import com.fabledsword.minstrel.library.data.LibraryRepository
import com.fabledsword.minstrel.library.data.shufflePlayArtist
import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.likes.data.LikesRepository
import com.fabledsword.minstrel.models.ArtistDetailRef import com.fabledsword.minstrel.models.ArtistDetailRef
import com.fabledsword.minstrel.models.ArtistRef import com.fabledsword.minstrel.models.ArtistRef
@@ -145,24 +146,7 @@ class ArtistDetailViewModel @Inject constructor(
*/ */
fun playArtist() { fun playArtist() {
viewModelScope.launch { viewModelScope.launch {
try { shufflePlayArtist(artistId, repository, player) { transientMessagesChannel.trySend(it) }
val tracks = repository.fetchArtistTracks(artistId).shuffled()
if (tracks.isEmpty()) {
transientMessagesChannel.trySend("No tracks to play for this artist.")
} else {
player.setQueue(
tracks = tracks,
initialIndex = 0,
source = "artist:$artistId",
)
}
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
transientMessagesChannel.trySend(
"Couldn't start playback: ${ErrorCopy.fromThrowable(e)}",
)
}
} }
} }
@@ -14,12 +14,13 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.composables.icons.lucide.Disc3 import com.composables.icons.lucide.Disc3
import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Lucide
import androidx.compose.material3.Icon
import com.fabledsword.minstrel.models.AlbumRef import com.fabledsword.minstrel.models.AlbumRef
import com.fabledsword.minstrel.nav.LocalDetailSeedCache import com.fabledsword.minstrel.nav.LocalDetailSeedCache
import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon
import com.fabledsword.minstrel.shared.widgets.CoverTile import com.fabledsword.minstrel.shared.widgets.CoverTile
import com.fabledsword.minstrel.shared.widgets.PlayCircleButton import com.fabledsword.minstrel.shared.widgets.PlayCircleButton
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
@@ -34,6 +35,9 @@ import androidx.compose.ui.Alignment
* circular play button is overlaid at the bottom-right of the cover. * circular play button is overlaid at the bottom-right of the cover.
* Only Home wires it currently; Library / Discover / detail surfaces * Only Home wires it currently; Library / Discover / detail surfaces
* leave it null. * leave it null.
*
* [artSize] is the cover's side; the tile is 32dp wider for its padding.
* Home shrinks it on shelves that rank below Recently added.
*/ */
@Composable @Composable
fun AlbumCard( fun AlbumCard(
@@ -41,11 +45,12 @@ fun AlbumCard(
onClick: () -> Unit, onClick: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
onPlay: (suspend () -> Unit)? = null, onPlay: (suspend () -> Unit)? = null,
artSize: Dp = 144.dp,
) { ) {
val seedCache = LocalDetailSeedCache.current val seedCache = LocalDetailSeedCache.current
Surface( Surface(
modifier = modifier modifier = modifier
.width(176.dp) .width(artSize + 32.dp)
.clickable { .clickable {
seedCache.stashAlbum(album) seedCache.stashAlbum(album)
onClick() onClick()
@@ -56,16 +61,9 @@ fun AlbumCard(
CoverTile( CoverTile(
url = album.displayCoverUrl, url = album.displayCoverUrl,
contentDescription = album.title, contentDescription = album.title,
size = 144.dp, size = artSize,
background = MaterialTheme.colorScheme.surfaceVariant, background = MaterialTheme.colorScheme.surfaceVariant,
fallback = { fallback = { CoverFallbackIcon(Lucide.Disc3) },
Icon(
imageVector = Lucide.Disc3,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(56.dp),
)
},
overlay = { overlay = {
if (onPlay != null) { if (onPlay != null) {
PlayCircleButton( PlayCircleButton(
@@ -8,7 +8,6 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -18,11 +17,13 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.User import com.composables.icons.lucide.User
import com.fabledsword.minstrel.models.ArtistRef import com.fabledsword.minstrel.models.ArtistRef
import com.fabledsword.minstrel.nav.LocalDetailSeedCache import com.fabledsword.minstrel.nav.LocalDetailSeedCache
import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon
import com.fabledsword.minstrel.shared.widgets.CoverTile import com.fabledsword.minstrel.shared.widgets.CoverTile
import com.fabledsword.minstrel.shared.widgets.PlayCircleButton import com.fabledsword.minstrel.shared.widgets.PlayCircleButton
@@ -35,6 +36,9 @@ import com.fabledsword.minstrel.shared.widgets.PlayCircleButton
* circular play button is overlaid at the bottom-right of the avatar. * circular play button is overlaid at the bottom-right of the avatar.
* Only Home wires it currently. Padding is 4dp instead of 6dp because * Only Home wires it currently. Padding is 4dp instead of 6dp because
* the circular avatar pulls the button visually inward at the corner. * the circular avatar pulls the button visually inward at the corner.
*
* [artSize] is the avatar's diameter; the tile is 16dp wider for its
* padding. Home shrinks it on shelves that rank below the album shelves.
*/ */
@Composable @Composable
fun ArtistCard( fun ArtistCard(
@@ -42,11 +46,12 @@ fun ArtistCard(
onClick: () -> Unit, onClick: () -> Unit,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
onPlay: (suspend () -> Unit)? = null, onPlay: (suspend () -> Unit)? = null,
artSize: Dp = 128.dp,
) { ) {
val seedCache = LocalDetailSeedCache.current val seedCache = LocalDetailSeedCache.current
Surface( Surface(
modifier = modifier modifier = modifier
.width(144.dp) .width(artSize + 16.dp)
.clickable { .clickable {
seedCache.stashArtist(artist) seedCache.stashArtist(artist)
onClick() onClick()
@@ -60,16 +65,9 @@ fun ArtistCard(
CoverTile( CoverTile(
url = artist.displayCoverUrl, url = artist.displayCoverUrl,
contentDescription = artist.name, contentDescription = artist.name,
size = 128.dp, size = artSize,
shape = CircleShape, shape = CircleShape,
fallback = { fallback = { CoverFallbackIcon(Lucide.User) },
Icon(
imageVector = Lucide.User,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(56.dp),
)
},
overlay = { overlay = {
if (onPlay != null) { if (onPlay != null) {
PlayCircleButton( PlayCircleButton(
@@ -1,5 +1,7 @@
package com.fabledsword.minstrel.likes.data package com.fabledsword.minstrel.likes.data
import com.fabledsword.minstrel.cache.mutations.WriteOutcome
import com.fabledsword.minstrel.cache.mutations.likeToggleKey
import com.fabledsword.minstrel.api.endpoints.LikesApi import com.fabledsword.minstrel.api.endpoints.LikesApi
import com.fabledsword.minstrel.auth.AuthController import com.fabledsword.minstrel.auth.AuthController
import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao
@@ -8,6 +10,7 @@ import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao
import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao
import com.fabledsword.minstrel.cache.db.entities.CachedLikeEntity import com.fabledsword.minstrel.cache.db.entities.CachedLikeEntity
import com.fabledsword.minstrel.cache.mutations.MutationQueue import com.fabledsword.minstrel.cache.mutations.MutationQueue
import com.fabledsword.minstrel.cache.mutations.sendOrQueue
import com.fabledsword.minstrel.di.ApplicationScope import com.fabledsword.minstrel.di.ApplicationScope
import com.fabledsword.minstrel.library.data.toDomain import com.fabledsword.minstrel.library.data.toDomain
import com.fabledsword.minstrel.models.AlbumRef import com.fabledsword.minstrel.models.AlbumRef
@@ -28,6 +31,7 @@ import retrofit2.create
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.milliseconds
import timber.log.Timber
/** /**
* Cache-first reads + offline-first writes for likes. * Cache-first reads + offline-first writes for likes.
@@ -164,20 +168,25 @@ class LikesRepository @Inject constructor(
} else { } else {
likeDao.delete(uid, entityType, entityId) likeDao.delete(uid, entityType, entityId)
} }
// An older toggle for this entity is still queued: going live would
// let it replay after this one and undo it. Queue behind it instead;
// the replayer sends only the newest toggle per entity.
if (mutationQueue.pendingLikeStates().containsKey(likeToggleKey(entityType, entityId))) {
mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState)
return false
}
// 2. Best-effort REST call; 3. enqueue on failure. // 2. Best-effort REST call; 3. enqueue on failure.
val kindPath = serverPathFor(entityType) val kindPath = serverPathFor(entityType)
return try { // A refusal isn't surfaced: the heart buttons don't wait on this call,
if (desiredState) api.like(kindPath, entityId) else api.unlike(kindPath, entityId) // and the next likes refresh puts the server's answer back on screen.
true return sendOrQueue(
} catch ( send = { if (desiredState) api.like(kindPath, entityId) else api.unlike(kindPath, entityId) },
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, queue = { mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState) },
) { onRefused = { e ->
// Intentional swallow: the queue replays this later; surfacing Timber.i(e, "likes: %s %s refused (%d)", entityType, entityId, e.code())
// the network error here would force callers (UI) to handle it WriteOutcome.Refused
// even though it's already been buffered. },
mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState) ) == WriteOutcome.Synced
false
}
} }
/** /**
@@ -194,17 +203,28 @@ class LikesRepository @Inject constructor(
* The server lists each kind most recently liked first but sends no * The server lists each kind most recently liked first but sends no
* times, so the rows are stamped a millisecond apart in that order; * times, so the rows are stamped a millisecond apart in that order;
* `likedAt` then sorts the way the server does. * `likedAt` then sorts the way the server does.
*
* A like or unlike still queued here wins over the server's answer,
* which hasn't seen it yet: taking the server's would undo it on
* screen until the replay landed.
*/ */
suspend fun refreshIds() { suspend fun refreshIds() {
val uid = currentUserId() val uid = currentUserId()
val wire = api.ids() val wire = api.ids()
val pending = mutationQueue.pendingLikeStates()
val now = Clock.System.now() val now = Clock.System.now()
fun rowsOf(type: String, ids: List<String>) = fun rowsOf(type: String, ids: List<String>) =
ids.mapIndexed { i, id -> CachedLikeEntity(uid, type, id, likedAt = now - i.milliseconds) } ids.filter { pending[likeToggleKey(type, it)] != false }
.mapIndexed { i, id -> CachedLikeEntity(uid, type, id, likedAt = now - i.milliseconds) }
val rows = mutableListOf<CachedLikeEntity>() val rows = mutableListOf<CachedLikeEntity>()
rows += rowsOf(ENTITY_ARTIST, wire.artistIds) rows += rowsOf(ENTITY_ARTIST, wire.artistIds)
rows += rowsOf(ENTITY_ALBUM, wire.albumIds) rows += rowsOf(ENTITY_ALBUM, wire.albumIds)
rows += rowsOf(ENTITY_TRACK, wire.trackIds) rows += rowsOf(ENTITY_TRACK, wire.trackIds)
val listed = rows.mapTo(HashSet()) { likeToggleKey(it.entityType, it.entityId) }
pending.filterValues { it }.keys.filter { it !in listed }.forEach { key ->
val (type, id) = key.split(":", limit = 2)
rows += CachedLikeEntity(uid, type, id, likedAt = now)
}
likeDao.replaceAllForUser(uid, rows) likeDao.replaceAllForUser(uid, rows)
} }
@@ -226,3 +246,11 @@ class LikesRepository @Inject constructor(
} }
} }
} }
/**
* Flips a track's like, reading whether it is liked now from [likedIds], the
* set the screen is already showing. The heart buttons on track lists (an
* album, a playlist, the player) call this.
*/
suspend fun LikesRepository.toggleTrackLike(trackId: String, likedIds: Set<String>): Boolean =
toggleLike(LikesRepository.ENTITY_TRACK, trackId, desiredState = trackId !in likedIds)
@@ -1,8 +1,7 @@
package com.fabledsword.minstrel.models package com.fabledsword.minstrel.models
/** /**
* One admin-side user row. The * One admin-side user row. The admin-scoped variant carries the
* admin-scoped variant exposes `autoApproveRequests` and the
* canonical `createdAt` that the user-scoped /me response omits. * canonical `createdAt` that the user-scoped /me response omits.
*/ */
data class AdminUserRef( data class AdminUserRef(
@@ -10,6 +9,5 @@ data class AdminUserRef(
val username: String, val username: String,
val displayName: String? = null, val displayName: String? = null,
val isAdmin: Boolean = false, val isAdmin: Boolean = false,
val autoApproveRequests: Boolean = false,
val createdAt: String = "", val createdAt: String = "",
) )
@@ -9,3 +9,11 @@ package com.fabledsword.minstrel.models
*/ */
fun albumCoverPath(albumId: String): String = fun albumCoverPath(albumId: String): String =
if (albumId.isEmpty()) "" else "http://placeholder.invalid/api/albums/$albumId/cover" if (albumId.isEmpty()) "" else "http://placeholder.invalid/api/albums/$albumId/cover"
/**
* Absolute URL of an artist's image, or "" when [artistId] is blank. The
* server answers with the artist's picture, or else their newest album
* cover, through the same placeholder host as [albumCoverPath].
*/
fun artistImagePath(artistId: String): String =
if (artistId.isEmpty()) "" else "http://placeholder.invalid/api/artists/$artistId/image"
@@ -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
}
}
@@ -21,15 +21,25 @@ data class PlaylistRef(
val ownerUsername: String = "", val ownerUsername: String = "",
/** All member tracks resident in the audio cache — playable fully offline. */ /** All member tracks resident in the audio cache — playable fully offline. */
val fullyCached: Boolean = false, val fullyCached: Boolean = false,
/**
* Albums whose covers can stand for this playlist, in playlist order. Home
* gives each tile one the tiles before it do not already show.
*/
val coverAlbumIds: List<String> = emptyList(),
/** ISO-8601. A system mix is rebuilt in place, so this is when it was last refreshed. */
val createdAt: String = "",
/** Place on its Home shelf, 1 first; 0 when the app orders it itself. See playlists/Shelf.kt byShelfRank. */
val shelfRank: Int = 0,
) { ) {
val isSystem: Boolean get() = systemVariant != null val isSystem: Boolean get() = systemVariant != null
/** /**
* Whether the "Regenerate" affordance applies: every system playlist * Whether the "Regenerate" affordance applies: every system playlist
* EXCEPT songs_like_artist (the server's songs-like family exposes no * EXCEPT the kinds with several playlists per user (songs_like_artist,
* refresh trigger; rebuilds are scheduler-driven). * 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 * Can't be relied on while offline — either it needs the live server to
@@ -39,6 +49,9 @@ data class PlaylistRef(
val unavailableOffline: Boolean get() = refreshable || !fullyCached 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. * 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
}
}
@@ -15,7 +15,9 @@ package com.fabledsword.minstrel.models
* verbatim rather than validated, so an unexpected value is shown rather * verbatim rather than validated, so an unexpected value is shown rather
* than dropped. * than dropped.
* *
* [apkUrl] is server-relative (e.g. `/api/client/apk`). * [apkUrl] is server-relative (e.g. `/api/client/apk`). [sha256] is the
* served file's digest, in hex; empty from a server that predates it, and
* then a download is judged whole by its size alone.
*/ */
data class UpdateInfo( data class UpdateInfo(
val version: String, val version: String,
@@ -23,4 +25,5 @@ data class UpdateInfo(
val channel: String?, val channel: String?,
val apkUrl: String, val apkUrl: String,
val sizeBytes: Long, val sizeBytes: Long,
val sha256: String,
) )
@@ -6,8 +6,8 @@ import kotlinx.serialization.Serializable
/** /**
* One admin-side user row. Mirrors `adminUserView` from * One admin-side user row. Mirrors `adminUserView` from
* `internal/api/admin_users.go`. Distinct from the user-scoped /me * `internal/api/admin_users.go`. Distinct from the user-scoped /me
* profile shape because admin endpoints expose `auto_approve_requests` * profile shape because admin endpoints expose the canonical
* and the canonical `created_at`. * `created_at`.
*/ */
@Serializable @Serializable
data class AdminUserWire( data class AdminUserWire(
@@ -15,7 +15,6 @@ data class AdminUserWire(
val username: String = "", val username: String = "",
@SerialName("display_name") val displayName: String? = null, @SerialName("display_name") val displayName: String? = null,
@SerialName("is_admin") val isAdmin: Boolean = false, @SerialName("is_admin") val isAdmin: Boolean = false,
@SerialName("auto_approve_requests") val autoApproveRequests: Boolean = false,
@SerialName("created_at") val createdAt: String = "", @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,
)
@@ -23,6 +23,16 @@ data class PlaylistWire(
@SerialName("owner_username") val ownerUsername: String = "", @SerialName("owner_username") val ownerUsername: String = "",
@SerialName("created_at") val createdAt: String = "", @SerialName("created_at") val createdAt: String = "",
@SerialName("updated_at") val updatedAt: String = "", @SerialName("updated_at") val updatedAt: String = "",
/**
* Up to six distinct albums with art, in the order they first appear in
* the playlist. Home's shelves pick each tile's picture from these.
*/
@SerialName("cover_album_ids") val coverAlbumIds: List<String> = emptyList(),
/**
* A system mix's place on its Home shelf, 1 first: genre mixes are
* numbered by how much the listener plays each genre. 0 when unranked.
*/
@SerialName("shelf_rank") val shelfRank: Int = 0,
) )
/** /**
@@ -79,5 +89,8 @@ data class PlaylistDetailWire(
@SerialName("track_count") val trackCount: Int = 0, @SerialName("track_count") val trackCount: Int = 0,
@SerialName("cover_url") val coverUrl: String = "", @SerialName("cover_url") val coverUrl: String = "",
@SerialName("owner_username") val ownerUsername: String = "", @SerialName("owner_username") val ownerUsername: String = "",
@SerialName("created_at") val createdAt: String = "",
@SerialName("cover_album_ids") val coverAlbumIds: List<String> = emptyList(),
@SerialName("shelf_rank") val shelfRank: Int = 0,
val tracks: List<PlaylistTrackWire> = emptyList(), val tracks: List<PlaylistTrackWire> = emptyList(),
) )
@@ -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,
)
@@ -26,4 +26,5 @@ data class UpdateInfoWire(
val channel: String? = null, val channel: String? = null,
@SerialName("apk_url") val apkUrl: String = "/api/client/apk", @SerialName("apk_url") val apkUrl: String = "/api/client/apk",
@SerialName("size_bytes") val sizeBytes: Long = 0, @SerialName("size_bytes") val sizeBytes: Long = 0,
val sha256: String = "",
) )
@@ -15,12 +15,10 @@ import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable import androidx.navigation.compose.composable
import com.fabledsword.minstrel.admin.ui.AdminLandingScreen import com.fabledsword.minstrel.admin.ui.AdminLandingScreen
import com.fabledsword.minstrel.admin.ui.AdminQuarantineScreen 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.AdminTagSourcesScreen
import com.fabledsword.minstrel.admin.ui.AdminUsersScreen import com.fabledsword.minstrel.admin.ui.AdminUsersScreen
import com.fabledsword.minstrel.auth.ui.LoginScreen import com.fabledsword.minstrel.auth.ui.LoginScreen
import com.fabledsword.minstrel.auth.ui.ServerUrlScreen 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.home.ui.HomeScreen
import com.fabledsword.minstrel.library.ui.AlbumDetailScreen import com.fabledsword.minstrel.library.ui.AlbumDetailScreen
import com.fabledsword.minstrel.library.ui.ArtistDetailScreen 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.player.ui.QueueScreen
import com.fabledsword.minstrel.playlists.ui.PlaylistDetailScreen import com.fabledsword.minstrel.playlists.ui.PlaylistDetailScreen
import com.fabledsword.minstrel.playlists.ui.PlaylistsListScreen 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.search.ui.SearchScreen
import com.fabledsword.minstrel.settings.ui.SettingsScreen import com.fabledsword.minstrel.settings.ui.SettingsScreen
import com.fabledsword.minstrel.shared.widgets.ShellScaffold 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> { composable<Playlists> {
WithAnimatedScope { WithAnimatedScope {
ShellScaffold(onExpandPlayer = expandPlayer) { 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> { composable<AdminQuarantine> {
WithAnimatedScope { WithAnimatedScope {
ShellScaffold(onExpandPlayer = expandPlayer) { ShellScaffold(onExpandPlayer = expandPlayer) {
@@ -8,11 +8,9 @@ import kotlinx.serialization.Serializable
@Serializable data object Home @Serializable data object Home
@Serializable data object Library @Serializable data object Library
@Serializable data object Search @Serializable data object Search
@Serializable data object Discover
@Serializable data object Playlists @Serializable data object Playlists
@Serializable data object Settings @Serializable data object Settings
@Serializable data object Admin @Serializable data object Admin
@Serializable data object Requests
@Serializable data object Notifications @Serializable data object Notifications
@Serializable data object NotificationSettings @Serializable data object NotificationSettings
@@ -21,7 +19,6 @@ import kotlinx.serialization.Serializable
@Serializable data class AlbumDetail(val id: String) @Serializable data class AlbumDetail(val id: String)
@Serializable data class ArtistDetail(val id: String) @Serializable data class ArtistDetail(val id: String)
@Serializable data class PlaylistDetail(val id: String) @Serializable data class PlaylistDetail(val id: String)
@Serializable data object AdminRequests
@Serializable data object AdminQuarantine @Serializable data object AdminQuarantine
@Serializable data object AdminUsers @Serializable data object AdminUsers
@Serializable data object AdminTagSources @Serializable data object AdminTagSources
@@ -9,8 +9,9 @@ import com.fabledsword.minstrel.cache.db.entities.CachedNotificationSettingsEnti
import com.fabledsword.minstrel.cache.mutations.MutationKind import com.fabledsword.minstrel.cache.mutations.MutationKind
import com.fabledsword.minstrel.cache.mutations.MutationQueue import com.fabledsword.minstrel.cache.mutations.MutationQueue
import com.fabledsword.minstrel.cache.mutations.NotificationSettingPayload import com.fabledsword.minstrel.cache.mutations.NotificationSettingPayload
import com.fabledsword.minstrel.cache.mutations.WriteOutcome
import com.fabledsword.minstrel.cache.mutations.notificationSettingChange import com.fabledsword.minstrel.cache.mutations.notificationSettingChange
import kotlinx.coroutines.CancellationException import com.fabledsword.minstrel.cache.mutations.sendOrQueue
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
@@ -61,16 +62,14 @@ class NotificationSettingsRepository @Inject constructor(
return return
} }
val change = notificationSettingChange(payload) ?: return val change = notificationSettingChange(payload) ?: return
try { sendOrQueue(
save(api.putSettings(PutNotificationSettingsBody(listOf(change)))) send = { save(api.putSettings(PutNotificationSettingsBody(listOf(change)))) },
} catch (e: CancellationException) { queue = { mutationQueue.enqueueNotificationSettingSet(payload) },
throw e onRefused = { e ->
} catch ( Timber.i(e, "notification settings: PUT refused (%d)", e.code())
@Suppress("TooGenericExceptionCaught") e: Throwable, WriteOutcome.Refused
) { },
Timber.i(e, "notification settings: PUT failed; queued") )
mutationQueue.enqueueNotificationSettingSet(payload)
}
} }
private suspend fun current(): NotificationSettingsWire? = dao.getSettings()?.let(::decode) private suspend fun current(): NotificationSettingsWire? = dao.getSettings()?.let(::decode)
@@ -6,7 +6,8 @@ import com.fabledsword.minstrel.api.endpoints.ReadAllBody
import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationEntity import com.fabledsword.minstrel.cache.db.entities.CachedNotificationEntity
import com.fabledsword.minstrel.cache.mutations.MutationQueue import com.fabledsword.minstrel.cache.mutations.MutationQueue
import kotlinx.coroutines.CancellationException import com.fabledsword.minstrel.cache.mutations.WriteOutcome
import com.fabledsword.minstrel.cache.mutations.sendOrQueue
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.datetime.Clock import kotlinx.datetime.Clock
@@ -52,24 +53,12 @@ class NotificationsRepository @Inject constructor(
suspend fun markRead(id: String) { suspend fun markRead(id: String) {
dao.markRead(id, Clock.System.now()) dao.markRead(id, Clock.System.now())
try { // A refusal (404: trimmed or gone server-side) leaves nothing to mark.
api.markRead(id) sendOrQueue(
} catch (e: CancellationException) { send = { api.markRead(id) },
throw e queue = { mutationQueue.enqueueNotificationRead(id) },
} catch (e: HttpException) { onRefused = { e -> refused("mark read", e) },
// A 4xx (404: trimmed or gone server-side) leaves nothing to mark; )
// a 5xx is the server's trouble, so the read waits in the queue.
if (e.code() >= HTTP_SERVER_ERROR) {
mutationQueue.enqueueNotificationRead(id)
} else {
Timber.i(e, "notifications: mark read refused (%d)", e.code())
}
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
Timber.i(e, "notifications: mark read failed; queued")
mutationQueue.enqueueNotificationRead(id)
}
} }
/** /**
@@ -80,16 +69,16 @@ class NotificationsRepository @Inject constructor(
suspend fun markAllRead() { suspend fun markAllRead() {
val upTo = readAllCutoff(dao.getAll().map { it.createdAt })?.toString() val upTo = readAllCutoff(dao.getAll().map { it.createdAt })?.toString()
dao.markAllRead(Clock.System.now()) dao.markAllRead(Clock.System.now())
try { sendOrQueue(
api.readAll(ReadAllBody(upTo = upTo)) send = { api.readAll(ReadAllBody(upTo = upTo)) },
} catch (e: CancellationException) { queue = { mutationQueue.enqueueNotificationsReadAll(upTo) },
throw e onRefused = { e -> refused("mark all read", e) },
} catch ( )
@Suppress("TooGenericExceptionCaught") e: Throwable, }
) {
Timber.i(e, "notifications: mark all read failed; queued") private fun refused(what: String, e: HttpException): WriteOutcome {
mutationQueue.enqueueNotificationsReadAll(upTo) Timber.i(e, "notifications: %s refused (%d)", what, e.code())
} return WriteOutcome.Refused
} }
/** The page the device holds, newest first. */ /** The page the device holds, newest first. */
@@ -103,8 +92,6 @@ class NotificationsRepository @Inject constructor(
companion object { companion object {
/** The newest page the device keeps; older notices stay on the server. */ /** The newest page the device keeps; older notices stay on the server. */
const val PAGE_SIZE = 50 const val PAGE_SIZE = 50
private const val HTTP_SERVER_ERROR = 500
} }
} }
@@ -76,7 +76,7 @@ internal fun announcementFor(fresh: List<CachedNotificationEntity>): Announcemen
channel = if (fresh.all { shadeChannelFor(it.kind) == ShadeChannel.LIBRARY_HEALTH }) { channel = if (fresh.all { shadeChannelFor(it.kind) == ShadeChannel.LIBRARY_HEALTH }) {
ShadeChannel.LIBRARY_HEALTH ShadeChannel.LIBRARY_HEALTH
} else { } else {
ShadeChannel.YOUR_REQUESTS ShadeChannel.NEW_MUSIC
}, },
lines = fresh.sortedByDescending { it.createdAt }.take(PILE_LINES).map { it.title }, 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. * user's system-level choice for it.
*/ */
internal enum class ShadeChannel(val id: String, val title: String, val description: String) { 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"), NEW_MUSIC("new_music", "New music", "Albums arriving in the library"),
LIBRARY_HEALTH("library_health", "Library health", "For admins: requests to review and library problems"), 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. */ /** Everything a listener can receive is theirs; the rest is admin work. */
internal fun shadeChannelFor(kind: String): ShadeChannel = 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. */ /** The delivery service runs exactly while signed in with background delivery on. */
internal fun deliveryWanted(signedIn: Boolean, enabled: Boolean): Boolean = signedIn && enabled internal fun deliveryWanted(signedIn: Boolean, enabled: Boolean): Boolean = signedIn && enabled
@@ -79,6 +79,7 @@ class NotificationPoster @Inject constructor(
private fun ensureChannels() { private fun ensureChannels() {
val manager = context.getSystemService(NotificationManager::class.java) ?: return val manager = context.getSystemService(NotificationManager::class.java) ?: return
retiredShadeChannelIds.forEach { manager.deleteNotificationChannel(it) }
ShadeChannel.entries.forEach { c -> ShadeChannel.entries.forEach { c ->
manager.createNotificationChannel( manager.createNotificationChannel(
NotificationChannel(c.id, c.title, NotificationManager.IMPORTANCE_DEFAULT) 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.Admin
import com.fabledsword.minstrel.nav.AdminQuarantine import com.fabledsword.minstrel.nav.AdminQuarantine
import com.fabledsword.minstrel.nav.AdminRequests
import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.AlbumDetail
import com.fabledsword.minstrel.nav.ArtistDetail 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 * 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 * 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, * 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 * 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? { internal fun routeForLink(link: String): Any? {
val parts = link.substringBefore('?').trim('/').split('/').filter { it.isNotEmpty() } val parts = link.substringBefore('?').trim('/').split('/').filter { it.isNotEmpty() }
return when { return when {
link.isBlank() -> null
parts.isEmpty() -> Home
parts.size == 2 && parts[0] == "albums" -> AlbumDetail(parts[1]) parts.size == 2 && parts[0] == "albums" -> AlbumDetail(parts[1])
parts.size == 2 && parts[0] == "artists" -> ArtistDetail(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 == listOf("collection", "reports") -> AdminQuarantine
parts.firstOrNull() == "collection" && parts.getOrNull(1) in ADMIN_COLLECTION_PAGES -> Admin parts.firstOrNull() == "collection" && parts.getOrNull(1) in ADMIN_COLLECTION_PAGES -> Admin
parts.firstOrNull() == "admin" -> Admin parts.firstOrNull() == "admin" -> Admin

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