Compare commits

..
Author SHA1 Message Date
Renovate Bot 8d443f3b3c chore(config): migrate config renovate.json 2026-12-05 04:02:17 +00:00
bvandeusen 077c5a9ec2 Release: CONTRIBUTING says pull requests aren't taken
release / go (push) Successful in 1m48s
release / integration (push) Successful in 2m35s
release / govulncheck (push) Successful in 22s
release / web (push) Successful in 1m15s
release / android (push) Successful in 2m12s
release / Build signed APK (push) Successful in 2m3s
release / Build + push container image (push) Successful in 2m2s
2026-12-03 22:21:02 -05:00
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
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
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
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
467 changed files with 16728 additions and 18665 deletions
-1
View File
@@ -5,7 +5,6 @@
ci/ export-ignore
ci-requirements.md export-ignore
renovate.json export-ignore
.gitleaks.toml export-ignore
internal/server/release_gate_test.go export-ignore
internal/server/release_version_test.go export-ignore
.gitattributes export-ignore
+15 -22
View File
@@ -122,7 +122,7 @@ jobs:
go:
runs-on: go-ci
container:
image: git.fabledsword.com/bvandeusen/ci-go:1.27
image: git.fabledsword.com/bvandeusen/ci-go:1.26
steps:
- name: Checkout
@@ -176,10 +176,10 @@ jobs:
integration:
runs-on: go-ci
container:
image: git.fabledsword.com/bvandeusen/ci-go:1.27
image: git.fabledsword.com/bvandeusen/ci-go:1.26
services:
postgres:
image: postgres:19-alpine
image: postgres:16-alpine
env:
POSTGRES_USER: minstrel
POSTGRES_PASSWORD: minstrel
@@ -211,7 +211,7 @@ jobs:
echo "self ($SELF) networks: $SELF_NETS"
PG_ID=""
PG_NAME=""
for cid in $(docker ps --filter "ancestor=postgres:19-alpine" -q); do
for cid in $(docker ps --filter "ancestor=postgres:16-alpine" -q); do
nm=$(docker inspect -f '{{.Name}}' "$cid" | sed 's#^/##')
case "$nm" in *minstrel-postgres*|*_postgres_*) continue ;; esac
for net in $(docker inspect -f '{{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' "$cid"); do
@@ -223,9 +223,6 @@ jobs:
PG_IP=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$PG_ID")
test -n "$PG_IP"
export MINSTREL_TEST_DATABASE_URL="postgres://minstrel:minstrel@${PG_IP}:5432/minstrel_test?sslmode=disable"
# A database test that finds no database fails here instead of
# skipping, so this lane can't pass with nothing run.
export MINSTREL_TEST_DATABASE_REQUIRED=1
# Wait for Postgres to accept connections. Asked of the service
# container itself: the run: shell is dash, where a `/dev/tcp`
@@ -306,7 +303,7 @@ jobs:
web:
runs-on: go-ci
container:
image: git.fabledsword.com/bvandeusen/ci-go:1.27
image: git.fabledsword.com/bvandeusen/ci-go:1.26
defaults:
run:
@@ -335,7 +332,7 @@ jobs:
# docker that can pull our container.image.
runs-on: flutter-ci
container:
image: git.fabledsword.com/bvandeusen/ci-android:37
image: git.fabledsword.com/bvandeusen/ci-android:36
defaults:
run:
@@ -413,7 +410,7 @@ jobs:
govulncheck:
runs-on: go-ci
container:
image: golang:1.27-trixie
image: golang:1.26-bookworm
steps:
# Plain git, not actions/checkout: that action runs on node, which the
@@ -446,7 +443,7 @@ jobs:
|| github.ref == 'refs/heads/main'
runs-on: flutter-ci
container:
image: git.fabledsword.com/bvandeusen/ci-android:37
image: git.fabledsword.com/bvandeusen/ci-android:36
defaults:
run:
@@ -560,14 +557,10 @@ jobs:
signer="$(ls "$sdk"/build-tools/*/apksigner 2>/dev/null | sort -V | tail -1 || true)"
test -n "$signer" || { echo "::error::no apksigner under '$sdk/build-tools'"; exit 1; }
certs="$("$signer" verify --print-certs app/build/outputs/apk/release/app-release.apk)"
# apksigner's signer label varies between versions: "Signer #1
# certificate ..." before build-tools 37, "V3.0 Signer: certificate
# ..." from 37 on. So the digests are read without relying on it.
printf '%s\n' "$certs" | grep -E 'certificate (DN|SHA-256 digest):' || true
# One signer, and it is ours: exactly one distinct SHA-256 across
# every scheme apksigner reports. A second key would be a lineage or
printf '%s\n' "$certs" | grep -E '^Signer #[0-9]+ certificate (DN|SHA-256 digest)'
# One signer, and it is ours. A second signer would be a lineage or
# a mistake; either way not something to ship unexamined.
digests="$(printf '%s\n' "$certs" | sed -n 's/^.*certificate SHA-256 digest: //p' | sort -u)"
digests="$(printf '%s\n' "$certs" | sed -n 's/^Signer #[0-9]* certificate SHA-256 digest: //p')"
if [ "$digests" != "$RELEASE_CERT_SHA256" ]; then
if printf '%s' "$certs" | grep -q 'CN=Android Debug'; then
echo "::error::the release APK is signed with a debug key"
@@ -622,7 +615,7 @@ jobs:
&& needs.android-release.result == 'success' }}
runs-on: go-ci
container:
image: git.fabledsword.com/bvandeusen/ci-go:1.27
image: git.fabledsword.com/bvandeusen/ci-go:1.26
env:
IMAGE: git.fabledsword.com/bvandeusen/minstrel
@@ -707,7 +700,7 @@ jobs:
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 .gitleaks.toml; do
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
@@ -790,8 +783,8 @@ jobs:
- name: Build and push
shell: bash
# --pull: the Dockerfile's base images are floating tags (golang:1.27,
# debian:trixie-slim). Without it the runner's daemon reuses
# --pull: the Dockerfile's base images are floating tags (golang:1.26,
# debian:bookworm-slim). Without it the runner's daemon reuses
# whatever it cached, and the shipped binary can sit on a Go patch
# release govulncheck already flagged while the lane, which pulls
# fresh, reports clean.
-22
View File
@@ -1,22 +0,0 @@
# The weekly security sweep reads this file in place of the family gitleaks
# config, so it extends that config and adds only this repository's
# allowlist. The path is where the sweep's image keeps the family rules.
#
# Every entry says why the matched value is not a secret.
[extend]
path = "/opt/security-rules/gitleaks-family.toml"
[allowlist]
description = "Minstrel: test values that look like credentials and are not"
regexes = [
# AWS's published SigV4 example credentials ("Examples: Signature
# Calculations in AWS Signature Version 4", Amazon S3 API reference).
# internal/backup/s3_test.go signs AWS's own worked example with them and
# checks the signature AWS prints, so they must stay exactly as published.
'''AKIAIOSFODNN7EXAMPLE''',
'''wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY''',
# An invite token that a register test inserts into the throwaway test
# database and then redeems (internal/api/auth_register_test.go).
'''test-invite-abc123''',
]
+4 -4
View File
@@ -1,13 +1,13 @@
# syntax=docker/dockerfile:1.29
# syntax=docker/dockerfile:1.6
FROM node:26-trixie-slim AS web
FROM node:22-bookworm-slim AS web
WORKDIR /web
COPY web/package.json web/package-lock.json ./
RUN npm ci
COPY web/ ./
RUN npm run build
FROM golang:1.27-trixie AS builder
FROM golang:1.26-bookworm AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
@@ -31,7 +31,7 @@ RUN go build -trimpath \
-X 'github.com/Fabled-Sword/minstrel/internal/buildinfo.Channel=${MINSTREL_CHANNEL}'" \
-o /out/minstrel ./cmd/minstrel
FROM debian:trixie-slim
FROM debian:bookworm-slim
# ffmpeg: duration probes and the exact-tier audio hash (a SHA-256 of the
# encoded audio packets, so no decode). libchromaprint-tools: fpcalc, the
# acoustic fingerprint that tells the same recording at two bitrates apart
+1 -3
View File
@@ -32,7 +32,7 @@ services:
depends_on: [db]
db:
image: postgres:19
image: postgres:17
environment:
POSTGRES_USER: minstrel
POSTGRES_PASSWORD: minstrel
@@ -94,8 +94,6 @@ Every image carries a signed Android app, all with the same key, so a phone can
**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.
**Keep the Postgres image on the major version your database was created with.** The quick start uses `postgres:19`. Postgres can't open a data folder made by another major version, so moving an existing database to a newer one takes a `pg_dump`, a fresh volume and a restore.
## Features
**Listening**
-11
View File
@@ -1,11 +0,0 @@
# ktlint reads this. The code style is ktlint's default (ktlint_official)
# with two changes:
# - Lines wrap at 120, detekt's MaxLineLength, so the two checks agree.
# ktlint_official alone would wrap at 140.
# - @Composable functions are exempt from the lowercase naming rule, because
# Compose names them like types (PlayerScreen, not playerScreen).
root = true
[*.{kt,kts}]
max_line_length = 120
ktlint_function_naming_ignore_when_annotated_with = Composable
+1 -4
View File
@@ -15,10 +15,7 @@ plugins {
android {
namespace = "com.fabledsword.minstrel"
// 37.1: Compose 1.13 requires compiling against Android 37.1 or later.
compileSdk {
version = release(37) { minorApiLevel = 1 }
}
compileSdk = 36
defaultConfig {
applicationId = "com.fabledsword.minstrel"
@@ -30,8 +30,8 @@ import com.fabledsword.minstrel.auth.AuthStore
import com.fabledsword.minstrel.auth.ui.AuthGateViewModel
import com.fabledsword.minstrel.cache.CachedTrackIds
import com.fabledsword.minstrel.connectivity.LocalServerHealth
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.nav.DetailSeedCache
import com.fabledsword.minstrel.nav.LocalDetailSeedCache
import com.fabledsword.minstrel.nav.Login
@@ -56,11 +56,8 @@ import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@Inject lateinit var seedCache: DetailSeedCache
@Inject lateinit var cachedTrackIds: CachedTrackIds
@Inject lateinit var serverHealth: NetworkStatusController
@Inject lateinit var authStore: AuthStore
// Set when the user taps a notification: the media one asks for the full
@@ -123,9 +120,8 @@ class MainActivity : ComponentActivity() {
val signedIn = authStore.sessionCookie.map { !it.isNullOrEmpty() }
combine(signedIn, authStore.backgroundDelivery, ::deliveryWanted).first { it }
val permission = Manifest.permission.POST_NOTIFICATIONS
val granted =
ContextCompat.checkSelfPermission(this@MainActivity, permission) ==
PackageManager.PERMISSION_GRANTED
val granted = ContextCompat.checkSelfPermission(this@MainActivity, permission) ==
PackageManager.PERMISSION_GRANTED
if (!granted) askToNotify.launch(permission)
}
}
@@ -200,10 +196,7 @@ private fun App(
* request fails.
*/
@Composable
private fun SignInWhenSessionRejected(
gate: AuthGateViewModel,
navController: NavHostController,
) {
private fun SignInWhenSessionRejected(gate: AuthGateViewModel, navController: NavHostController) {
val sessionRejected by gate.sessionRejected.collectAsStateWithLifecycle()
LaunchedEffect(sessionRejected, navController) {
if (!sessionRejected) return@LaunchedEffect
@@ -11,7 +11,6 @@ import com.fabledsword.minstrel.cache.CacheIndexer
import com.fabledsword.minstrel.cache.audiocache.CacheBudgetSync
import com.fabledsword.minstrel.cache.mutations.MutationReplayer
import com.fabledsword.minstrel.cache.sync.SyncController
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.di.ApplicationScope
import com.fabledsword.minstrel.diagnostics.DiagnosticsReporter
import com.fabledsword.minstrel.diagnostics.DiagnosticsUploader
@@ -25,6 +24,7 @@ import com.fabledsword.minstrel.player.LikedAudioPinner
import com.fabledsword.minstrel.player.PlayEventsReporter
import com.fabledsword.minstrel.player.PlaybackErrorReporter
import com.fabledsword.minstrel.player.ResumeController
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@@ -41,6 +41,7 @@ class MinstrelApplication :
Application(),
Configuration.Provider,
SingletonImageLoader.Factory {
@Inject lateinit var workerFactory: HiltWorkerFactory
/**
@@ -65,9 +66,7 @@ class MinstrelApplication :
* cold start with persisted cookie). Without this @Inject the
* singleton would never instantiate.
*/
@Suppress("unused")
@Inject
lateinit var syncController: SyncController
@Suppress("unused") @Inject lateinit var syncController: SyncController
/**
* Same construct-the-singleton trick — MutationReplayer's init
@@ -76,9 +75,7 @@ class MinstrelApplication :
* cold start with persisted cookie). Without this @Inject the
* queue would only enqueue, never replay.
*/
@Suppress("unused")
@Inject
lateinit var mutationReplayer: MutationReplayer
@Suppress("unused") @Inject lateinit var mutationReplayer: MutationReplayer
/**
* Same construct-the-singleton trick — DeliveryLauncher starts and stops
@@ -86,9 +83,7 @@ class MinstrelApplication :
* every nudge and reconnect. Without this @Inject no phone
* notification would ever be posted.
*/
@Suppress("unused")
@Inject
lateinit var deliveryLauncher: DeliveryLauncher
@Suppress("unused") @Inject lateinit var deliveryLauncher: DeliveryLauncher
/**
* Same construct-the-singleton trick — PlayEventsReporter's init
@@ -97,9 +92,7 @@ class MinstrelApplication :
* server. Without this @Inject the singleton would never
* instantiate and Android plays would never reach the server.
*/
@Suppress("unused")
@Inject
lateinit var playEventsReporter: PlayEventsReporter
@Suppress("unused") @Inject lateinit var playEventsReporter: PlayEventsReporter
/**
* Same construct-the-singleton trick — PlaybackErrorReporter
@@ -109,9 +102,7 @@ class MinstrelApplication :
* snackbar. Without this construct ExoPlayer skip-on-error is
* invisible to the user.
*/
@Suppress("unused")
@Inject
lateinit var playbackErrorReporter: PlaybackErrorReporter
@Suppress("unused") @Inject lateinit var playbackErrorReporter: PlaybackErrorReporter
/**
* Same construct-the-singleton trick — CoverPrefetcher's init
@@ -119,9 +110,7 @@ class MinstrelApplication :
* cache with the next track's cover so track changes don't flash
* a loading state.
*/
@Suppress("unused")
@Inject
lateinit var coverPrefetcher: CoverPrefetcher
@Suppress("unused") @Inject lateinit var coverPrefetcher: CoverPrefetcher
/**
* Same construct-the-singleton trick — CacheIndexer's init block
@@ -130,9 +119,7 @@ class MinstrelApplication :
* and the cached indicator their data source. Without this @Inject
* the index would stay empty and the offline pools would be inert.
*/
@Suppress("unused")
@Inject
lateinit var cacheIndexer: CacheIndexer
@Suppress("unused") @Inject lateinit var cacheIndexer: CacheIndexer
/**
* Same construct-the-singleton trick — CacheBudgetSync's init block
@@ -140,18 +127,14 @@ class MinstrelApplication :
* Without this @Inject the evictor would never arm, and the cache
* would grow without a limit.
*/
@Suppress("unused")
@Inject
lateinit var cacheBudgetSync: CacheBudgetSync
@Suppress("unused") @Inject lateinit var cacheBudgetSync: CacheBudgetSync
/**
* Same construct-the-singleton trick — LikedAudioPinner's init block
* downloads liked tracks into the Liked songs budget. Without this
* @Inject, liking a track would not keep it offline.
*/
@Suppress("unused")
@Inject
lateinit var likedAudioPinner: LikedAudioPinner
@Suppress("unused") @Inject lateinit var likedAudioPinner: LikedAudioPinner
/**
* Same construct-the-singleton trick — AudioPrefetcher's init
@@ -160,9 +143,7 @@ class MinstrelApplication :
* SimpleCache via CacheWriter. Without this @Inject the
* prefetchWindow setting would be inert and skips would re-fetch.
*/
@Suppress("unused")
@Inject
lateinit var audioPrefetcher: AudioPrefetcher
@Suppress("unused") @Inject lateinit var audioPrefetcher: AudioPrefetcher
/**
* Same construct-the-singleton trick — NetworkStatusController owns the
@@ -171,9 +152,7 @@ class MinstrelApplication :
* signal (plus the VersionTooOld byproduct). It must exist from launch so
* the poll loop runs and the StateFlow stays warm for every consumer.
*/
@Suppress("unused")
@Inject
lateinit var networkStatusController: NetworkStatusController
@Suppress("unused") @Inject lateinit var networkStatusController: NetworkStatusController
/**
* Same construct-the-singleton trick — FreshnessSweeper's init
@@ -182,9 +161,7 @@ class MinstrelApplication :
* via MetadataProvider, so the cache stays warm without
* user-driven pull-to-refresh.
*/
@Suppress("unused")
@Inject
lateinit var freshnessSweeper: FreshnessSweeper
@Suppress("unused") @Inject lateinit var freshnessSweeper: FreshnessSweeper
/**
* Same construct-the-singleton trick — EventsStream's init block
@@ -193,31 +170,21 @@ class MinstrelApplication :
* Without this @Inject the events SharedFlow would have no
* upstream and consumers would never see anything.
*/
@Suppress("unused")
@Inject
lateinit var eventsStream: EventsStream
@Suppress("unused") @Inject lateinit var eventsStream: EventsStream
/**
* Same construct-the-singleton trick — LiveEventsDispatcher's
* init block subscribes to EventsStream.events + the process
* lifecycle and routes cross-screen state refreshes.
*/
@Suppress("unused")
@Inject
lateinit var liveEventsDispatcher: LiveEventsDispatcher
@Suppress("unused") @Inject lateinit var liveEventsDispatcher: LiveEventsDispatcher
// Device diagnostics. The reporter gates itself on the account's
// debug flag; the uploader drains its buffer on a tick / recovery.
@Suppress("unused")
@Inject
lateinit var diagnosticsReporter: DiagnosticsReporter
@Suppress("unused") @Inject lateinit var diagnosticsReporter: DiagnosticsReporter
@Suppress("unused") @Inject lateinit var diagnosticsUploader: DiagnosticsUploader
@Suppress("unused")
@Inject
lateinit var diagnosticsUploader: DiagnosticsUploader
@Inject @ApplicationScope
lateinit var appScope: CoroutineScope
@Inject @ApplicationScope lateinit var appScope: CoroutineScope
override fun onCreate() {
super.onCreate()
@@ -241,17 +208,10 @@ class MinstrelApplication :
* to the package-stack-trace tag DebugTree produces.
*/
private class ReleaseTree : Timber.Tree() {
override fun isLoggable(
tag: String?,
priority: Int,
): Boolean = priority >= android.util.Log.WARN
override fun isLoggable(tag: String?, priority: Int): Boolean =
priority >= android.util.Log.WARN
override fun log(
priority: Int,
tag: String?,
message: String,
t: Throwable?,
) {
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
val resolvedTag = tag ?: "Minstrel"
if (t == null) {
android.util.Log.println(priority, resolvedTag, message)
@@ -266,11 +226,9 @@ class MinstrelApplication :
}
override val workManagerConfiguration: Configuration
get() =
Configuration
.Builder()
.setWorkerFactory(workerFactory)
.build()
get() = Configuration.Builder()
.setWorkerFactory(workerFactory)
.build()
/**
* Builds the process-singleton Coil ImageLoader with our shared
@@ -284,10 +242,10 @@ class MinstrelApplication :
* two read as one cross-dissolve.
*/
override fun newImageLoader(context: android.content.Context): ImageLoader =
ImageLoader
.Builder(context)
ImageLoader.Builder(context)
.components {
add(OkHttpNetworkFetcherFactory(callFactory = { okHttpClient }))
}.crossfade(ART_CROSSFADE_MS)
}
.crossfade(ART_CROSSFADE_MS)
.build()
}
@@ -14,38 +14,25 @@ import javax.inject.Singleton
* admin repos — direct REST, no caching.
*/
@Singleton
class AdminInvitesRepository
@Inject
constructor(
retrofit: Retrofit,
) {
private val api: AdminInvitesApi = retrofit.create()
class AdminInvitesRepository @Inject constructor(retrofit: Retrofit) {
private val api: AdminInvitesApi = retrofit.create()
suspend fun list(): List<Invite> = api.list().invites.map { it.toDomain() }
suspend fun list(): List<Invite> = api.list().invites.map { it.toDomain() }
suspend fun create(note: String?): Invite =
api
.create(
CreateInviteBody(
note =
note?.takeIf {
it.isNotEmpty()
},
),
).toDomain()
suspend fun create(note: String?): Invite =
api.create(CreateInviteBody(note = note?.takeIf { it.isNotEmpty() })).toDomain()
suspend fun revoke(token: String) {
api.revoke(token)
}
suspend fun revoke(token: String) {
api.revoke(token)
}
}
private fun InviteWire.toDomain(): Invite =
Invite(
token = token,
invitedBy = invitedBy,
note = note,
createdAt = createdAt,
expiresAt = expiresAt,
redeemedAt = redeemedAt,
redeemedBy = redeemedBy,
)
private fun InviteWire.toDomain(): Invite = Invite(
token = token,
invitedBy = invitedBy,
note = note,
createdAt = createdAt,
expiresAt = expiresAt,
redeemedAt = redeemedAt,
redeemedBy = redeemedBy,
)
@@ -17,21 +17,19 @@ import javax.inject.Singleton
* Each action takes the row off the queue once the server accepts it.
*/
@Singleton
class AdminQuarantineRepository
@Inject
constructor(
retrofit: Retrofit,
) {
private val api: AdminQuarantineApi = retrofit.create()
class AdminQuarantineRepository @Inject constructor(
retrofit: Retrofit,
) {
private val api: AdminQuarantineApi = retrofit.create()
suspend fun list(): List<AdminQuarantineItemRef> = api.list().map { it.toDomain() }
suspend fun list(): List<AdminQuarantineItemRef> = api.list().map { it.toDomain() }
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 removeFile(trackId: String) = api.removeFile(trackId)
suspend fun deleteFile(trackId: String) = api.deleteFile(trackId)
}
suspend fun deleteFile(trackId: String) = api.deleteFile(trackId)
}
// ── Mappers ──
@@ -18,38 +18,31 @@ import javax.inject.Singleton
* Exceptions propagate to the ViewModel (which maps them via ErrorCopy).
*/
@Singleton
class AdminTagSourcesRepository
@Inject
constructor(
retrofit: Retrofit,
) {
private val api: AdminTagSourcesApi = retrofit.create()
class AdminTagSourcesRepository @Inject constructor(
retrofit: Retrofit,
) {
private val api: AdminTagSourcesApi = retrofit.create()
suspend fun list(): List<AdminTagSourceRef> = api.list().providers.map { it.toDomain() }
suspend fun list(): List<AdminTagSourceRef> = api.list().providers.map { it.toDomain() }
suspend fun setEnabled(
id: String,
enabled: Boolean,
): AdminTagSourceRef = api.update(id, UpdateTagSourceBody(enabled = enabled)).toDomain()
suspend fun setEnabled(id: String, enabled: Boolean): AdminTagSourceRef =
api.update(id, UpdateTagSourceBody(enabled = enabled)).toDomain()
suspend fun setApiKey(
id: String,
apiKey: String,
): AdminTagSourceRef = api.update(id, UpdateTagSourceBody(apiKey = apiKey)).toDomain()
suspend fun setApiKey(id: String, apiKey: String): AdminTagSourceRef =
api.update(id, UpdateTagSourceBody(apiKey = apiKey)).toDomain()
suspend fun test(id: String): TagSourceTestResult = api.test(id).toResult()
}
suspend fun test(id: String): TagSourceTestResult = api.test(id).toResult()
}
private fun AdminTagSourceWire.toDomain(): AdminTagSourceRef =
AdminTagSourceRef(
id = id,
displayName = displayName,
requiresApiKey = requiresApiKey,
supports = supports,
enabled = enabled,
apiKeySet = apiKeySet,
testable = testable,
)
private fun AdminTagSourceWire.toDomain(): AdminTagSourceRef = AdminTagSourceRef(
id = id,
displayName = displayName,
requiresApiKey = requiresApiKey,
supports = supports,
enabled = enabled,
apiKeySet = apiKeySet,
testable = testable,
)
private fun TestTagSourceWire.toResult(): TagSourceTestResult =
TagSourceTestResult(ok = ok, durationMs = durationMs, error = error)
@@ -16,33 +16,26 @@ import javax.inject.Singleton
* admin repositories.
*/
@Singleton
class AdminUsersRepository
@Inject
constructor(
retrofit: Retrofit,
) {
private val api: AdminUsersApi = retrofit.create()
class AdminUsersRepository @Inject constructor(
retrofit: Retrofit,
) {
private val api: AdminUsersApi = retrofit.create()
suspend fun list(): List<AdminUserRef> = api.list().users.map { it.toDomain() }
suspend fun list(): List<AdminUserRef> = api.list().users.map { it.toDomain() }
suspend fun setAdmin(
id: String,
isAdmin: Boolean,
) = api.setAdmin(id, SetAdminBody(isAdmin))
suspend fun setAdmin(id: String, isAdmin: Boolean) =
api.setAdmin(id, SetAdminBody(isAdmin))
suspend fun resetPassword(
id: String,
newPassword: String,
) = api.resetPassword(id, ResetPasswordBody(newPassword))
suspend fun resetPassword(id: String, newPassword: String) =
api.resetPassword(id, ResetPasswordBody(newPassword))
suspend fun delete(id: String) = api.delete(id)
}
suspend fun delete(id: String) = api.delete(id)
}
private fun AdminUserWire.toDomain(): AdminUserRef =
AdminUserRef(
id = id,
username = username,
displayName = displayName,
isAdmin = isAdmin,
createdAt = createdAt,
)
private fun AdminUserWire.toDomain(): AdminUserRef = AdminUserRef(
id = id,
username = username,
displayName = displayName,
isAdmin = isAdmin,
createdAt = createdAt,
)
@@ -25,73 +25,72 @@ data class AdminInvitesUiState(
)
@HiltViewModel
class AdminInvitesViewModel
@Inject
constructor(
private val repository: AdminInvitesRepository,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow(AdminInvitesUiState())
val state: StateFlow<AdminInvitesUiState> = internal.asStateFlow()
class AdminInvitesViewModel @Inject constructor(
private val repository: AdminInvitesRepository,
networkStatus: NetworkStatusController,
) : ViewModel() {
/** One-shot signal for screens to show the generated token + copy UI. */
private val createdChannel = Channel<Invite>(Channel.BUFFERED)
val created: Flow<Invite> = createdChannel.receiveAsFlow()
private val internal = MutableStateFlow(AdminInvitesUiState())
val state: StateFlow<AdminInvitesUiState> = internal.asStateFlow()
init {
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.message != null) refresh()
}
}
}
/** One-shot signal for screens to show the generated token + copy UI. */
private val createdChannel = Channel<Invite>(Channel.BUFFERED)
val created: Flow<Invite> = createdChannel.receiveAsFlow()
fun refresh() {
viewModelScope.launch {
internal.update { it.copy(isLoading = true, message = null) }
try {
val rows = repository.list()
internal.update { it.copy(isLoading = false, invites = rows) }
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.update {
it.copy(
isLoading = false,
message = ErrorCopy.fromThrowable(e),
)
}
}
}
}
fun generate(note: String?) {
viewModelScope.launch {
try {
val invite = repository.create(note)
createdChannel.trySend(invite)
// Optimistically prepend; next refresh reconciles.
internal.update { it.copy(invites = listOf(invite) + it.invites) }
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.update {
it.copy(message = ErrorCopy.fromThrowable(e))
}
}
}
}
fun revoke(token: String) {
val before = internal.value.invites
// Optimistic removal.
internal.update { it.copy(invites = before.filterNot { i -> i.token == token }) }
viewModelScope.launch {
runCatching { repository.revoke(token) }
.onFailure { refresh() }
init {
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.message != null) refresh()
}
}
}
fun refresh() {
viewModelScope.launch {
internal.update { it.copy(isLoading = true, message = null) }
try {
val rows = repository.list()
internal.update { it.copy(isLoading = false, invites = rows) }
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.update {
it.copy(
isLoading = false,
message = ErrorCopy.fromThrowable(e),
)
}
}
}
}
fun generate(note: String?) {
viewModelScope.launch {
try {
val invite = repository.create(note)
createdChannel.trySend(invite)
// Optimistically prepend; next refresh reconciles.
internal.update { it.copy(invites = listOf(invite) + it.invites) }
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.update {
it.copy(message = ErrorCopy.fromThrowable(e))
}
}
}
}
fun revoke(token: String) {
val before = internal.value.invites
// Optimistic removal.
internal.update { it.copy(invites = before.filterNot { i -> i.token == token }) }
viewModelScope.launch {
runCatching { repository.revoke(token) }
.onFailure { refresh() }
}
}
}
@@ -39,11 +39,11 @@ import com.fabledsword.minstrel.nav.AdminTagSources
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.EmptyState
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
@@ -56,11 +56,7 @@ import javax.inject.Inject
// ─── State ───────────────────────────────────────────────────────────
data class AdminCounts(
val quarantine: Int,
val users: Int,
val tagSources: Int,
)
data class AdminCounts(val quarantine: Int, val users: Int, val tagSources: Int)
/** The admin landing's counts, as the shared [UiState] (never Empty: it always has counts). */
typealias AdminLandingUiState = UiState<AdminCounts>
@@ -68,35 +64,32 @@ typealias AdminLandingUiState = UiState<AdminCounts>
// ─── ViewModel ───────────────────────────────────────────────────────
@HiltViewModel
class AdminLandingViewModel
@Inject
constructor(
private val quarantineRepo: AdminQuarantineRepository,
private val usersRepo: AdminUsersRepository,
private val tagSourcesRepo: AdminTagSourcesRepository,
) : ViewModel() {
private val internal = MutableStateFlow<AdminLandingUiState>(UiState.Loading)
val uiState: StateFlow<AdminLandingUiState> = internal.asStateFlow()
class AdminLandingViewModel @Inject constructor(
private val quarantineRepo: AdminQuarantineRepository,
private val usersRepo: AdminUsersRepository,
private val tagSourcesRepo: AdminTagSourcesRepository,
) : ViewModel() {
init {
refresh()
}
private val internal = MutableStateFlow<AdminLandingUiState>(UiState.Loading)
val uiState: StateFlow<AdminLandingUiState> = internal.asStateFlow()
fun refresh(): Job =
viewModelScope.launch {
internal.value = UiState.Loading
internal.value =
loadUiState {
coroutineScope {
val qua = async { quarantineRepo.list().size }
val usr = async { usersRepo.list().size }
val tag = async { tagSourcesRepo.list().count { it.enabled } }
UiState.Success(AdminCounts(qua.await(), usr.await(), tag.await()))
}
}
}
init {
refresh()
}
fun refresh(): Job = viewModelScope.launch {
internal.value = UiState.Loading
internal.value = loadUiState {
coroutineScope {
val qua = async { quarantineRepo.list().size }
val usr = async { usersRepo.list().size }
val tag = async { tagSourcesRepo.list().count { it.enabled } }
UiState.Success(AdminCounts(qua.await(), usr.await(), tag.await()))
}
}
}
}
// ─── Screen ──────────────────────────────────────────────────────────
@Composable
@@ -123,26 +116,21 @@ fun AdminLandingScreen(
) {
when (val s = state) {
UiState.Loading, UiState.Empty -> LoadingCentered()
is UiState.Error ->
EmptyState(
title = "Couldn't load admin counts",
body = s.message,
)
is UiState.Success ->
SectionList(
counts = s.data,
navController = navController,
)
is UiState.Error -> EmptyState(
title = "Couldn't load admin counts",
body = s.message,
)
is UiState.Success -> SectionList(
counts = s.data,
navController = navController,
)
}
}
}
}
@Composable
private fun SectionList(
counts: AdminCounts,
navController: NavHostController,
) {
private fun SectionList(counts: AdminCounts, navController: NavHostController) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(16.dp),
@@ -187,10 +175,9 @@ private fun SectionCard(
onClick: () -> Unit,
) {
ElevatedCard(
modifier =
Modifier
.fillMaxWidth()
.clickable(onClick = onClick),
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick),
) {
Row(
modifier = Modifier.padding(16.dp),
@@ -35,12 +35,12 @@ import com.fabledsword.minstrel.models.AdminQuarantineItemRef
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.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
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -74,26 +74,22 @@ fun AdminQuarantineScreen(
) {
when (val s = state) {
UiState.Loading -> LoadingCentered()
UiState.Empty ->
EmptyState(
title = "No reports",
body =
"When listeners flag a track as a bad rip, wrong tags or " +
"a duplicate, their reports gather here.",
)
is UiState.Error ->
ErrorRetry(
title = "Couldn't load queue",
message = s.message,
onRetry = { viewModel.refresh() },
)
is UiState.Success ->
QueueList(
rows = s.data,
onResolve = viewModel::resolve,
onRemoveFile = viewModel::removeFile,
onDeleteFile = viewModel::deleteFile,
)
UiState.Empty -> EmptyState(
title = "No reports",
body = "When listeners flag a track as a bad rip, wrong tags or " +
"a duplicate, their reports gather here.",
)
is UiState.Error -> ErrorRetry(
title = "Couldn't load queue",
message = s.message,
onRetry = { viewModel.refresh() },
)
is UiState.Success -> QueueList(
rows = s.data,
onResolve = viewModel::resolve,
onRemoveFile = viewModel::removeFile,
onDeleteFile = viewModel::deleteFile,
)
}
}
}
@@ -102,10 +98,7 @@ 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,
)
private data class PendingRemoval(val row: AdminQuarantineItemRef, val kind: Removal)
@Composable
private fun QueueList(
@@ -153,23 +146,20 @@ private fun RemovalConfirm(
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",
)
}
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,
@@ -187,10 +177,9 @@ private fun QuarantineRow(
onDeleteFile: () -> Unit,
) {
Column(
modifier =
Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
@@ -27,69 +27,62 @@ import javax.inject.Inject
typealias AdminQuarantineUiState = UiState<List<AdminQuarantineItemRef>>
@HiltViewModel
class AdminQuarantineViewModel
@Inject
constructor(
private val repository: AdminQuarantineRepository,
private val eventsStream: EventsStream,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow<AdminQuarantineUiState>(UiState.Loading)
val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow()
class AdminQuarantineViewModel @Inject constructor(
private val repository: AdminQuarantineRepository,
private val eventsStream: EventsStream,
networkStatus: NetworkStatusController,
) : ViewModel() {
/**
* 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 removal
* refused by a read-only library it hides the one thing an admin can fix.
*/
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED)
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
private val internal = MutableStateFlow<AdminQuarantineUiState>(UiState.Loading)
val uiState: StateFlow<AdminQuarantineUiState> = internal.asStateFlow()
init {
refresh()
viewModelScope.launch {
eventsStream.events
.filter { it.kind.startsWith("quarantine.") }
.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 UiState.Error) refresh()
}
}
/**
* 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 removal
* refused by a read-only library it hides the one thing an admin can fix.
*/
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED)
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
init {
refresh()
viewModelScope.launch {
eventsStream.events
.filter { it.kind.startsWith("quarantine.") }
.collect { refresh() }
}
fun refresh(): Job =
viewModelScope.launch {
internal.value = UiState.Loading
internal.value = loadUiState { repository.list().toListState() }
}
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) }
private fun act(
trackId: String,
action: suspend (String) -> Unit,
) {
val before = internal.value
if (before is UiState.Success) {
internal.value = before.data.filterNot { it.trackId == trackId }.toListState()
}
viewModelScope.launch {
try {
action(trackId)
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
transientMessagesChannel.trySend(ErrorCopy.fromThrowable(e))
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 UiState.Error) refresh()
}
}
}
fun refresh(): Job = viewModelScope.launch {
internal.value = UiState.Loading
internal.value = loadUiState { repository.list().toListState() }
}
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) }
private fun act(trackId: String, action: suspend (String) -> Unit) {
val before = internal.value
if (before is UiState.Success) {
internal.value = before.data.filterNot { it.trackId == trackId }.toListState()
}
viewModelScope.launch {
try {
action(trackId)
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
transientMessagesChannel.trySend(ErrorCopy.fromThrowable(e))
refresh()
}
}
}
}
@@ -36,12 +36,12 @@ import com.fabledsword.minstrel.models.AdminTagSourceRef
import com.fabledsword.minstrel.models.TagSourceTestResult
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.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
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -68,25 +68,22 @@ fun AdminTagSourcesScreen(
) {
when (val s = state) {
UiState.Loading -> LoadingCentered()
UiState.Empty ->
EmptyState(
title = "No tag sources",
body = "Tag-enrichment providers register on the server; none are available.",
)
is UiState.Error ->
ErrorRetry(
title = "Couldn't load tag sources",
message = s.message,
onRetry = { viewModel.refresh() },
)
is UiState.Success ->
TagSourceList(
providers = s.data.providers,
testResults = s.data.testResults,
onToggle = viewModel::setEnabled,
onSaveKey = viewModel::saveApiKey,
onTest = viewModel::test,
)
UiState.Empty -> EmptyState(
title = "No tag sources",
body = "Tag-enrichment providers register on the server; none are available.",
)
is UiState.Error -> ErrorRetry(
title = "Couldn't load tag sources",
message = s.message,
onRetry = { viewModel.refresh() },
)
is UiState.Success -> TagSourceList(
providers = s.data.providers,
testResults = s.data.testResults,
onToggle = viewModel::setEnabled,
onSaveKey = viewModel::saveApiKey,
onTest = viewModel::test,
)
}
}
}
@@ -159,10 +156,7 @@ private fun TagSourceCard(
}
@Composable
private fun ApiKeyRow(
provider: AdminTagSourceRef,
onSaveKey: (String, String) -> Unit,
) {
private fun ApiKeyRow(provider: AdminTagSourceRef, onSaveKey: (String, String) -> Unit) {
var key by remember(provider.id) { mutableStateOf("") }
OutlinedTextField(
value = key,
@@ -28,99 +28,86 @@ data class AdminTagSources(
typealias AdminTagSourcesUiState = UiState<AdminTagSources>
@HiltViewModel
class AdminTagSourcesViewModel
@Inject
constructor(
private val repository: AdminTagSourcesRepository,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow<AdminTagSourcesUiState>(UiState.Loading)
val uiState: StateFlow<AdminTagSourcesUiState> = internal.asStateFlow()
class AdminTagSourcesViewModel @Inject constructor(
private val repository: AdminTagSourcesRepository,
networkStatus: NetworkStatusController,
) : ViewModel() {
init {
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 UiState.Error) refresh()
}
private val internal = MutableStateFlow<AdminTagSourcesUiState>(UiState.Loading)
val uiState: StateFlow<AdminTagSourcesUiState> = internal.asStateFlow()
init {
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 UiState.Error) refresh()
}
}
fun refresh(): Job =
viewModelScope.launch {
internal.value = UiState.Loading
internal.value =
loadUiState {
val providers = repository.list()
if (providers.isEmpty()) UiState.Empty else UiState.Success(AdminTagSources(providers))
}
}
fun setEnabled(
id: String,
enabled: Boolean,
) {
val before = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
// Optimistic toggle; reconcile via refresh() if the server rejects.
internal.value =
UiState.Success(
before.copy(
providers =
before.providers.map {
if (it.id == id) it.copy(enabled = enabled) else it
},
),
)
viewModelScope.launch {
try {
repository.setEnabled(id, enabled)
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
refresh()
}
}
}
fun saveApiKey(
id: String,
apiKey: String,
) {
viewModelScope.launch {
try {
replaceProvider(repository.setApiKey(id, apiKey))
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
refresh()
}
}
}
fun test(id: String) {
viewModelScope.launch {
val result =
try {
repository.test(id)
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e))
}
val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return@launch
internal.value = UiState.Success(current.copy(testResults = current.testResults + (id to result)))
}
}
private fun replaceProvider(updated: AdminTagSourceRef) {
val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
internal.value =
UiState.Success(
current.copy(
providers = current.providers.map { if (it.id == updated.id) updated else it },
),
)
}
}
fun refresh(): Job = viewModelScope.launch {
internal.value = UiState.Loading
internal.value = loadUiState {
val providers = repository.list()
if (providers.isEmpty()) UiState.Empty else UiState.Success(AdminTagSources(providers))
}
}
fun setEnabled(id: String, enabled: Boolean) {
val before = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
// Optimistic toggle; reconcile via refresh() if the server rejects.
internal.value = UiState.Success(
before.copy(
providers = before.providers.map {
if (it.id == id) it.copy(enabled = enabled) else it
},
),
)
viewModelScope.launch {
try {
repository.setEnabled(id, enabled)
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
refresh()
}
}
}
fun saveApiKey(id: String, apiKey: String) {
viewModelScope.launch {
try {
replaceProvider(repository.setApiKey(id, apiKey))
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
refresh()
}
}
}
fun test(id: String) {
viewModelScope.launch {
val result = try {
repository.test(id)
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e))
}
val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return@launch
internal.value = UiState.Success(current.copy(testResults = current.testResults + (id to result)))
}
}
private fun replaceProvider(updated: AdminTagSourceRef) {
val current = (internal.value as? UiState.Success<AdminTagSources>)?.data ?: return
internal.value = UiState.Success(
current.copy(
providers = current.providers.map { if (it.id == updated.id) updated else it },
),
)
}
}
@@ -2,27 +2,37 @@
package com.fabledsword.minstrel.admin.ui
import android.content.ClipData
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.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.layout.size
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Copy
import com.composables.icons.lucide.KeyRound
import com.composables.icons.lucide.Plus
import com.composables.icons.lucide.Trash2
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import android.content.ClipData
import androidx.compose.ui.platform.ClipEntry
import androidx.compose.ui.platform.LocalClipboard
import com.fabledsword.minstrel.auth.PasswordRules
import com.fabledsword.minstrel.models.Invite
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
@@ -32,28 +42,19 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ClipEntry
import androidx.compose.ui.platform.LocalClipboard
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import com.composables.icons.lucide.Copy
import com.composables.icons.lucide.KeyRound
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.Plus
import com.composables.icons.lucide.Trash2
import com.fabledsword.minstrel.auth.PasswordRules
import com.fabledsword.minstrel.models.AdminUserRef
import com.fabledsword.minstrel.models.Invite
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.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import kotlinx.coroutines.launch
@Composable
@@ -174,15 +175,11 @@ private fun AdminUsersScaffold(
}
@Composable
private fun SectionHeader(
label: String,
trailing: (@Composable () -> Unit)? = null,
) {
private fun SectionHeader(label: String, trailing: (@Composable () -> Unit)? = null) {
Row(
modifier =
Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
@@ -205,16 +202,15 @@ private fun androidx.compose.foundation.lazy.LazyListScope.usersSection(
UiState.Loading -> item { CenteredHint("Loading users…") }
UiState.Empty -> item { CenteredHint("No registered users.") }
is UiState.Error -> item { CenteredHint(state.message) }
is UiState.Success ->
items(items = state.data, key = { it.id }) { user ->
UserRow(
user = user,
onSetAdmin = { onSetAdmin(user.id, it) },
onResetPassword = { onAskResetPassword(user) },
onDelete = { onAskDelete(user) },
)
HorizontalDivider()
}
is UiState.Success -> items(items = state.data, key = { it.id }) { user ->
UserRow(
user = user,
onSetAdmin = { onSetAdmin(user.id, it) },
onResetPassword = { onAskResetPassword(user) },
onDelete = { onAskDelete(user) },
)
HorizontalDivider()
}
}
}
@@ -224,15 +220,13 @@ private fun androidx.compose.foundation.lazy.LazyListScope.invitesSection(
) {
when {
state.isLoading -> item { CenteredHint("Loading invites…") }
state.invites.isEmpty() ->
item {
CenteredHint("No active invites. Use Generate to create one.")
}
else ->
items(items = state.invites, key = { it.token }) { invite ->
InviteRow(invite = invite, onRevoke = { onRevoke(invite.token) })
HorizontalDivider()
}
state.invites.isEmpty() -> item {
CenteredHint("No active invites. Use Generate to create one.")
}
else -> items(items = state.invites, key = { it.token }) { invite ->
InviteRow(invite = invite, onRevoke = { onRevoke(invite.token) })
HorizontalDivider()
}
}
}
@@ -247,15 +241,11 @@ private fun CenteredHint(text: String) {
}
@Composable
private fun InviteRow(
invite: Invite,
onRevoke: () -> Unit,
) {
private fun InviteRow(invite: Invite, onRevoke: () -> Unit) {
Row(
modifier =
Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(modifier = Modifier.weight(1f)) {
@@ -266,14 +256,13 @@ private fun InviteRow(
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
val subtitle =
buildString {
if (!invite.note.isNullOrEmpty()) {
append(invite.note)
append(" · ")
}
append(if (invite.isRedeemed) "redeemed" else "expires ${invite.expiresAt}")
val subtitle = buildString {
if (!invite.note.isNullOrEmpty()) {
append(invite.note)
append(" · ")
}
append(if (invite.isRedeemed) "redeemed" else "expires ${invite.expiresAt}")
}
Text(
text = subtitle,
style = MaterialTheme.typography.bodySmall,
@@ -295,10 +284,7 @@ private fun InviteRow(
}
@Composable
private fun GenerateInviteDialog(
onDismiss: () -> Unit,
onConfirm: (String?) -> Unit,
) {
private fun GenerateInviteDialog(onDismiss: () -> Unit, onConfirm: (String?) -> Unit) {
var note by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = onDismiss,
@@ -331,10 +317,7 @@ private fun GenerateInviteDialog(
}
@Composable
private fun GeneratedInviteDialog(
invite: Invite,
onDismiss: () -> Unit,
) {
private fun GeneratedInviteDialog(invite: Invite, onDismiss: () -> Unit) {
val clipboard = LocalClipboard.current
val scope = rememberCoroutineScope()
AlertDialog(
@@ -416,10 +399,9 @@ private fun UserRow(
onDelete: () -> Unit,
) {
Column(
modifier =
Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Text(
@@ -462,11 +444,7 @@ private fun UserRow(
}
@Composable
private fun ToggleRow(
label: String,
checked: Boolean,
onChange: (Boolean) -> Unit,
) {
private fun ToggleRow(label: String, checked: Boolean, onChange: (Boolean) -> Unit) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
@@ -518,9 +496,8 @@ private fun DeleteConfirmDialog(
) {
ConfirmDestructiveDialog(
title = "Delete user?",
text =
"Delete @${user.username}? This removes the account and all " +
"their data. Type $DELETE_CONFIRM_WORD to confirm.",
text = "Delete @${user.username}? This removes the account and all " +
"their data. Type $DELETE_CONFIRM_WORD to confirm.",
confirmLabel = "Delete",
onConfirm = onConfirm,
onDismiss = onDismiss,
@@ -529,3 +506,4 @@ private fun DeleteConfirmDialog(
}
private const val DELETE_CONFIRM_WORD = "DELETE"
@@ -21,86 +21,77 @@ import javax.inject.Inject
typealias AdminUsersUiState = UiState<List<AdminUserRef>>
@HiltViewModel
class AdminUsersViewModel
@Inject
constructor(
private val repository: AdminUsersRepository,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val internal = MutableStateFlow<AdminUsersUiState>(UiState.Loading)
val uiState: StateFlow<AdminUsersUiState> = internal.asStateFlow()
class AdminUsersViewModel @Inject constructor(
private val repository: AdminUsersRepository,
networkStatus: NetworkStatusController,
) : ViewModel() {
init {
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 UiState.Error) refresh()
}
}
}
private val internal = MutableStateFlow<AdminUsersUiState>(UiState.Loading)
val uiState: StateFlow<AdminUsersUiState> = internal.asStateFlow()
fun refresh(): Job =
viewModelScope.launch {
internal.value = UiState.Loading
internal.value = loadUiState { repository.list().toListState() }
}
fun setAdmin(
id: String,
isAdmin: Boolean,
) = patch(id, { it.copy(isAdmin = isAdmin) }) {
repository.setAdmin(it, isAdmin)
}
fun resetPassword(
id: String,
newPassword: String,
) {
viewModelScope.launch {
runCatching { repository.resetPassword(id, newPassword) }
}
}
fun delete(id: String) {
val before = internal.value
if (before is UiState.Success) {
internal.value = before.data.filterNot { it.id == id }.toListState()
}
viewModelScope.launch {
try {
repository.delete(id)
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
refresh()
}
}
}
private fun patch(
id: String,
mutate: (AdminUserRef) -> AdminUserRef,
action: suspend (String) -> Unit,
) {
val before = internal.value
if (before is UiState.Success) {
internal.value =
UiState.Success(
before.data.map { if (it.id == id) mutate(it) else it },
)
}
viewModelScope.launch {
try {
action(id)
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
// Server-side guard might have rejected the toggle (e.g.
// last-admin protection); refetch reconciles state.
refresh()
}
init {
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 UiState.Error) refresh()
}
}
}
fun refresh(): Job = viewModelScope.launch {
internal.value = UiState.Loading
internal.value = loadUiState { repository.list().toListState() }
}
fun setAdmin(id: String, isAdmin: Boolean) = patch(id, { it.copy(isAdmin = isAdmin) }) {
repository.setAdmin(it, isAdmin)
}
fun resetPassword(id: String, newPassword: String) {
viewModelScope.launch {
runCatching { repository.resetPassword(id, newPassword) }
}
}
fun delete(id: String) {
val before = internal.value
if (before is UiState.Success) {
internal.value = before.data.filterNot { it.id == id }.toListState()
}
viewModelScope.launch {
try {
repository.delete(id)
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
refresh()
}
}
}
private fun patch(
id: String,
mutate: (AdminUserRef) -> AdminUserRef,
action: suspend (String) -> Unit,
) {
val before = internal.value
if (before is UiState.Success) {
internal.value = UiState.Success(
before.data.map { if (it.id == id) mutate(it) else it },
)
}
viewModelScope.launch {
try {
action(id)
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
// Server-side guard might have rejected the toggle (e.g.
// last-admin protection); refetch reconciles state.
refresh()
}
}
}
}
@@ -20,47 +20,43 @@ import javax.inject.Singleton
* from any of those hosts would sign the user out of Minstrel.
*/
@Singleton
class AuthCookieInterceptor
@Inject
constructor(
private val authStore: AuthStore,
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
if (original.url.host != BaseUrlInterceptor.PLACEHOLDER_HOST) {
// External request — no Minstrel session cookie attached,
// and a 401 from this host does NOT clear the user's
// session. Pass through untouched.
return chain.proceed(original)
}
val cookie = authStore.sessionCookieForRequest()
val request =
original
.newBuilder()
.apply {
if (!cookie.isNullOrEmpty()) header("Cookie", cookie)
}.build()
class AuthCookieInterceptor @Inject constructor(
private val authStore: AuthStore,
) : Interceptor {
val response = chain.proceed(request)
if (response.code == HTTP_UNAUTHORIZED) {
// Only a refusal of the cookie this request carried ends the
// session. A request sent without one says nothing about the
// stored login, and a refusal of an older cookie must not
// discard one a sign-in has stored since.
if (!cookie.isNullOrEmpty()) authStore.dropRejectedSessionCookie(cookie)
} else if (response.isSuccessful) {
// Capture the first Set-Cookie pair on login; subsequent
// responses that include Set-Cookie keep the store fresh.
response.headers("Set-Cookie").firstOrNull()?.let { sc ->
val firstPair = sc.substringBefore(';')
if (firstPair.isNotBlank()) authStore.setSessionCookie(firstPair)
}
}
return response
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
if (original.url.host != BaseUrlInterceptor.PLACEHOLDER_HOST) {
// External request — no Minstrel session cookie attached,
// and a 401 from this host does NOT clear the user's
// session. Pass through untouched.
return chain.proceed(original)
}
val cookie = authStore.sessionCookieForRequest()
val request = original.newBuilder().apply {
if (!cookie.isNullOrEmpty()) header("Cookie", cookie)
}.build()
private companion object {
const val HTTP_UNAUTHORIZED = 401
val response = chain.proceed(request)
if (response.code == HTTP_UNAUTHORIZED) {
// Only a refusal of the cookie this request carried ends the
// session. A request sent without one says nothing about the
// stored login, and a refusal of an older cookie must not
// discard one a sign-in has stored since.
if (!cookie.isNullOrEmpty()) authStore.dropRejectedSessionCookie(cookie)
} else if (response.isSuccessful) {
// Capture the first Set-Cookie pair on login; subsequent
// responses that include Set-Cookie keep the store fresh.
response.headers("Set-Cookie").firstOrNull()?.let { sc ->
val firstPair = sc.substringBefore(';')
if (firstPair.isNotBlank()) authStore.setSessionCookie(firstPair)
}
}
return response
}
private companion object {
const val HTTP_UNAUTHORIZED = 401
}
}
@@ -31,43 +31,39 @@ import javax.inject.Singleton
* error in the caller's normal error path.
*/
@Singleton
class BaseUrlInterceptor
@Inject
constructor(
private val authStore: AuthStore,
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
// Early-bail keeps the no-op path for external URLs cheap
// (no AuthStore read, no URL parse).
if (original.url.host != PLACEHOLDER_HOST) return chain.proceed(original)
// Unparseable baseUrl folds into the same proceed path — keeps
// detekt's ReturnCount happy by avoiding a second early return.
val rewritten: HttpUrl =
authStore.baseUrl.value.toHttpUrlOrNull()?.let { baseUrl ->
original.url
.newBuilder()
.scheme(baseUrl.scheme)
.host(baseUrl.host)
.port(baseUrl.port)
.build()
} ?: original.url
return chain.proceed(
original
.newBuilder()
.url(rewritten)
// Lets CleartextGuardInterceptor tell server requests from
// external fetches once the placeholder host is gone.
.tag(MinstrelServerRequest::class.java, MinstrelServerRequest)
.build(),
)
}
class BaseUrlInterceptor @Inject constructor(
private val authStore: AuthStore,
) : Interceptor {
companion object {
/** Sentinel host used by Retrofit + every code path that builds
* a Minstrel-server URL via the `http://placeholder.invalid/...`
* form (see [com.fabledsword.minstrel.shared.resolveServerUrl],
* CoverUrls.kt, AlbumRef/TrackRef cover getters). */
const val PLACEHOLDER_HOST = "placeholder.invalid"
}
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
// Early-bail keeps the no-op path for external URLs cheap
// (no AuthStore read, no URL parse).
if (original.url.host != PLACEHOLDER_HOST) return chain.proceed(original)
// Unparseable baseUrl folds into the same proceed path — keeps
// detekt's ReturnCount happy by avoiding a second early return.
val rewritten: HttpUrl = authStore.baseUrl.value.toHttpUrlOrNull()?.let { baseUrl ->
original.url.newBuilder()
.scheme(baseUrl.scheme)
.host(baseUrl.host)
.port(baseUrl.port)
.build()
} ?: original.url
return chain.proceed(
original.newBuilder()
.url(rewritten)
// Lets CleartextGuardInterceptor tell server requests from
// external fetches once the placeholder host is gone.
.tag(MinstrelServerRequest::class.java, MinstrelServerRequest)
.build(),
)
}
companion object {
/** Sentinel host used by Retrofit + every code path that builds
* a Minstrel-server URL via the `http://placeholder.invalid/...`
* form (see [com.fabledsword.minstrel.shared.resolveServerUrl],
* CoverUrls.kt, AlbumRef/TrackRef cover getters). */
const val PLACEHOLDER_HOST = "placeholder.invalid"
}
}
@@ -39,12 +39,7 @@ class CleartextGuardInterceptor(
if (request.isHttps || request.tag(MinstrelServerRequest::class.java) == null) {
return chain.proceed(request)
}
val address =
chain
.connection()
?.route()
?.socketAddress
?.address
val address = chain.connection()?.route()?.socketAddress?.address
if (address != null && !allows(address)) {
throw CleartextToPublicHostException(request.url.host)
}
@@ -53,9 +48,8 @@ class CleartextGuardInterceptor(
}
/** The server was reached over plain HTTP at a public address, and refused. */
class CleartextToPublicHostException(
host: String,
) : IOException("refusing plain http:// to $host: it is a public address")
class CleartextToPublicHostException(host: String) :
IOException("refusing plain http:// to $host: it is a public address")
/** Which addresses plain HTTP may reach: the home network, never the internet. */
object CleartextPolicy {
@@ -68,10 +62,8 @@ object CleartextPolicy {
fun allows(address: InetAddress): Boolean =
address.isLoopbackAddress ||
address.isSiteLocalAddress ||
// 10/8, 172.16/12, 192.168/16
address.isLinkLocalAddress ||
// 169.254/16, fe80::/10
address.isSiteLocalAddress || // 10/8, 172.16/12, 192.168/16
address.isLinkLocalAddress || // 169.254/16, fe80::/10
address.isAnyLocalAddress ||
isCarrierGradeNat(address) ||
isUniqueLocal(address)
@@ -1,5 +1,6 @@
package com.fabledsword.minstrel.api
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import retrofit2.HttpException
@@ -22,15 +23,10 @@ object ErrorCopy {
private val json = Json { ignoreUnknownKeys = true }
@Serializable
private data class Envelope(
val error: Body? = null,
)
private data class Envelope(val error: Body? = null)
@Serializable
private data class Body(
val code: String = "",
val message: String = "",
)
private data class Body(val code: String = "", val message: String = "")
/** Friendly copy for a known error [code], or the `unknown` fallback. */
fun messageFor(code: String): String = TABLE[code] ?: TABLE.getValue("unknown")
@@ -40,13 +36,12 @@ object ErrorCopy {
* HttpException bodies for the server code; treats IOExceptions
* as connection failures.
*/
fun fromThrowable(t: Throwable): String =
when (t) {
is HttpException -> fromHttp(t)
is CleartextToPublicHostException -> messageFor("cleartext_public")
is IOException -> messageFor("connection_refused")
else -> TABLE.getValue("unknown")
}
fun fromThrowable(t: Throwable): String = when (t) {
is HttpException -> fromHttp(t)
is CleartextToPublicHostException -> messageFor("cleartext_public")
is IOException -> messageFor("connection_refused")
else -> TABLE.getValue("unknown")
}
/**
* Codes whose server message carries specifics an admin needs in order
@@ -70,9 +65,8 @@ object ErrorCopy {
}
private fun bodyFromHttp(e: HttpException): Body {
val raw =
runCatching { e.response()?.errorBody()?.string() }.getOrNull()
?: return Body()
val raw = runCatching { e.response()?.errorBody()?.string() }.getOrNull()
?: return Body()
return runCatching { json.decodeFromString<Envelope>(raw).error }
.getOrNull() ?: Body()
}
@@ -28,6 +28,7 @@ import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideHttpLogging(): HttpLoggingInterceptor =
@@ -48,8 +49,7 @@ object NetworkModule {
reachability: ReachabilityReportingInterceptor,
logging: HttpLoggingInterceptor,
): OkHttpClient =
OkHttpClient
.Builder()
OkHttpClient.Builder()
// ReachabilityReportingInterceptor MUST run first: it identifies
// Minstrel-bound requests by the still-unrewritten PLACEHOLDER_HOST
// (so external artwork fetches don't read as server reachability)
@@ -82,8 +82,7 @@ object NetworkModule {
okHttp: OkHttpClient,
json: Json,
): Retrofit =
Retrofit
.Builder()
Retrofit.Builder()
// Placeholder base URL — BaseUrlInterceptor rewrites every
// outgoing request to the live AuthStore value, so this
// string only has to satisfy Retrofit's parser and is
@@ -6,6 +6,4 @@ package com.fabledsword.minstrel.api
* the graph.
*/
@JvmInline
value class ServerBaseUrl(
val value: String,
)
value class ServerBaseUrl(val value: String)
@@ -20,14 +20,10 @@ interface AdminInvitesApi {
suspend fun list(): AdminInvitesListWire
@POST("api/admin/invites")
suspend fun create(
@Body body: CreateInviteBody,
): InviteWire
suspend fun create(@Body body: CreateInviteBody): InviteWire
@DELETE("api/admin/invites/{token}")
suspend fun revoke(
@Path("token") token: String,
)
suspend fun revoke(@Path("token") token: String)
}
/**
@@ -35,6 +31,4 @@ interface AdminInvitesApi {
* which the server treats the same as an absent field.
*/
@Serializable
data class CreateInviteBody(
val note: String? = null,
)
data class CreateInviteBody(val note: String? = null)
@@ -19,17 +19,11 @@ interface AdminQuarantineApi {
suspend fun list(): List<AdminQuarantineItemWire>
@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,
)
suspend fun removeFile(@Path("trackId") trackId: String)
@POST("api/admin/quarantine/{trackId}/delete-file")
suspend fun deleteFile(
@Path("trackId") trackId: String,
)
suspend fun deleteFile(@Path("trackId") trackId: String)
}
@@ -23,15 +23,10 @@ interface AdminTagSourcesApi {
suspend fun list(): AdminTagSourcesListWire
@PATCH("api/admin/tag-sources/{id}")
suspend fun update(
@Path("id") id: String,
@Body body: UpdateTagSourceBody,
): AdminTagSourceWire
suspend fun update(@Path("id") id: String, @Body body: UpdateTagSourceBody): AdminTagSourceWire
@POST("api/admin/tag-sources/{id}/test")
suspend fun test(
@Path("id") id: String,
): TestTagSourceWire
suspend fun test(@Path("id") id: String): TestTagSourceWire
}
/**
@@ -15,21 +15,13 @@ interface AdminUsersApi {
suspend fun list(): AdminUsersListWire
@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)
@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)
@DELETE("api/admin/users/{id}")
suspend fun delete(
@Path("id") id: String,
)
suspend fun delete(@Path("id") id: String)
}
@Serializable
@@ -38,6 +30,4 @@ data class SetAdminBody(
)
@Serializable
data class ResetPasswordBody(
val password: String,
)
data class ResetPasswordBody(val password: String)
@@ -14,9 +14,7 @@ import retrofit2.http.POST
*/
interface AuthApi {
@POST("api/auth/login")
suspend fun login(
@Body body: LoginRequestBody,
): LoginResponseWire
suspend fun login(@Body body: LoginRequestBody): LoginResponseWire
@POST("api/auth/logout")
suspend fun logout()
@@ -22,9 +22,7 @@ import retrofit2.http.POST
*/
interface CastApi {
@POST("api/cast/stream-token")
suspend fun streamToken(
@Body req: StreamTokenRequest,
): StreamTokenResponse
suspend fun streamToken(@Body req: StreamTokenRequest): StreamTokenResponse
}
/**
@@ -14,9 +14,7 @@ import retrofit2.http.POST
*/
interface DiagnosticsApi {
@POST("api/diagnostics")
suspend fun report(
@Body body: DiagnosticsReportRequest,
)
suspend fun report(@Body body: DiagnosticsReportRequest)
}
@Serializable
@@ -17,22 +17,14 @@ import retrofit2.http.POST
*/
interface EventsApi {
@POST("api/events")
suspend fun playStarted(
@Body body: PlayStartedRequest,
): PlayStartedResponse
suspend fun playStarted(@Body body: PlayStartedRequest): PlayStartedResponse
@POST("api/events")
suspend fun playEnded(
@Body body: PlayEndedRequest,
)
suspend fun playEnded(@Body body: PlayEndedRequest)
@POST("api/events")
suspend fun playSkipped(
@Body body: PlaySkippedRequest,
)
suspend fun playSkipped(@Body body: PlaySkippedRequest)
@POST("api/events")
suspend fun playOffline(
@Body body: PlayOfflineRequest,
)
suspend fun playOffline(@Body body: PlayOfflineRequest)
}
@@ -30,19 +30,13 @@ import retrofit2.http.Query
*/
interface LibraryApi {
@GET("api/tracks/{id}")
suspend fun getTrack(
@Path("id") id: String,
): TrackWire
suspend fun getTrack(@Path("id") id: String): TrackWire
@GET("api/artists/{id}")
suspend fun getArtistDetail(
@Path("id") id: String,
): ArtistDetailWire
suspend fun getArtistDetail(@Path("id") id: String): ArtistDetailWire
@GET("api/artists/{id}/tracks")
suspend fun getArtistTracks(
@Path("id") id: String,
): List<TrackWire>
suspend fun getArtistTracks(@Path("id") id: String): List<TrackWire>
@GET("api/artists/{id}/similar")
suspend fun getSimilarArtists(
@@ -57,14 +51,10 @@ interface LibraryApi {
): List<TrackWire>
@GET("api/albums/{id}")
suspend fun getAlbumDetail(
@Path("id") id: String,
): AlbumDetailWire
suspend fun getAlbumDetail(@Path("id") id: String): AlbumDetailWire
@GET("api/library/shuffle")
suspend fun shuffleLibrary(
@Query("limit") limit: Int = 100,
): List<TrackWire>
suspend fun shuffleLibrary(@Query("limit") limit: Int = 100): List<TrackWire>
// Browse axes. Both indexes are unpaged by design: the client needs
// the whole set to render a browsable picker, and even a messy library
@@ -20,16 +20,10 @@ import retrofit2.http.Path
*/
interface LikesApi {
@POST("api/likes/{kind}/{id}")
suspend fun like(
@Path("kind") kind: String,
@Path("id") id: String,
)
suspend fun like(@Path("kind") kind: String, @Path("id") id: String)
@DELETE("api/likes/{kind}/{id}")
suspend fun unlike(
@Path("kind") kind: String,
@Path("id") id: String,
)
suspend fun unlike(@Path("kind") kind: String, @Path("id") id: String)
@GET("api/likes/ids")
suspend fun ids(): LikedIdsWire
@@ -27,18 +27,14 @@ interface MeApi {
* state without an extra GET.
*/
@PUT("api/me/profile")
suspend fun updateProfile(
@Body body: UpdateProfileRequest,
): MyProfileWire
suspend fun updateProfile(@Body body: UpdateProfileRequest): MyProfileWire
/**
* Change the caller's password. Server validates `current_password`
* before accepting `new_password`. No body on success (204).
*/
@PUT("api/me/password")
suspend fun changePassword(
@Body body: ChangePasswordRequest,
)
suspend fun changePassword(@Body body: ChangePasswordRequest)
/**
* Caller's ListenBrainz state — never returns the token itself,
@@ -63,9 +59,7 @@ interface MeApi {
* post-write status so callers refresh without a separate GET.
*/
@PUT("api/me/listenbrainz")
suspend fun setListenBrainz(
@Body body: ListenBrainzPutBody,
): ListenBrainzStatusWire
suspend fun setListenBrainz(@Body body: ListenBrainzPutBody): ListenBrainzStatusWire
/** The caller's loudness-normalization preference, or the defaults if never set. */
@GET("api/me/normalization")
@@ -73,9 +67,7 @@ interface MeApi {
/** Replaces the whole preference; returns what the server stored. */
@PUT("api/me/normalization")
suspend fun putNormalization(
@Body body: NormalizationPrefs,
): NormalizationPrefs
suspend fun putNormalization(@Body body: NormalizationPrefs): NormalizationPrefs
}
/**
@@ -15,28 +15,20 @@ import retrofit2.http.Query
*/
interface NotificationsApi {
@GET("api/me/notifications")
suspend fun list(
@Query("limit") limit: Int,
): NotificationsPageWire
suspend fun list(@Query("limit") limit: Int): NotificationsPageWire
/** 204; 404 when the notice is gone, which a replay treats as done. */
@POST("api/me/notifications/{id}/read")
suspend fun markRead(
@Path("id") id: String,
)
suspend fun markRead(@Path("id") id: String)
@POST("api/me/notifications/read-all")
suspend fun readAll(
@Body body: ReadAllBody,
)
suspend fun readAll(@Body body: ReadAllBody)
@GET("api/me/notification-settings")
suspend fun getSettings(): NotificationSettingsWire
@PUT("api/me/notification-settings")
suspend fun putSettings(
@Body body: PutNotificationSettingsBody,
): NotificationSettingsWire
suspend fun putSettings(@Body body: PutNotificationSettingsBody): NotificationSettingsWire
}
@Serializable
@@ -63,9 +55,7 @@ data class NotificationsPageWire(
* the app's Json drops default-valued fields.
*/
@Serializable
data class ReadAllBody(
@SerialName("up_to") val upTo: String?,
)
data class ReadAllBody(@SerialName("up_to") val upTo: String?)
@Serializable
data class NotificationKindSettingWire(
@@ -97,6 +87,4 @@ data class NotificationSettingChangeWire(
)
@Serializable
data class PutNotificationSettingsBody(
val kinds: List<NotificationSettingChangeWire>,
)
data class PutNotificationSettingsBody(val kinds: List<NotificationSettingChangeWire>)
@@ -13,9 +13,7 @@ import retrofit2.http.POST
*/
interface PlaybackErrorsApi {
@POST("api/playback-errors")
suspend fun report(
@Body body: PlaybackErrorReportRequest,
)
suspend fun report(@Body body: PlaybackErrorReportRequest)
}
/**
@@ -24,35 +24,24 @@ interface PlaylistsApi {
* playlists (not kind-filtered).
*/
@GET("api/playlists")
suspend fun list(
@Query("kind") kind: String = "all",
): PlaylistsListWire
suspend fun list(@Query("kind") kind: String = "all"): PlaylistsListWire
@GET("api/playlists/{id}")
suspend fun get(
@Path("id") id: String,
): PlaylistDetailWire
suspend fun get(@Path("id") id: String): PlaylistDetailWire
/**
* POST /api/playlists — make a playlist under the id the app chose,
* so a create queued offline and sent again finds the same list.
*/
@POST("api/playlists")
suspend fun create(
@Body body: CreatePlaylistRequest,
)
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,
)
suspend fun update(@Path("id") id: String, @Body body: UpdatePlaylistRequest)
@DELETE("api/playlists/{id}")
suspend fun delete(
@Path("id") id: String,
)
suspend fun delete(@Path("id") id: String)
/**
* DELETE /api/playlists/{id}/tracks/{position}. [trackId] is the song
@@ -73,10 +62,7 @@ interface PlaylistsApi {
* changes nothing the second time.
*/
@PUT("api/playlists/{id}/tracks")
suspend fun reorder(
@Path("id") id: String,
@Body body: ReorderTracksRequest,
)
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")
@@ -93,9 +79,7 @@ interface PlaylistsApi {
* pick seed tracks. The kind is the raw system_variant.
*/
@POST("api/playlists/system/{kind}/refresh")
suspend fun refreshSystem(
@Path("kind") variant: String,
): RefreshSystemResponse
suspend fun refreshSystem(@Path("kind") variant: String): RefreshSystemResponse
/**
* GET /api/playlists/system/{kind}/shuffle. Returns
@@ -105,9 +89,7 @@ interface PlaylistsApi {
* the stored order.
*/
@GET("api/playlists/system/{kind}/shuffle")
suspend fun systemShuffle(
@Path("kind") variant: String,
): PlaylistDetailWire
suspend fun systemShuffle(@Path("kind") variant: String): PlaylistDetailWire
}
/**
@@ -20,14 +20,10 @@ interface QuarantineApi {
suspend fun listMine(): List<QuarantineMineWire>
@POST("api/quarantine")
suspend fun flag(
@Body body: FlagRequest,
)
suspend fun flag(@Body body: FlagRequest)
@DELETE("api/quarantine/{trackId}")
suspend fun unflag(
@Path("trackId") trackId: String,
)
suspend fun unflag(@Path("trackId") trackId: String)
}
/**
@@ -11,7 +11,5 @@ interface ReplayGainApi {
* missing from `items` has not been measured yet.
*/
@GET("api/tracks/replay-gain")
suspend fun getReplayGain(
@Query("ids") ids: String,
): ReplayGainResponseWire
suspend fun getReplayGain(@Query("ids") ids: String): ReplayGainResponseWire
}
@@ -19,7 +19,5 @@ import retrofit2.http.Query
*/
interface SyncApi {
@GET("api/library/sync")
suspend fun sync(
@Query("since") since: Long,
): Response<SyncResponseWire>
suspend fun sync(@Query("since") since: Long): Response<SyncResponseWire>
}
@@ -29,124 +29,114 @@ import javax.inject.Singleton
* username after a fresh app launch without re-prompting.
*/
@Singleton
class AuthController
@Inject
constructor(
private val authStore: AuthStore,
private val json: Json,
@ApplicationScope private val scope: CoroutineScope,
retrofit: Retrofit,
) {
private val api: AuthApi = retrofit.create()
private val meApi: MeApi = retrofit.create()
class AuthController @Inject constructor(
private val authStore: AuthStore,
private val json: Json,
@ApplicationScope private val scope: CoroutineScope,
retrofit: Retrofit,
) {
private val api: AuthApi = retrofit.create()
private val meApi: MeApi = retrofit.create()
private val currentUserState = MutableStateFlow<UserRef?>(null)
val currentUser: StateFlow<UserRef?> = currentUserState.asStateFlow()
private val currentUserState = MutableStateFlow<UserRef?>(null)
val currentUser: StateFlow<UserRef?> = currentUserState.asStateFlow()
val sessionCookie: StateFlow<String?> get() = authStore.sessionCookie
val sessionCookie: StateFlow<String?> get() = authStore.sessionCookie
val isSignedIn: Boolean
get() = !authStore.sessionCookie.value.isNullOrEmpty()
val isSignedIn: Boolean
get() = !authStore.sessionCookie.value.isNullOrEmpty()
init {
// Rehydrate currentUser whenever the persisted userJson emits
// (cold start with a saved cookie OR explicit sign-in/out
// writing through AuthStore). Decode failures collapse to null
// so a malformed row can't crash the app — worst case is a
// blank username until the next sign-in writes a valid value.
scope.launch {
authStore.userJson.collect { raw ->
currentUserState.value = raw?.let { decodeUser(it) }
}
init {
// Rehydrate currentUser whenever the persisted userJson emits
// (cold start with a saved cookie OR explicit sign-in/out
// writing through AuthStore). Decode failures collapse to null
// so a malformed row can't crash the app — worst case is a
// blank username until the next sign-in writes a valid value.
scope.launch {
authStore.userJson.collect { raw ->
currentUserState.value = raw?.let { decodeUser(it) }
}
// Refresh from /api/me on startup so a remotely-changed account
// flag (e.g. an admin enabling debug mode) reaches the device
// without a re-login. Best-effort; failures keep the cached value.
scope.launch { refreshProfile() }
}
/**
* Submit credentials. On success the AuthCookieInterceptor will
* have captured the Set-Cookie before this method returns; the
* caller can safely navigate to the in-shell graph. Throws on
* any non-2xx response (caller surfaces in UI).
*/
suspend fun signIn(
username: String,
password: String,
): UserRef {
val response = api.login(LoginRequestBody(username = username, password = password))
val user =
UserRef(
id = response.user.id,
username = response.user.username,
isAdmin = response.user.isAdmin,
)
currentUserState.value = user
authStore.setUserJson(json.encodeToString(UserRef.serializer(), user))
// Pull the fuller /me shape (carries debug_mode_enabled) right
// after login so the diagnostics gate is correct without waiting
// for the next startup refresh.
scope.launch { refreshProfile() }
return user
}
/**
* Re-fetch the caller's profile from /api/me and update currentUser
* + persisted userJson. Carries account-level flags (debug mode)
* that aren't in the login response. Best-effort: a network failure
* leaves the cached identity untouched. No-op when signed out.
* Waits for the stored login to load first: at launch this runs before
* it has, and would otherwise read the user as signed out and skip.
*/
suspend fun refreshProfile() {
authStore.awaitSessionHydrated()
if (!isSignedIn) return
val p = runCatching { meApi.getProfile() }.getOrNull() ?: return
val user =
UserRef(
id = p.id,
username = p.username,
isAdmin = p.isAdmin,
debugModeEnabled = p.debugModeEnabled,
)
currentUserState.value = user
authStore.setUserJson(json.encodeToString(UserRef.serializer(), user))
}
/**
* Signs out here at once and ends the session on the server too.
*
* The app shows signed-out straight away, then calls
* `/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() {
currentUserState.value = null
authStore.setUserJson(null)
scope
.launch {
try {
withTimeoutOrNull(LOGOUT_TIMEOUT_MS) { runCatching { api.logout() } }
} finally {
authStore.setSessionCookie(null)
}
}.join()
}
private fun decodeUser(raw: String): UserRef? =
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
}
// Refresh from /api/me on startup so a remotely-changed account
// flag (e.g. an admin enabling debug mode) reaches the device
// without a re-login. Best-effort; failures keep the cached value.
scope.launch { refreshProfile() }
}
/**
* Submit credentials. On success the AuthCookieInterceptor will
* have captured the Set-Cookie before this method returns; the
* caller can safely navigate to the in-shell graph. Throws on
* any non-2xx response (caller surfaces in UI).
*/
suspend fun signIn(username: String, password: String): UserRef {
val response = api.login(LoginRequestBody(username = username, password = password))
val user = UserRef(
id = response.user.id,
username = response.user.username,
isAdmin = response.user.isAdmin,
)
currentUserState.value = user
authStore.setUserJson(json.encodeToString(UserRef.serializer(), user))
// Pull the fuller /me shape (carries debug_mode_enabled) right
// after login so the diagnostics gate is correct without waiting
// for the next startup refresh.
scope.launch { refreshProfile() }
return user
}
/**
* Re-fetch the caller's profile from /api/me and update currentUser
* + persisted userJson. Carries account-level flags (debug mode)
* that aren't in the login response. Best-effort: a network failure
* leaves the cached identity untouched. No-op when signed out.
* Waits for the stored login to load first: at launch this runs before
* it has, and would otherwise read the user as signed out and skip.
*/
suspend fun refreshProfile() {
authStore.awaitSessionHydrated()
if (!isSignedIn) return
val p = runCatching { meApi.getProfile() }.getOrNull() ?: return
val user = UserRef(
id = p.id,
username = p.username,
isAdmin = p.isAdmin,
debugModeEnabled = p.debugModeEnabled,
)
currentUserState.value = user
authStore.setUserJson(json.encodeToString(UserRef.serializer(), user))
}
/**
* Signs out here at once and ends the session on the server too.
*
* The app shows signed-out straight away, then calls
* `/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() {
currentUserState.value = null
authStore.setUserJson(null)
scope.launch {
try {
withTimeoutOrNull(LOGOUT_TIMEOUT_MS) { runCatching { api.logout() } }
} finally {
authStore.setSessionCookie(null)
}
}.join()
}
private fun decodeUser(raw: String): UserRef? =
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
}
}
@@ -21,14 +21,6 @@ import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
// AuthStore is the single-row facade over auth_session (de-facto
// app_preferences — see entity comment). It legitimately owns one
// getter + one setter + one persist helper per pref column; the
// function count scales with the pref count, not with feature
// complexity. Splitting into per-pref stores would scatter the
// shared dao + scope + json plumbing for no real gain. Suppress
// the cap rather than fragment.
/**
* Holds the user's session cookie and configured server base URL.
*
@@ -52,352 +44,353 @@ import javax.inject.Singleton
* [awaitSessionHydrated] lets a caller that needs a definitive answer
* (the auth gate) wait for this.
*/
// AuthStore is the single-row facade over auth_session (de-facto
// app_preferences — see entity comment). It legitimately owns one
// getter + one setter + one persist helper per pref column; the
// function count scales with the pref count, not with feature
// complexity. Splitting into per-pref stores would scatter the
// shared dao + scope + json plumbing for no real gain. Suppress
// the cap rather than fragment.
@Suppress("TooManyFunctions")
@Singleton
class AuthStore
@Inject
constructor(
private val dao: AuthSessionDao,
private val vault: SessionVault,
@ApplicationScope private val scope: CoroutineScope,
) {
private val sessionCookieState = MutableStateFlow<String?>(null)
val sessionCookie: StateFlow<String?> = sessionCookieState.asStateFlow()
class AuthStore @Inject constructor(
private val dao: AuthSessionDao,
private val vault: SessionVault,
@ApplicationScope private val scope: CoroutineScope,
) {
private val sessionCookieState = MutableStateFlow<String?>(null)
val sessionCookie: StateFlow<String?> = sessionCookieState.asStateFlow()
private val baseUrlState = MutableStateFlow(DEFAULT_BASE_URL)
val baseUrl: StateFlow<String> = baseUrlState.asStateFlow()
private val baseUrlState = MutableStateFlow(DEFAULT_BASE_URL)
val baseUrl: StateFlow<String> = baseUrlState.asStateFlow()
private val userJsonState = MutableStateFlow<String?>(null)
val userJson: StateFlow<String?> = userJsonState.asStateFlow()
private val userJsonState = MutableStateFlow<String?>(null)
val userJson: StateFlow<String?> = userJsonState.asStateFlow()
private val themeModeState = MutableStateFlow<String?>(null)
val themeMode: StateFlow<String?> = themeModeState.asStateFlow()
private val themeModeState = MutableStateFlow<String?>(null)
val themeMode: StateFlow<String?> = themeModeState.asStateFlow()
private val clientIdState = MutableStateFlow<String?>(null)
val clientId: StateFlow<String?> = clientIdState.asStateFlow()
private val clientIdState = MutableStateFlow<String?>(null)
val clientId: StateFlow<String?> = clientIdState.asStateFlow()
private val cacheSettingsState = MutableStateFlow(CacheSettings.DEFAULT)
val cacheSettings: StateFlow<CacheSettings> = cacheSettingsState.asStateFlow()
private val cacheSettingsState = MutableStateFlow(CacheSettings.DEFAULT)
val cacheSettings: StateFlow<CacheSettings> = cacheSettingsState.asStateFlow()
private val diagnosticsOptOutState = MutableStateFlow(false)
val diagnosticsOptOut: StateFlow<Boolean> = diagnosticsOptOutState.asStateFlow()
private val diagnosticsOptOutState = MutableStateFlow(false)
val diagnosticsOptOut: StateFlow<Boolean> = diagnosticsOptOutState.asStateFlow()
private val normalizationState = MutableStateFlow(NormalizationPrefs.DEFAULT)
val normalization: StateFlow<NormalizationPrefs> = normalizationState.asStateFlow()
private val normalizationState = MutableStateFlow(NormalizationPrefs.DEFAULT)
val normalization: StateFlow<NormalizationPrefs> = normalizationState.asStateFlow()
// Background delivery: the device's choice, on by default.
// The shade's high-water mark lives in the same row but is read and
// written through the DAO by NotificationSync, awaited, never cached here.
private val backgroundDeliveryState = MutableStateFlow(true)
val backgroundDelivery: StateFlow<Boolean> = backgroundDeliveryState.asStateFlow()
// Background delivery: the device's choice, on by default.
// The shade's high-water mark lives in the same row but is read and
// written through the DAO by NotificationSync, awaited, never cached here.
private val backgroundDeliveryState = MutableStateFlow(true)
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()
// 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)
private val settingsLoadedState = MutableStateFlow(false)
/** True once the stored settings row has been read at least once. */
val settingsLoaded: StateFlow<Boolean> = settingsLoadedState.asStateFlow()
/** 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
// sign-in or a 401 that lands while hydration runs is never overwritten
// by the stale value hydration read.
private val cookieLock = Mutex()
// Serialises every cookie persist with the one-time hydration, so a
// sign-in or a 401 that lands while hydration runs is never overwritten
// by the stale value hydration read.
private val cookieLock = Mutex()
// Set by setSessionCookie. Once something has written the cookie this
// process, that value wins over whatever hydration finds on disk.
@Volatile private var cookieTouched = false
// Set by setSessionCookie. Once something has written the cookie this
// process, that value wins over whatever hydration finds on disk.
@Volatile private var cookieTouched = false
private val cookieHydration: Deferred<Unit> = scope.async { hydrateSessionCookie() }
private val cookieHydration: Deferred<Unit> = scope.async { hydrateSessionCookie() }
init {
scope.launch {
dao.observe().collect { row ->
baseUrlState.value = row?.baseUrl ?: DEFAULT_BASE_URL
userJsonState.value = row?.userJson
themeModeState.value = row?.themeMode
clientIdState.value = row?.clientId
cacheSettingsState.value = decodeCacheSettings(row?.cacheSettingsJson)
diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false
normalizationState.value = decodeNormalization(row?.normalizationJson)
backgroundDeliveryState.value = row?.backgroundDelivery ?: true
cacheOwnerState.value = row?.cacheOwnerUserId
settingsLoadedState.value = true
}
init {
scope.launch {
dao.observe().collect { row ->
baseUrlState.value = row?.baseUrl ?: DEFAULT_BASE_URL
userJsonState.value = row?.userJson
themeModeState.value = row?.themeMode
clientIdState.value = row?.clientId
cacheSettingsState.value = decodeCacheSettings(row?.cacheSettingsJson)
diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false
normalizationState.value = decodeNormalization(row?.normalizationJson)
backgroundDeliveryState.value = row?.backgroundDelivery ?: true
cacheOwnerState.value = row?.cacheOwnerUserId
settingsLoadedState.value = true
}
}
private fun decodeCacheSettings(raw: String?): CacheSettings {
if (raw.isNullOrEmpty()) return CacheSettings.DEFAULT
return runCatching {
json.decodeFromString(CacheSettings.serializer(), raw)
}.getOrDefault(CacheSettings.DEFAULT)
}
private fun decodeNormalization(raw: String?): NormalizationPrefs {
if (raw.isNullOrEmpty()) return NormalizationPrefs.DEFAULT
return runCatching {
json.decodeFromString(NormalizationPrefs.serializer(), raw)
}.getOrDefault(NormalizationPrefs.DEFAULT)
}
/**
* Suspends until the stored session cookie has been loaded into
* [sessionCookie], or [HYDRATION_DEADLINE_MS] passes, so a wedged
* Keystore cannot leave the start screen spinning. Returns false on
* the deadline; the caller then decides from whatever has loaded, and a
* late hydration still lands in [sessionCookie].
*/
suspend fun awaitSessionHydrated(): Boolean {
val done = withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } != null
if (!done) Timber.w("auth store: session hydration passed its deadline; deciding without it")
return done
}
fun setSessionCookie(value: String?) {
cookieTouched = true
sessionCookieState.value = 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 {
val legacy = runCatching { dao.get()?.sessionCookie }.getOrNull()
if (cookieTouched) return@withLock
// A cookie in the row is the newer one when both exist: the row is
// only written when the vault failed, and an install upgrading from
// before the vault has nothing in the vault yet.
val cookie = legacy ?: vault.read()
// Best-effort: if moving it fails, the session still loads this time
// and the move is retried on the next launch. Hydration must never
// throw, or awaitSessionHydrated would leave the auth gate stuck.
if (legacy != null) {
runCatching { storeCookie(legacy) }
.onFailure { Timber.w(it, "auth store: could not move the session cookie into the vault") }
}
sessionCookieState.value = cookie
}
// Vault first; the Room row only when the Keystore is unusable, so a
// broken Keystore degrades to the old storage rather than a sign-out.
private suspend fun storeCookie(value: String?) {
if (vault.write(value)) {
if (dao.get()?.sessionCookie != null) dao.setSessionCookie(null)
} else {
persistLegacyCookie(value)
}
}
fun setBaseUrl(value: String) {
baseUrlState.value = value
scope.launch { persistBaseUrl(value) }
}
fun setUserJson(value: String?) {
userJsonState.value = value
scope.launch { persistUserJson(value) }
}
fun setThemeMode(value: String?) {
themeModeState.value = value
scope.launch { persistThemeMode(value) }
}
fun setClientId(value: String?) {
clientIdState.value = value
scope.launch { persistClientId(value) }
}
fun setCacheSettings(value: CacheSettings) {
cacheSettingsState.value = value
val encoded = json.encodeToString(CacheSettings.serializer(), value)
scope.launch { persistCacheSettings(encoded) }
}
fun setDiagnosticsOptOut(value: Boolean) {
diagnosticsOptOutState.value = value
scope.launch { persistDiagnosticsOptOut(value) }
}
fun setNormalization(value: NormalizationPrefs) {
normalizationState.value = value
val encoded = json.encodeToString(NormalizationPrefs.serializer(), value)
scope.launch { persistNormalization(encoded) }
}
fun setBackgroundDelivery(value: Boolean) {
backgroundDeliveryState.value = value
scope.launch {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(backgroundDelivery = value))
} else {
dao.setBackgroundDelivery(value)
}
}
}
/**
* 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?) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(sessionCookie = value))
} else {
dao.setSessionCookie(value)
}
}
private suspend fun persistBaseUrl(value: String) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(baseUrl = value))
} else {
dao.setBaseUrl(value)
}
}
private suspend fun persistUserJson(value: String?) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(userJson = value))
} else {
dao.setUserJson(value)
}
}
private suspend fun persistThemeMode(value: String?) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(themeMode = value))
} else {
dao.setThemeMode(value)
}
}
private suspend fun persistClientId(value: String?) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(clientId = value))
} else {
dao.setClientId(value)
}
}
private suspend fun persistCacheSettings(json: String) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(cacheSettingsJson = json))
} else {
dao.setCacheSettingsJson(json)
}
}
private suspend fun persistDiagnosticsOptOut(value: Boolean) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(diagnosticsOptOut = value))
} else {
dao.setDiagnosticsOptOut(value)
}
}
private suspend fun persistNormalization(json: String) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(normalizationJson = json))
} else {
dao.setNormalizationJson(json)
}
}
private fun currentEntity(): AuthSessionEntity =
AuthSessionEntity(
id = ROW_ID,
// Never copied into the row: the cookie lives in the vault, and
// persistLegacyCookie sets it explicitly on the fallback path.
sessionCookie = null,
baseUrl = baseUrlState.value,
userJson = userJsonState.value,
themeMode = themeModeState.value,
clientId = clientIdState.value,
cacheSettingsJson =
json.encodeToString(
CacheSettings.serializer(),
cacheSettingsState.value,
),
diagnosticsOptOut = diagnosticsOptOutState.value,
normalizationJson =
json.encodeToString(
NormalizationPrefs.serializer(),
normalizationState.value,
),
backgroundDelivery = backgroundDeliveryState.value,
cacheOwnerUserId = cacheOwnerState.value,
)
companion object {
const val DEFAULT_BASE_URL: String = "http://localhost:8080"
// Generous on purpose: hydration is one local row read and one
// Keystore decrypt, normally milliseconds. This only bounds "never".
const val HYDRATION_DEADLINE_MS: Long = 10_000
private const val ROW_ID = 0
}
}
private fun decodeCacheSettings(raw: String?): CacheSettings {
if (raw.isNullOrEmpty()) return CacheSettings.DEFAULT
return runCatching {
json.decodeFromString(CacheSettings.serializer(), raw)
}.getOrDefault(CacheSettings.DEFAULT)
}
private fun decodeNormalization(raw: String?): NormalizationPrefs {
if (raw.isNullOrEmpty()) return NormalizationPrefs.DEFAULT
return runCatching {
json.decodeFromString(NormalizationPrefs.serializer(), raw)
}.getOrDefault(NormalizationPrefs.DEFAULT)
}
/**
* Suspends until the stored session cookie has been loaded into
* [sessionCookie], or [HYDRATION_DEADLINE_MS] passes, so a wedged
* Keystore cannot leave the start screen spinning. Returns false on
* the deadline; the caller then decides from whatever has loaded, and a
* late hydration still lands in [sessionCookie].
*/
suspend fun awaitSessionHydrated(): Boolean {
val done = withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } != null
if (!done) Timber.w("auth store: session hydration passed its deadline; deciding without it")
return done
}
fun setSessionCookie(value: String?) {
cookieTouched = true
sessionCookieState.value = 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 {
val legacy = runCatching { dao.get()?.sessionCookie }.getOrNull()
if (cookieTouched) return@withLock
// A cookie in the row is the newer one when both exist: the row is
// only written when the vault failed, and an install upgrading from
// before the vault has nothing in the vault yet.
val cookie = legacy ?: vault.read()
// Best-effort: if moving it fails, the session still loads this time
// and the move is retried on the next launch. Hydration must never
// throw, or awaitSessionHydrated would leave the auth gate stuck.
if (legacy != null) {
runCatching { storeCookie(legacy) }
.onFailure { Timber.w(it, "auth store: could not move the session cookie into the vault") }
}
sessionCookieState.value = cookie
}
// Vault first; the Room row only when the Keystore is unusable, so a
// broken Keystore degrades to the old storage rather than a sign-out.
private suspend fun storeCookie(value: String?) {
if (vault.write(value)) {
if (dao.get()?.sessionCookie != null) dao.setSessionCookie(null)
} else {
persistLegacyCookie(value)
}
}
fun setBaseUrl(value: String) {
baseUrlState.value = value
scope.launch { persistBaseUrl(value) }
}
fun setUserJson(value: String?) {
userJsonState.value = value
scope.launch { persistUserJson(value) }
}
fun setThemeMode(value: String?) {
themeModeState.value = value
scope.launch { persistThemeMode(value) }
}
fun setClientId(value: String?) {
clientIdState.value = value
scope.launch { persistClientId(value) }
}
fun setCacheSettings(value: CacheSettings) {
cacheSettingsState.value = value
val encoded = json.encodeToString(CacheSettings.serializer(), value)
scope.launch { persistCacheSettings(encoded) }
}
fun setDiagnosticsOptOut(value: Boolean) {
diagnosticsOptOutState.value = value
scope.launch { persistDiagnosticsOptOut(value) }
}
fun setNormalization(value: NormalizationPrefs) {
normalizationState.value = value
val encoded = json.encodeToString(NormalizationPrefs.serializer(), value)
scope.launch { persistNormalization(encoded) }
}
fun setBackgroundDelivery(value: Boolean) {
backgroundDeliveryState.value = value
scope.launch {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(backgroundDelivery = value))
} else {
dao.setBackgroundDelivery(value)
}
}
}
/**
* 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?) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(sessionCookie = value))
} else {
dao.setSessionCookie(value)
}
}
private suspend fun persistBaseUrl(value: String) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(baseUrl = value))
} else {
dao.setBaseUrl(value)
}
}
private suspend fun persistUserJson(value: String?) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(userJson = value))
} else {
dao.setUserJson(value)
}
}
private suspend fun persistThemeMode(value: String?) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(themeMode = value))
} else {
dao.setThemeMode(value)
}
}
private suspend fun persistClientId(value: String?) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(clientId = value))
} else {
dao.setClientId(value)
}
}
private suspend fun persistCacheSettings(json: String) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(cacheSettingsJson = json))
} else {
dao.setCacheSettingsJson(json)
}
}
private suspend fun persistDiagnosticsOptOut(value: Boolean) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(diagnosticsOptOut = value))
} else {
dao.setDiagnosticsOptOut(value)
}
}
private suspend fun persistNormalization(json: String) {
if (dao.get() == null) {
dao.upsert(currentEntity().copy(normalizationJson = json))
} else {
dao.setNormalizationJson(json)
}
}
private fun currentEntity(): AuthSessionEntity = AuthSessionEntity(
id = ROW_ID,
// Never copied into the row: the cookie lives in the vault, and
// persistLegacyCookie sets it explicitly on the fallback path.
sessionCookie = null,
baseUrl = baseUrlState.value,
userJson = userJsonState.value,
themeMode = themeModeState.value,
clientId = clientIdState.value,
cacheSettingsJson = json.encodeToString(
CacheSettings.serializer(),
cacheSettingsState.value,
),
diagnosticsOptOut = diagnosticsOptOutState.value,
normalizationJson = json.encodeToString(
NormalizationPrefs.serializer(),
normalizationState.value,
),
backgroundDelivery = backgroundDeliveryState.value,
cacheOwnerUserId = cacheOwnerState.value,
)
companion object {
const val DEFAULT_BASE_URL: String = "http://localhost:8080"
// Generous on purpose: hydration is one local row read and one
// Keystore decrypt, normally milliseconds. This only bounds "never".
const val HYDRATION_DEADLINE_MS: Long = 10_000
private const val ROW_ID = 0
}
}
@@ -35,30 +35,21 @@ import kotlin.coroutines.resumeWithException
* 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)
class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis: Long) {
private val client: OkHttpClient =
client
.newBuilder()
.connectTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS)
.callTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS)
.build()
// 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 Found(val baseUrl: String) : Result
data class Failed(
val message: String,
) : Result
data class Failed(val message: String) : Result
}
suspend fun find(input: String): Result {
@@ -109,28 +100,21 @@ class ServerProbe internal constructor(
data object Minstrel : Outcome
/** Nothing answered: the next scheme may be tried. */
data class Unreachable(
val publicCleartext: Boolean = false,
) : Outcome
data class Unreachable(val publicCleartext: Boolean = false) : Outcome
/** Something answered, or TLS failed to verify: stop here. */
data class Stop(
val message: String,
) : Outcome
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()
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)) {
@@ -139,13 +123,9 @@ class ServerProbe internal constructor(
Outcome.Stop("A server answered at $baseUrl, but it isn't Minstrel.")
}
}
} catch (
@Suppress("SwallowedException") e: CleartextToPublicHostException,
) {
} catch (@Suppress("SwallowedException") e: CleartextToPublicHostException) {
Outcome.Unreachable(publicCleartext = true)
} catch (
@Suppress("SwallowedException") e: UnknownHostException,
) {
} catch (@Suppress("SwallowedException") e: UnknownHostException) {
Outcome.Stop("Couldn't find a server named ${url.host}.")
} catch (e: IOException) {
if (isCertificateFailure(e)) {
@@ -171,43 +151,21 @@ class ServerProbe internal constructor(
// (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.
//
// OkHttp tries a host's addresses in parallel (fast fallback). When
// all of them fail it throws one failure and attaches the rest as
// suppressed, so the certificate error can sit behind a refused
// connection to the host's other address. Both causes and suppressed
// exceptions are searched.
private fun isCertificateFailure(e: IOException): Boolean {
val seen = mutableSetOf<Throwable>()
val pending = ArrayDeque<Throwable>().apply { add(e) }
var found = false
while (!found && pending.isNotEmpty() && seen.size < MAX_EXCEPTIONS_SEARCHED) {
val t = pending.removeFirst()
if (seen.add(t)) {
found = t is SSLPeerUnverifiedException || t is GeneralSecurityException
t.cause?.let { pending.addLast(it) }
pending.addAll(t.suppressed)
}
}
return found
}
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,
) {
override fun onResponse(call: Call, response: Response) {
if (continuation.isActive) continuation.resume(response) else response.close()
}
override fun onFailure(
call: Call,
e: IOException,
) {
override fun onFailure(call: Call, e: IOException) {
if (continuation.isActive) continuation.resumeWithException(e)
}
},
@@ -217,6 +175,6 @@ class ServerProbe internal constructor(
private companion object {
const val SETUP_STATUS_PATH = "/api/auth/setup-status"
const val CALL_TIMEOUT_MILLIS = 8_000L
const val MAX_EXCEPTIONS_SEARCHED = 16
const val MAX_CAUSE_DEPTH = 8
}
}
@@ -54,10 +54,7 @@ internal object SealedBox {
// under the same key will not open as a session cookie.
private val AAD = "minstrel-session-cookie-v1".toByteArray(Charsets.UTF_8)
fun seal(
key: SecretKey,
plaintext: String,
): String {
fun seal(key: SecretKey, plaintext: String): String {
val cipher = Cipher.getInstance(TRANSFORMATION)
// No IV passed: the provider generates a fresh random one. Keystore
// keys refuse a caller-chosen IV for encryption by default.
@@ -67,10 +64,7 @@ internal object SealedBox {
return Base64.getEncoder().encodeToString(sealed)
}
fun open(
key: SecretKey,
sealed: String,
): String {
fun open(key: SecretKey, sealed: String): String {
val bytes = Base64.getDecoder().decode(sealed)
require(bytes.size > IV_BYTES) { "sealed value too short" }
val cipher = Cipher.getInstance(TRANSFORMATION)
@@ -91,61 +85,59 @@ internal object SealedBox {
* credential that no longer verifies.
*/
@Singleton
class KeystoreSessionVault
@Inject
constructor(
@ApplicationContext context: Context,
) : SessionVault {
private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
class KeystoreSessionVault @Inject constructor(
@ApplicationContext context: Context,
) : SessionVault {
private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
override fun read(): String? {
val sealed = prefs.getString(KEY_COOKIE, null) ?: return null
return runCatching { SealedBox.open(key(), sealed) }
.onFailure {
Timber.w(it, "session vault: stored cookie would not decrypt; discarding it")
prefs.edit().remove(KEY_COOKIE).commit()
}.getOrNull()
}
override fun write(value: String?): Boolean =
runCatching {
val editor = prefs.edit()
if (value == null) {
editor.remove(KEY_COOKIE)
} else {
editor.putString(KEY_COOKIE, SealedBox.seal(key(), value))
}
editor.commit()
}.onFailure {
Timber.w(it, "session vault: Keystore unavailable; cookie not stored in the vault")
}.getOrDefault(false)
private fun key(): SecretKey {
val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)
generator.init(
KeyGenParameterSpec
.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
).setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(KEY_BITS)
.build(),
)
return generator.generateKey()
}
private companion object {
const val ANDROID_KEYSTORE = "AndroidKeyStore"
const val KEY_ALIAS = "minstrel_session_cookie"
const val KEY_BITS = 256
const val PREFS_NAME = "session_vault"
const val KEY_COOKIE = "sealed_cookie"
}
override fun read(): String? {
val sealed = prefs.getString(KEY_COOKIE, null) ?: return null
return runCatching { SealedBox.open(key(), sealed) }
.onFailure {
Timber.w(it, "session vault: stored cookie would not decrypt; discarding it")
prefs.edit().remove(KEY_COOKIE).commit()
}
.getOrNull()
}
override fun write(value: String?): Boolean = runCatching {
val editor = prefs.edit()
if (value == null) {
editor.remove(KEY_COOKIE)
} else {
editor.putString(KEY_COOKIE, SealedBox.seal(key(), value))
}
editor.commit()
}.onFailure {
Timber.w(it, "session vault: Keystore unavailable; cookie not stored in the vault")
}.getOrDefault(false)
private fun key(): SecretKey {
val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)
generator.init(
KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(KEY_BITS)
.build(),
)
return generator.generateKey()
}
private companion object {
const val ANDROID_KEYSTORE = "AndroidKeyStore"
const val KEY_ALIAS = "minstrel_session_cookie"
const val KEY_BITS = 256
const val PREFS_NAME = "session_vault"
const val KEY_COOKIE = "sealed_cookie"
}
}
@Module
@InstallIn(SingletonComponent::class)
abstract class SessionVaultModule {
@@ -30,36 +30,34 @@ import javax.inject.Inject
* and then exactly one resolved value.
*/
@HiltViewModel
class AuthGateViewModel
@Inject
constructor(
private val dao: AuthSessionDao,
private val authStore: AuthStore,
) : ViewModel() {
private val internal = MutableStateFlow<Any?>(null)
val startDestination: StateFlow<Any?> = internal.asStateFlow()
class AuthGateViewModel @Inject constructor(
private val dao: AuthSessionDao,
private val authStore: AuthStore,
) : ViewModel() {
/**
* 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
private val internal = MutableStateFlow<Any?>(null)
val startDestination: StateFlow<Any?> = internal.asStateFlow()
fun consumeSessionRejected() = authStore.consumeSessionRejected()
/**
* 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
init {
viewModelScope.launch {
authStore.awaitSessionHydrated()
val signedIn = !authStore.sessionCookie.value.isNullOrEmpty()
val row = dao.get()
internal.value =
when {
row == null -> ServerUrl
row.baseUrl == AuthStore.DEFAULT_BASE_URL && !signedIn -> ServerUrl
!signedIn -> Login
else -> Home
}
fun consumeSessionRejected() = authStore.consumeSessionRejected()
init {
viewModelScope.launch {
authStore.awaitSessionHydrated()
val signedIn = !authStore.sessionCookie.value.isNullOrEmpty()
val row = dao.get()
internal.value = when {
row == null -> ServerUrl
row.baseUrl == AuthStore.DEFAULT_BASE_URL && !signedIn -> ServerUrl
!signedIn -> Login
else -> Home
}
}
}
}
@@ -71,10 +71,9 @@ private fun LoginForm(
onChangeServerUrl: () -> Unit,
) {
Column(
modifier =
Modifier
.fillMaxSize()
.padding(24.dp),
modifier = Modifier
.fillMaxSize()
.padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
@@ -90,11 +89,10 @@ private fun LoginForm(
label = { Text("Username") },
singleLine = true,
enabled = !state.isSubmitting,
keyboardOptions =
KeyboardOptions(
keyboardType = KeyboardType.Email,
imeAction = ImeAction.Next,
),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Email,
imeAction = ImeAction.Next,
),
)
OutlinedTextField(
value = state.password,
@@ -104,11 +102,10 @@ private fun LoginForm(
singleLine = true,
enabled = !state.isSubmitting,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions =
KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Done,
),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Done,
),
keyboardActions = KeyboardActions(onDone = { onSubmit() }),
)
if (state.errorMessage != null) {
@@ -129,16 +126,12 @@ private fun LoginForm(
}
@Composable
private fun SubmitButton(
state: LoginFormState,
onSubmit: () -> Unit,
) {
private fun SubmitButton(state: LoginFormState, onSubmit: () -> Unit) {
Button(
onClick = onSubmit,
enabled =
!state.isSubmitting &&
state.username.isNotBlank() &&
state.password.isNotBlank(),
enabled = !state.isSubmitting &&
state.username.isNotBlank() &&
state.password.isNotBlank(),
modifier = Modifier.fillMaxWidth(),
) {
if (state.isSubmitting) {
@@ -21,45 +21,44 @@ data class LoginFormState(
)
@HiltViewModel
class LoginViewModel
@Inject
constructor(
private val auth: AuthController,
) : ViewModel() {
private val internal = MutableStateFlow(LoginFormState())
val state: StateFlow<LoginFormState> = internal.asStateFlow()
class LoginViewModel @Inject constructor(
private val auth: AuthController,
) : ViewModel() {
fun setUsername(value: String) {
internal.update { it.copy(username = value, errorMessage = null) }
}
private val internal = MutableStateFlow(LoginFormState())
val state: StateFlow<LoginFormState> = internal.asStateFlow()
fun setPassword(value: String) {
internal.update { it.copy(password = value, errorMessage = null) }
}
fun setUsername(value: String) {
internal.update { it.copy(username = value, errorMessage = null) }
}
fun submit() {
val s = internal.value
if (s.username.isBlank() || s.password.isBlank() || s.isSubmitting) return
viewModelScope.launch {
internal.update { it.copy(isSubmitting = true, errorMessage = null) }
try {
auth.signIn(s.username, s.password)
internal.update { it.copy(isSubmitting = false, signedIn = true) }
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.update {
it.copy(
isSubmitting = false,
errorMessage = ErrorCopy.fromThrowable(e),
)
}
fun setPassword(value: String) {
internal.update { it.copy(password = value, errorMessage = null) }
}
fun submit() {
val s = internal.value
if (s.username.isBlank() || s.password.isBlank() || s.isSubmitting) return
viewModelScope.launch {
internal.update { it.copy(isSubmitting = true, errorMessage = null) }
try {
auth.signIn(s.username, s.password)
internal.update { it.copy(isSubmitting = false, signedIn = true) }
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.update {
it.copy(
isSubmitting = false,
errorMessage = ErrorCopy.fromThrowable(e),
)
}
}
}
/** Called after the navigation away from /login completes. */
fun consumeSignedIn() {
internal.update { it.copy(signedIn = false) }
}
}
/** Called after the navigation away from /login completes. */
fun consumeSignedIn() {
internal.update { it.copy(signedIn = false) }
}
}
@@ -51,68 +51,64 @@ data class ServerUrlFormState(
)
@HiltViewModel
class ServerUrlViewModel
@Inject
constructor(
private val authStore: AuthStore,
private val probe: ServerProbe,
) : ViewModel() {
private val internal =
MutableStateFlow(
// Pre-fill ONLY if the user has previously saved a real URL —
// the DEFAULT_BASE_URL placeholder (`http://localhost:8080`) is
// an internal HTTP-client fallback, not something a user
// typed. Leaving the field empty lets the OutlinedTextField's
// placeholder ("minstrel.example.com") show through so the user
// can just type without first having to clear.
ServerUrlFormState(
url =
authStore.baseUrl.value
.takeIf { it != AuthStore.DEFAULT_BASE_URL }
.orEmpty(),
),
)
val state: StateFlow<ServerUrlFormState> = internal.asStateFlow()
class ServerUrlViewModel @Inject constructor(
private val authStore: AuthStore,
private val probe: ServerProbe,
) : ViewModel() {
private var probeJob: Job? = null
private val internal = MutableStateFlow(
// Pre-fill ONLY if the user has previously saved a real URL —
// the DEFAULT_BASE_URL placeholder (`http://localhost:8080`) is
// an internal HTTP-client fallback, not something a user
// typed. Leaving the field empty lets the OutlinedTextField's
// placeholder ("minstrel.example.com") show through so the user
// can just type without first having to clear.
ServerUrlFormState(
url = authStore.baseUrl.value
.takeIf { it != AuthStore.DEFAULT_BASE_URL }
.orEmpty(),
),
)
val state: StateFlow<ServerUrlFormState> = internal.asStateFlow()
fun setUrl(value: String) {
internal.update { it.copy(url = value, errorMessage = null) }
}
private var probeJob: Job? = 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() {
if (internal.value.probing) return
val typed = internal.value.url
probeJob =
viewModelScope.launch {
internal.update { it.copy(probing = true, errorMessage = null) }
when (val result = probe.find(typed)) {
is ServerProbe.Result.Found -> {
authStore.setBaseUrl(result.baseUrl)
internal.update { it.copy(probing = false, saved = true) }
}
is ServerProbe.Result.Failed ->
internal.update { it.copy(probing = false, errorMessage = result.message) }
}
fun setUrl(value: String) {
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() {
if (internal.value.probing) return
val typed = internal.value.url
probeJob = viewModelScope.launch {
internal.update { it.copy(probing = true, errorMessage = null) }
when (val result = probe.find(typed)) {
is ServerProbe.Result.Found -> {
authStore.setBaseUrl(result.baseUrl)
internal.update { it.copy(probing = false, saved = true) }
}
}
fun cancelProbe() {
probeJob?.cancel()
probeJob = null
internal.update { it.copy(probing = false) }
}
fun consumeSaved() {
internal.update { it.copy(saved = false) }
is ServerProbe.Result.Failed ->
internal.update { it.copy(probing = false, errorMessage = result.message) }
}
}
}
fun cancelProbe() {
probeJob?.cancel()
probeJob = null
internal.update { it.copy(probing = false) }
}
fun consumeSaved() {
internal.update { it.copy(saved = false) }
}
}
// ─── Screen ───────────────────────────────────────────────────────────
@Composable
@@ -153,10 +149,9 @@ private fun ServerUrlForm(
onCancel: () -> Unit,
) {
Column(
modifier =
Modifier
.fillMaxSize()
.padding(24.dp),
modifier = Modifier
.fillMaxSize()
.padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
@@ -181,11 +176,10 @@ private fun ServerUrlForm(
},
singleLine = true,
enabled = !state.probing,
keyboardOptions =
KeyboardOptions(
keyboardType = KeyboardType.Uri,
imeAction = ImeAction.Done,
),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Uri,
imeAction = ImeAction.Done,
),
keyboardActions = KeyboardActions(onDone = { onSubmit() }),
)
if (state.errorMessage != null) {
@@ -31,36 +31,34 @@ import javax.inject.Singleton
* the construct-the-singleton trick in `MinstrelApplication`.
*/
@Singleton
class CacheIndexer
@Inject
constructor(
playerController: PlayerController,
private val dao: AudioCacheIndexDao,
@ApplicationScope private val scope: CoroutineScope,
) {
init {
scope.launch {
playerController.uiState
.map { it.currentTrack }
.distinctUntilChanged { a, b -> a?.id == b?.id }
.collect { track -> if (track != null) record(track) }
}
}
private suspend fun record(track: TrackRef) {
val now = Clock.System.now()
if (dao.get(track.id) != null) {
dao.touchLastPlayed(track.id, now)
} else {
dao.upsert(
AudioCacheIndexEntity(
trackId = track.id,
path = track.streamUrl,
sizeBytes = 0,
lastPlayedAt = now,
source = CacheSource.INCIDENTAL,
),
)
}
class CacheIndexer @Inject constructor(
playerController: PlayerController,
private val dao: AudioCacheIndexDao,
@ApplicationScope private val scope: CoroutineScope,
) {
init {
scope.launch {
playerController.uiState
.map { it.currentTrack }
.distinctUntilChanged { a, b -> a?.id == b?.id }
.collect { track -> if (track != null) record(track) }
}
}
private suspend fun record(track: TrackRef) {
val now = Clock.System.now()
if (dao.get(track.id) != null) {
dao.touchLastPlayed(track.id, now)
} else {
dao.upsert(
AudioCacheIndexEntity(
trackId = track.id,
path = track.streamUrl,
sizeBytes = 0,
lastPlayedAt = now,
source = CacheSource.INCIDENTAL,
),
)
}
}
}
@@ -33,30 +33,28 @@ import javax.inject.Singleton
* library is opened offline with no active playback.
*/
@Singleton
class CachedTrackIds
@Inject
constructor(
playerController: PlayerController,
private val playerFactory: PlayerFactory,
@ApplicationScope scope: CoroutineScope,
) {
private val refresh = MutableStateFlow(0L)
class CachedTrackIds @Inject constructor(
playerController: PlayerController,
private val playerFactory: PlayerFactory,
@ApplicationScope scope: CoroutineScope,
) {
private val refresh = MutableStateFlow(0L)
val ids: StateFlow<Set<String>> =
refresh
.map { readKeys() }
.flowOn(Dispatchers.IO)
.stateIn(scope, SharingStarted.Eagerly, emptySet())
val ids: StateFlow<Set<String>> =
refresh
.map { readKeys() }
.flowOn(Dispatchers.IO)
.stateIn(scope, SharingStarted.Eagerly, emptySet())
init {
scope.launch {
playerController.uiState
.map { it.currentTrack?.id }
.distinctUntilChanged()
.collect { refresh.value += 1 }
}
init {
scope.launch {
playerController.uiState
.map { it.currentTrack?.id }
.distinctUntilChanged()
.collect { refresh.value += 1 }
}
private fun readKeys(): Set<String> =
runCatching { playerFactory.simpleCache.keys.toSet() }.getOrDefault(emptySet())
}
private fun readKeys(): Set<String> =
runCatching { playerFactory.simpleCache.keys.toSet() }.getOrDefault(emptySet())
}
@@ -28,45 +28,42 @@ private const val POOL_LIMIT = 100
* plays the pool from the cache.
*/
@Singleton
class ShuffleSource
@Inject
constructor(
private val cacheIndexDao: AudioCacheIndexDao,
private val trackDao: CachedTrackDao,
private val likes: LikesRepository,
private val playerFactory: PlayerFactory,
) {
/** Cached tracks, most-recently-played first (liked included). */
suspend fun recentlyPlayed(limit: Int = POOL_LIMIT): List<TrackRef> =
materialize(residentIdsByRecency()).take(limit)
class ShuffleSource @Inject constructor(
private val cacheIndexDao: AudioCacheIndexDao,
private val trackDao: CachedTrackDao,
private val likes: LikesRepository,
private val playerFactory: PlayerFactory,
) {
/** Cached tracks, most-recently-played first (liked included). */
suspend fun recentlyPlayed(limit: Int = POOL_LIMIT): List<TrackRef> =
materialize(residentIdsByRecency()).take(limit)
/** Cached tracks that are in the user's liked set, recency-ordered. */
suspend fun liked(limit: Int = POOL_LIMIT): List<TrackRef> {
val likedSet = likes.likedTrackIds()
val ids = residentIdsByRecency().filter { it in likedSet }
return materialize(ids).take(limit)
}
/** Cached tracks that are in the user's liked set, recency-ordered. */
suspend fun liked(limit: Int = POOL_LIMIT): List<TrackRef> {
val likedSet = likes.likedTrackIds()
val ids = residentIdsByRecency().filter { it in likedSet }
return materialize(ids).take(limit)
}
/** Recency-ordered ids whose audio is actually resident in the cache. */
private suspend fun residentIdsByRecency(): List<String> {
val resident =
runCatching { playerFactory.simpleCache.keys.toSet() }
.getOrDefault(emptySet())
return cacheIndexDao.trackIdsByRecency().filter { it in resident }
}
/** Recency-ordered ids whose audio is actually resident in the cache. */
private suspend fun residentIdsByRecency(): List<String> {
val resident = runCatching { playerFactory.simpleCache.keys.toSet() }
.getOrDefault(emptySet())
return cacheIndexDao.trackIdsByRecency().filter { it in resident }
}
/** Materialize ordered ids into TrackRefs from cached metadata, preserving order. */
private suspend fun materialize(orderedIds: List<String>): List<TrackRef> {
if (orderedIds.isEmpty()) return emptyList()
val byId = trackDao.getByIds(orderedIds).associateBy { it.id }
return orderedIds.mapNotNull { id ->
// Clear the server's missing mark. Every id reaching here
// came through residentIdsByRecency, which already proved the
// AUDIO is in the local cache — so these play regardless of what
// the server has lost, and the queue filter in PlayerController
// would otherwise throw away tracks that work perfectly. Missing
// means "cannot stream", not "cannot play".
byId[id]?.toDomain()?.copy(unavailable = false)
}
/** Materialize ordered ids into TrackRefs from cached metadata, preserving order. */
private suspend fun materialize(orderedIds: List<String>): List<TrackRef> {
if (orderedIds.isEmpty()) return emptyList()
val byId = trackDao.getByIds(orderedIds).associateBy { it.id }
return orderedIds.mapNotNull { id ->
// Clear the server's missing mark. Every id reaching here
// came through residentIdsByRecency, which already proved the
// AUDIO is in the local cache — so these play regardless of what
// the server has lost, and the queue filter in PlayerController
// would otherwise throw away tracks that work perfectly. Missing
// means "cannot stream", not "cannot play".
byId[id]?.toDomain()?.copy(unavailable = false)
}
}
}
@@ -34,17 +34,12 @@ internal enum class OwnerStep {
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
}
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
@@ -67,53 +62,48 @@ internal fun ownerStep(
* 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)
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()
/** 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()
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()
}
}
@@ -12,21 +12,17 @@ import javax.inject.Singleton
* (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()
}
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()
}
}
}
@@ -27,11 +27,10 @@ class BucketLedger<S : Any>(
private val lengthOf: (S) -> Long,
lruOrder: Comparator<S>,
) {
private val spans =
mapOf(
CacheBucket.LIKED to TreeSet(lruOrder),
CacheBucket.RECENT to TreeSet(lruOrder),
)
private val spans = mapOf(
CacheBucket.LIKED to TreeSet(lruOrder),
CacheBucket.RECENT to TreeSet(lruOrder),
)
private val bytes = mutableMapOf(CacheBucket.LIKED to 0L, CacheBucket.RECENT to 0L)
private val spansByKey = HashMap<String, MutableSet<S>>()
private val bucketByKey = HashMap<String, CacheBucket>()
@@ -44,16 +43,16 @@ class BucketLedger<S : Any>(
/** Cap on Recently played bytes; 0 means unlimited. */
var recentCapBytes: Long = 0L
fun bucketOf(key: String): CacheBucket = if (key in liked) CacheBucket.LIKED else CacheBucket.RECENT
fun bucketOf(key: String): CacheBucket =
if (key in liked) CacheBucket.LIKED else CacheBucket.RECENT
fun bytesIn(bucket: CacheBucket): Long = bytes.getValue(bucket)
/** Bytes the Liked budget can still take; [Long.MAX_VALUE] when unlimited. */
fun likedRoomBytes(): Long =
when {
likedCapBytes <= 0L -> Long.MAX_VALUE
else -> (likedCapBytes - bytesIn(CacheBucket.LIKED)).coerceAtLeast(0L)
}
fun likedRoomBytes(): Long = when {
likedCapBytes <= 0L -> Long.MAX_VALUE
else -> (likedCapBytes - bytesIn(CacheBucket.LIKED)).coerceAtLeast(0L)
}
fun add(span: S) {
val key = keyOf(span)
@@ -106,10 +105,7 @@ class BucketLedger<S : Any>(
* [pendingBytes] describe a write about to start, so room is made for it
* in its own bucket first. Recently played is trimmed before Liked.
*/
fun nextEviction(
pendingKey: String? = null,
pendingBytes: Long = 0L,
): S? {
fun nextEviction(pendingKey: String? = null, pendingBytes: Long = 0L): S? {
if (!armed) return null
val pendingBucket = pendingKey?.let(::bucketOf)
return listOf(CacheBucket.RECENT, CacheBucket.LIKED).firstNotNullOfOrNull { bucket ->
@@ -118,10 +114,7 @@ class BucketLedger<S : Any>(
}
}
private fun oldestIfOver(
bucket: CacheBucket,
incoming: Long,
): S? {
private fun oldestIfOver(bucket: CacheBucket, incoming: Long): S? {
val cap = if (bucket == CacheBucket.LIKED) likedCapBytes else recentCapBytes
val over = cap > 0L && bytesIn(bucket) + incoming > cap
return if (over) spans.getValue(bucket).firstOrNull() else null
@@ -23,20 +23,18 @@ import javax.inject.Singleton
* `MinstrelApplication`.
*/
@Singleton
class CacheBudgetSync
@Inject
constructor(
likes: LikesRepository,
authStore: AuthStore,
evictor: TwoBucketCacheEvictor,
@ApplicationScope scope: CoroutineScope,
) {
init {
scope.launch(Dispatchers.IO) {
combine(likes.observeSignedInLikedTrackIds(), authStore.cacheSettings, ::Pair)
.collect { (ids, settings) ->
evictor.update(ids, settings.likedCapBytes, settings.rollingCapBytes)
}
}
class CacheBudgetSync @Inject constructor(
likes: LikesRepository,
authStore: AuthStore,
evictor: TwoBucketCacheEvictor,
@ApplicationScope scope: CoroutineScope,
) {
init {
scope.launch(Dispatchers.IO) {
combine(likes.observeSignedInLikedTrackIds(), authStore.cacheSettings, ::Pair)
.collect { (ids, settings) ->
evictor.update(ids, settings.likedCapBytes, settings.rollingCapBytes)
}
}
}
}
@@ -11,11 +11,7 @@ import javax.inject.Singleton
* Bytes held against each audio-cache budget, and how much more the Liked
* budget can take ([Long.MAX_VALUE] when it is unlimited).
*/
data class CacheUsage(
val likedBytes: Long,
val recentBytes: Long,
val likedRoomBytes: Long,
)
data class CacheUsage(val likedBytes: Long, val recentBytes: Long, val likedRoomBytes: Long)
/**
* The audio cache's eviction policy: two budgets, Liked songs and Recently
@@ -33,111 +29,84 @@ data class CacheUsage(
* deadlock.
*/
@Singleton
class TwoBucketCacheEvictor
@Inject
constructor() : CacheEvictor {
private val ledger =
BucketLedger<CacheSpan>(
keyOf = { it.key },
lengthOf = { it.length },
lruOrder = compareBy<CacheSpan> { it.lastTouchTimestamp }.then(naturalOrder()),
)
class TwoBucketCacheEvictor @Inject constructor() : CacheEvictor {
private val ledger = BucketLedger<CacheSpan>(
keyOf = { it.key },
lengthOf = { it.length },
lruOrder = compareBy<CacheSpan> { it.lastTouchTimestamp }.then(naturalOrder()),
)
@Volatile private var cache: Cache? = null
@Volatile private var cache: Cache? = null
/** Called once the SimpleCache exists, so updates can trim it. */
fun attach(cache: Cache) {
this.cache = cache
/** Called once the SimpleCache exists, so updates can trim it. */
fun attach(cache: Cache) {
this.cache = cache
}
/** Apply a new liked set and caps, then trim whatever no longer fits. */
fun update(likedIds: Set<String>, likedCapBytes: Long, recentCapBytes: Long) {
val c = cache
val apply = {
ledger.likedCapBytes = likedCapBytes
ledger.recentCapBytes = recentCapBytes
ledger.setLiked(likedIds)
}
/** Apply a new liked set and caps, then trim whatever no longer fits. */
fun update(
likedIds: Set<String>,
likedCapBytes: Long,
recentCapBytes: Long,
) {
val c = cache
val apply = {
ledger.likedCapBytes = likedCapBytes
ledger.recentCapBytes = recentCapBytes
ledger.setLiked(likedIds)
}
if (c == null) {
synchronized(ledger) { apply() }
} else {
synchronized(c) {
synchronized(ledger) {
apply()
evict(c, pendingKey = null, pendingBytes = 0L)
}
if (c == null) {
synchronized(ledger) { apply() }
} else {
synchronized(c) {
synchronized(ledger) {
apply()
evict(c, pendingKey = null, pendingBytes = 0L)
}
}
}
}
fun usage(): CacheUsage =
synchronized(ledger) {
CacheUsage(
likedBytes = ledger.bytesIn(CacheBucket.LIKED),
recentBytes = ledger.bytesIn(CacheBucket.RECENT),
likedRoomBytes = ledger.likedRoomBytes(),
)
}
fun usage(): CacheUsage = synchronized(ledger) {
CacheUsage(
likedBytes = ledger.bytesIn(CacheBucket.LIKED),
recentBytes = ledger.bytesIn(CacheBucket.RECENT),
likedRoomBytes = ledger.likedRoomBytes(),
)
}
override fun requiresCacheSpanTouches(): Boolean = true
override fun requiresCacheSpanTouches(): Boolean = true
override fun onCacheInitialized() = Unit
override fun onCacheInitialized() = Unit
override fun onStartFile(
cache: Cache,
key: String,
position: Long,
length: Long,
) {
synchronized(ledger) {
evict(cache, key, if (length == C.LENGTH_UNSET.toLong()) 0L else length)
}
}
override fun onSpanAdded(
cache: Cache,
span: CacheSpan,
) {
synchronized(ledger) {
ledger.add(span)
evict(cache, pendingKey = null, pendingBytes = 0L)
}
}
override fun onSpanRemoved(
cache: Cache,
span: CacheSpan,
) {
synchronized(ledger) { ledger.remove(span) }
}
override fun onSpanTouched(
cache: Cache,
oldSpan: CacheSpan,
newSpan: CacheSpan,
) {
synchronized(ledger) {
ledger.remove(oldSpan)
ledger.add(newSpan)
evict(cache, pendingKey = null, pendingBytes = 0L)
}
}
private fun evict(
cache: Cache,
pendingKey: String?,
pendingBytes: Long,
) {
while (true) {
val span = ledger.nextEviction(pendingKey, pendingBytes) ?: return
cache.removeSpan(span)
// removeSpan reports back through onSpanRemoved; removing here as
// well guarantees the loop advances even if it did not.
ledger.remove(span)
}
override fun onStartFile(cache: Cache, key: String, position: Long, length: Long) {
synchronized(ledger) {
evict(cache, key, if (length == C.LENGTH_UNSET.toLong()) 0L else length)
}
}
override fun onSpanAdded(cache: Cache, span: CacheSpan) {
synchronized(ledger) {
ledger.add(span)
evict(cache, pendingKey = null, pendingBytes = 0L)
}
}
override fun onSpanRemoved(cache: Cache, span: CacheSpan) {
synchronized(ledger) { ledger.remove(span) }
}
override fun onSpanTouched(cache: Cache, oldSpan: CacheSpan, newSpan: CacheSpan) {
synchronized(ledger) {
ledger.remove(oldSpan)
ledger.add(newSpan)
evict(cache, pendingKey = null, pendingBytes = 0L)
}
}
private fun evict(cache: Cache, pendingKey: String?, pendingBytes: Long) {
while (true) {
val span = ledger.nextEviction(pendingKey, pendingBytes) ?: return
cache.removeSpan(span)
// removeSpan reports back through onSpanRemoved; removing here as
// well guarantees the loop advances even if it did not.
ledger.remove(span)
}
}
}
@@ -15,9 +15,9 @@ import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao
import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao
import com.fabledsword.minstrel.cache.db.dao.CachedQuarantineDao
import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao
import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao
import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao
import com.fabledsword.minstrel.cache.db.dao.SyncMetadataDao
@@ -32,9 +32,9 @@ import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationEntity
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationSettingsEntity
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity
import com.fabledsword.minstrel.cache.db.entities.CachedResumeStateEntity
import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistTrackEntity
import com.fabledsword.minstrel.cache.db.entities.CachedQuarantineEntity
import com.fabledsword.minstrel.cache.db.entities.CachedResumeStateEntity
import com.fabledsword.minstrel.cache.db.entities.CachedTrackEntity
import com.fabledsword.minstrel.cache.db.entities.DiagnosticEventEntity
import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
@@ -101,126 +101,104 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
@TypeConverters(MinstrelTypeConverters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun syncMetadataDao(): SyncMetadataDao
abstract fun cachedArtistDao(): CachedArtistDao
abstract fun cachedAlbumDao(): CachedAlbumDao
abstract fun cachedTrackDao(): CachedTrackDao
abstract fun cachedLikeDao(): CachedLikeDao
abstract fun cachedPlaylistDao(): CachedPlaylistDao
abstract fun cachedPlaylistTrackDao(): CachedPlaylistTrackDao
abstract fun cachedQuarantineDao(): CachedQuarantineDao
abstract fun audioCacheIndexDao(): AudioCacheIndexDao
abstract fun cachedMutationDao(): CachedMutationDao
abstract fun cachedResumeStateDao(): CachedResumeStateDao
abstract fun cachedHomeIndexDao(): CachedHomeIndexDao
abstract fun cachedHistorySnapshotDao(): CachedHistorySnapshotDao
abstract fun authSessionDao(): AuthSessionDao
abstract fun diagnosticEventDao(): DiagnosticEventDao
abstract fun cachedNotificationDao(): CachedNotificationDao
}
/** v8 → v9: add the nullable normalization preference column. */
val MIGRATION_8_9: Migration =
object : Migration(8, 9) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN normalizationJson TEXT")
}
val MIGRATION_8_9: Migration = object : Migration(8, 9) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN normalizationJson TEXT")
}
}
/**
* v9 → v10: the gain columns. Rows synced before this carry no gains,
* and the sync is incremental, so it would never re-send them: the cursor goes
* back to 0 and the next sync is a full one, upserting every row in place.
*/
val MIGRATION_9_10: Migration =
object : Migration(9, 10) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackGain REAL")
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackPeak REAL")
db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumGain REAL")
db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumPeak REAL")
db.execSQL("UPDATE sync_metadata SET cursor = 0")
}
val MIGRATION_9_10: Migration = object : Migration(9, 10) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackGain REAL")
db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackPeak REAL")
db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumGain REAL")
db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumPeak REAL")
db.execSQL("UPDATE sync_metadata SET cursor = 0")
}
}
/**
* v10 → v11: the notifications inbox cache and its settings. The SQL
* matches what Room generates for the two entities; Room checks it on open.
*/
val MIGRATION_10_11: Migration =
object : Migration(10, 11) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS `cached_notifications` (" +
"`id` TEXT NOT NULL, `kind` TEXT NOT NULL, `title` TEXT NOT NULL, " +
"`body` TEXT NOT NULL, `link` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, " +
"`readAt` INTEGER, PRIMARY KEY(`id`))",
)
db.execSQL(
"CREATE TABLE IF NOT EXISTS `cached_notification_settings` (" +
"`id` INTEGER NOT NULL, `json` TEXT NOT NULL, PRIMARY KEY(`id`))",
)
}
val MIGRATION_10_11: Migration = object : Migration(10, 11) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS `cached_notifications` (" +
"`id` TEXT NOT NULL, `kind` TEXT NOT NULL, `title` TEXT NOT NULL, " +
"`body` TEXT NOT NULL, `link` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, " +
"`readAt` INTEGER, PRIMARY KEY(`id`))",
)
db.execSQL(
"CREATE TABLE IF NOT EXISTS `cached_notification_settings` (" +
"`id` INTEGER NOT NULL, `json` TEXT NOT NULL, PRIMARY KEY(`id`))",
)
}
}
/**
* v11 → v12: background delivery. The device choice defaults on,
* as the entity's column default says; the high-water mark starts empty, so
* the first catch-up sets it without announcing anything.
*/
val MIGRATION_11_12: Migration =
object : Migration(11, 12) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN backgroundDelivery INTEGER NOT NULL DEFAULT 1")
db.execSQL("ALTER TABLE auth_session ADD COLUMN notifiedUpTo INTEGER")
}
val MIGRATION_11_12: Migration = object : Migration(11, 12) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN backgroundDelivery INTEGER NOT NULL DEFAULT 1")
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 ''")
}
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")
}
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")
}
val MIGRATION_14_15: Migration = object : Migration(14, 15) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE auth_session ADD COLUMN cacheOwnerUserId TEXT")
}
}
@@ -11,12 +11,12 @@ import com.fabledsword.minstrel.cache.db.dao.CachedHomeIndexDao
import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao
import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao
import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao
import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao
import com.fabledsword.minstrel.cache.db.dao.CachedQuarantineDao
import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao
import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao
import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao
import com.fabledsword.minstrel.cache.db.dao.SyncMetadataDao
import dagger.Module
import dagger.Provides
@@ -31,11 +31,8 @@ import javax.inject.Singleton
object DatabaseModule {
@Provides
@Singleton
fun provideDatabase(
@ApplicationContext context: Context,
): AppDatabase =
Room
.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME)
// Explicit migrations from v8 onward; an older schema has no path
// and rebuilds. The sync controller refills the cache from the
// server on first launch, so a rebuild loses only the unsynced
@@ -48,7 +45,8 @@ object DatabaseModule {
MIGRATION_12_13,
MIGRATION_13_14,
MIGRATION_14_15,
).fallbackToDestructiveMigration(dropAllTables = true)
)
.fallbackToDestructiveMigration(dropAllTables = true)
.build()
// DAO @Provides — Hilt can't inject AppDatabase abstract accessors
@@ -71,27 +69,33 @@ object DatabaseModule {
@Provides
@Singleton
fun provideCachedResumeStateDao(db: AppDatabase): CachedResumeStateDao = db.cachedResumeStateDao()
fun provideCachedResumeStateDao(db: AppDatabase): CachedResumeStateDao =
db.cachedResumeStateDao()
@Provides
@Singleton
fun provideCachedHomeIndexDao(db: AppDatabase): CachedHomeIndexDao = db.cachedHomeIndexDao()
fun provideCachedHomeIndexDao(db: AppDatabase): CachedHomeIndexDao =
db.cachedHomeIndexDao()
@Provides
@Singleton
fun provideCachedHistorySnapshotDao(db: AppDatabase): CachedHistorySnapshotDao = db.cachedHistorySnapshotDao()
fun provideCachedHistorySnapshotDao(db: AppDatabase): CachedHistorySnapshotDao =
db.cachedHistorySnapshotDao()
@Provides
@Singleton
fun provideCachedQuarantineDao(db: AppDatabase): CachedQuarantineDao = db.cachedQuarantineDao()
fun provideCachedQuarantineDao(db: AppDatabase): CachedQuarantineDao =
db.cachedQuarantineDao()
@Provides
@Singleton
fun provideCachedPlaylistDao(db: AppDatabase): CachedPlaylistDao = db.cachedPlaylistDao()
fun provideCachedPlaylistDao(db: AppDatabase): CachedPlaylistDao =
db.cachedPlaylistDao()
@Provides
@Singleton
fun provideCachedPlaylistTrackDao(db: AppDatabase): CachedPlaylistTrackDao = db.cachedPlaylistTrackDao()
fun provideCachedPlaylistTrackDao(db: AppDatabase): CachedPlaylistTrackDao =
db.cachedPlaylistTrackDao()
@Provides
@Singleton
@@ -99,7 +103,8 @@ object DatabaseModule {
@Provides
@Singleton
fun provideCachedMutationDao(db: AppDatabase): CachedMutationDao = db.cachedMutationDao()
fun provideCachedMutationDao(db: AppDatabase): CachedMutationDao =
db.cachedMutationDao()
@Provides
@Singleton
@@ -107,15 +112,18 @@ object DatabaseModule {
@Provides
@Singleton
fun provideAudioCacheIndexDao(db: AppDatabase): AudioCacheIndexDao = db.audioCacheIndexDao()
fun provideAudioCacheIndexDao(db: AppDatabase): AudioCacheIndexDao =
db.audioCacheIndexDao()
@Provides
@Singleton
fun provideDiagnosticEventDao(db: AppDatabase): DiagnosticEventDao = db.diagnosticEventDao()
fun provideDiagnosticEventDao(db: AppDatabase): DiagnosticEventDao =
db.diagnosticEventDao()
@Provides
@Singleton
fun provideCachedNotificationDao(db: AppDatabase): CachedNotificationDao = db.cachedNotificationDao()
fun provideCachedNotificationDao(db: AppDatabase): CachedNotificationDao =
db.cachedNotificationDao()
private const val DATABASE_NAME = "minstrel.db"
}
@@ -21,9 +21,11 @@ enum class CacheSource { MANUAL, AUTO_LIKED, AUTO_PLAYLIST, AUTO_PREFETCH, INCID
class MinstrelTypeConverters {
@TypeConverter fun instantToLong(i: Instant?): Long? = i?.toEpochMilliseconds()
@TypeConverter fun longToInstant(l: Long?): Instant? = l?.let { Instant.fromEpochMilliseconds(it) }
@TypeConverter fun longToInstant(l: Long?): Instant? =
l?.let { Instant.fromEpochMilliseconds(it) }
@TypeConverter fun sourceToName(s: CacheSource?): String? = s?.name
@TypeConverter fun nameToSource(n: String?): CacheSource? = n?.let { CacheSource.valueOf(it) }
@TypeConverter fun nameToSource(n: String?): CacheSource? =
n?.let { CacheSource.valueOf(it) }
}
@@ -37,10 +37,7 @@ interface AudioCacheIndexDao {
@Query(
"UPDATE audio_cache_index SET lastPlayedAt = :at WHERE trackId = :trackId",
)
suspend fun touchLastPlayed(
trackId: String,
at: kotlinx.datetime.Instant,
)
suspend fun touchLastPlayed(trackId: String, at: kotlinx.datetime.Instant)
@Query("DELETE FROM audio_cache_index WHERE trackId = :trackId")
suspend fun deleteByTrackId(trackId: String)
@@ -30,16 +30,10 @@ interface CachedAlbumDao {
"ORDER BY sortTitle COLLATE NOCASE ASC " +
"LIMIT :limit",
)
suspend fun searchByTitle(
q: String,
limit: Int,
): List<CachedAlbumEntity>
suspend fun searchByTitle(q: String, limit: Int): List<CachedAlbumEntity>
@Query("SELECT id FROM cached_albums WHERE fetchedAt < :before LIMIT :limit")
suspend fun idsStaleBefore(
before: Long,
limit: Int,
): List<String>
suspend fun idsStaleBefore(before: Long, limit: Int): List<String>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(rows: List<CachedAlbumEntity>)
@@ -24,16 +24,10 @@ interface CachedArtistDao {
"ORDER BY sortName COLLATE NOCASE ASC " +
"LIMIT :limit",
)
suspend fun searchByName(
q: String,
limit: Int,
): List<CachedArtistEntity>
suspend fun searchByName(q: String, limit: Int): List<CachedArtistEntity>
@Query("SELECT id FROM cached_artists WHERE fetchedAt < :before LIMIT :limit")
suspend fun idsStaleBefore(
before: Long,
limit: Int,
): List<String>
suspend fun idsStaleBefore(before: Long, limit: Int): List<String>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(rows: List<CachedArtistEntity>)
@@ -44,10 +44,7 @@ interface CachedHomeIndexDao {
* sequence rather than as a single content swap.
*/
@Transaction
suspend fun replaceSections(
sections: List<String>,
rows: List<CachedHomeIndexEntity>,
) {
suspend fun replaceSections(sections: List<String>, rows: List<CachedHomeIndexEntity>) {
deleteSections(sections)
if (rows.isNotEmpty()) upsertAll(rows)
}
@@ -25,20 +25,13 @@ interface CachedLikeDao {
"SELECT entityId FROM cached_likes " +
"WHERE userId = :userId AND entityType = :entityType",
)
fun observeLikedIdsOfType(
userId: String,
entityType: String,
): Flow<List<String>>
fun observeLikedIdsOfType(userId: String, entityType: String): Flow<List<String>>
@Query(
"SELECT EXISTS(SELECT 1 FROM cached_likes " +
"WHERE userId = :userId AND entityType = :entityType AND entityId = :entityId)",
)
fun observeIsLiked(
userId: String,
entityType: String,
entityId: String,
): Flow<Boolean>
fun observeIsLiked(userId: String, entityType: String, entityId: String): Flow<Boolean>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(rows: List<CachedLikeEntity>)
@@ -47,11 +40,7 @@ interface CachedLikeDao {
"DELETE FROM cached_likes " +
"WHERE userId = :userId AND entityType = :entityType AND entityId = :entityId",
)
suspend fun delete(
userId: String,
entityType: String,
entityId: String,
)
suspend fun delete(userId: String, entityType: String, entityId: String)
@Query("DELETE FROM cached_likes WHERE userId = :userId")
suspend fun clearForUser(userId: String)
@@ -64,10 +53,7 @@ interface CachedLikeDao {
* stale Liked tab entry forever.
*/
@Transaction
suspend fun replaceAllForUser(
userId: String,
rows: List<CachedLikeEntity>,
) {
suspend fun replaceAllForUser(userId: String, rows: List<CachedLikeEntity>) {
clearForUser(userId)
upsertAll(rows)
}
@@ -24,10 +24,7 @@ interface CachedMutationDao {
"UPDATE cached_mutations SET attempts = attempts + 1, lastAttemptAt = :at " +
"WHERE id = :id",
)
suspend fun recordAttempt(
id: Long,
at: Instant,
)
suspend fun recordAttempt(id: Long, at: Instant)
@Query("DELETE FROM cached_mutations WHERE id = :id")
suspend fun delete(id: Long)
@@ -35,10 +35,7 @@ interface CachedNotificationDao {
}
@Query("UPDATE cached_notifications SET readAt = :at WHERE id = :id AND readAt IS NULL")
suspend fun markRead(
id: String,
at: Instant,
)
suspend fun markRead(id: String, at: Instant)
@Query("UPDATE cached_notifications SET readAt = :at WHERE readAt IS NULL")
suspend fun markAllRead(at: Instant)
@@ -55,10 +55,7 @@ interface CachedPlaylistDao {
suspend fun deleteAllOwned(userId: String)
@Query("DELETE FROM cached_playlists WHERE userId = :userId AND id NOT IN (:keepIds)")
suspend fun deleteOwnedNotIn(
userId: String,
keepIds: List<String>,
)
suspend fun deleteOwnedNotIn(userId: String, keepIds: List<String>)
/**
* Atomically reconciles the cache against the fresh list response.
@@ -67,8 +67,5 @@ interface CachedPlaylistTrackDao {
"DELETE FROM cached_playlist_tracks " +
"WHERE playlistId = :playlistId AND trackId IN (:trackIds)",
)
suspend fun deleteTracksFromPlaylist(
playlistId: String,
trackIds: List<String>,
)
suspend fun deleteTracksFromPlaylist(playlistId: String, trackIds: List<String>)
}
@@ -30,16 +30,10 @@ interface CachedTrackDao {
"ORDER BY title COLLATE NOCASE ASC " +
"LIMIT :limit",
)
suspend fun searchByTitle(
q: String,
limit: Int,
): List<CachedTrackEntity>
suspend fun searchByTitle(q: String, limit: Int): List<CachedTrackEntity>
@Query("SELECT id FROM cached_tracks WHERE fetchedAt < :before LIMIT :limit")
suspend fun idsStaleBefore(
before: Long,
limit: Int,
): List<String>
suspend fun idsStaleBefore(before: Long, limit: Int): List<String>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertAll(rows: List<CachedTrackEntity>)
@@ -87,238 +87,206 @@ data class LikeTogglePayload(
*/
@Suppress("TooManyFunctions") // one enqueue per mutation kind, like the replayer's dispatchers
@Singleton
class MutationQueue
@Inject
constructor(
private val dao: CachedMutationDao,
private val json: Json,
) {
// capacity=1 DROP_OLDEST so a burst of user enqueues (e.g. liking N
// tracks while offline) surfaces as one snackbar rather than queueing
// N. replay=0 because a hint observed at enqueue time isn't useful
// to a screen that mounts later.
private val _userEnqueueHints =
MutableSharedFlow<String>(
replay = 0,
extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
class MutationQueue @Inject constructor(
private val dao: CachedMutationDao,
private val json: Json,
) {
// capacity=1 DROP_OLDEST so a burst of user enqueues (e.g. liking N
// tracks while offline) surfaces as one snackbar rather than queueing
// N. replay=0 because a hint observed at enqueue time isn't useful
// to a screen that mounts later.
private val _userEnqueueHints = MutableSharedFlow<String>(
replay = 0,
extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
/**
* Hint stream consumed by [com.fabledsword.minstrel.shared.widgets.ShellScaffold]
* to surface "Saved — will sync when online" as a snackbar whenever a
* user-driven write hits the offline-fallback path. Background-only
* enqueues (play-events, playback-error reports) do not emit — those
* fire from non-foreground paths where a snackbar would be either
* dropped (no shell mounted) or jarring (lock-screen toggle).
*/
val userEnqueueHints: SharedFlow<String> = _userEnqueueHints.asSharedFlow()
/**
* Hint stream consumed by [com.fabledsword.minstrel.shared.widgets.ShellScaffold]
* to surface "Saved — will sync when online" as a snackbar whenever a
* user-driven write hits the offline-fallback path. Background-only
* enqueues (play-events, playback-error reports) do not emit — those
* fire from non-foreground paths where a snackbar would be either
* dropped (no shell mounted) or jarring (lock-screen toggle).
*/
val userEnqueueHints: SharedFlow<String> = _userEnqueueHints.asSharedFlow()
suspend fun enqueueLikeToggle(
entityType: String,
entityId: String,
desiredState: Boolean,
): Long =
insertUserDriven(
MutationKind.LIKE_TOGGLE,
json.encodeToString(
LikeTogglePayload.serializer(),
LikeTogglePayload(entityType, entityId, desiredState),
),
)
suspend fun enqueueLikeToggle(
entityType: String,
entityId: String,
desiredState: Boolean,
): Long = insertUserDriven(
MutationKind.LIKE_TOGGLE,
json.encodeToString(
LikeTogglePayload.serializer(),
LikeTogglePayload(entityType, entityId, desiredState),
),
)
suspend fun enqueueQuarantineUnflag(trackId: String): Long =
insertUserDriven(
MutationKind.QUARANTINE_UNFLAG,
json.encodeToString(
QuarantineUnflagPayload.serializer(),
QuarantineUnflagPayload(trackId),
),
)
suspend fun enqueueQuarantineUnflag(trackId: String): Long = insertUserDriven(
MutationKind.QUARANTINE_UNFLAG,
json.encodeToString(
QuarantineUnflagPayload.serializer(),
QuarantineUnflagPayload(trackId),
),
)
suspend fun enqueuePlaylistAppend(payload: PlaylistAppendPayload): Long =
insertUserDriven(
MutationKind.PLAYLIST_APPEND,
json.encodeToString(PlaylistAppendPayload.serializer(), payload),
)
suspend fun enqueuePlaylistAppend(payload: PlaylistAppendPayload): Long = insertUserDriven(
MutationKind.PLAYLIST_APPEND,
json.encodeToString(PlaylistAppendPayload.serializer(), payload),
)
suspend fun enqueuePlaylistCreate(payload: PlaylistCreatePayload): Long =
insertUserDriven(
MutationKind.PLAYLIST_CREATE,
json.encodeToString(PlaylistCreatePayload.serializer(), payload),
)
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 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 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 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),
)
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()
/**
* 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(
trackId: String,
reason: String,
notes: String,
): Long =
insertUserDriven(
MutationKind.QUARANTINE_FLAG,
json.encodeToString(
QuarantineFlagPayload.serializer(),
QuarantineFlagPayload(trackId, reason, notes),
),
)
/** Queues the user's whole normalization preference for replay. */
suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long =
insertUserDriven(
MutationKind.NORMALIZATION_SET,
json.encodeToString(NormalizationPrefs.serializer(), prefs),
)
suspend fun enqueueNotificationRead(id: String): Long =
insertUserDriven(
MutationKind.NOTIFICATION_READ,
json.encodeToString(NotificationReadPayload.serializer(), NotificationReadPayload(id)),
)
suspend fun enqueueNotificationsReadAll(upToIso: String?): Long =
insertUserDriven(
MutationKind.NOTIFICATIONS_READ_ALL,
json.encodeToString(
NotificationsReadAllPayload.serializer(),
NotificationsReadAllPayload(upToIso),
),
)
suspend fun enqueueNotificationSettingSet(payload: NotificationSettingPayload): Long =
insertUserDriven(
MutationKind.NOTIFICATION_SETTING_SET,
json.encodeToString(NotificationSettingPayload.serializer(), payload),
)
suspend fun enqueuePlayOffline(payload: PlayOfflinePayload): Long =
dao.insert(
CachedMutationEntity(
kind = MutationKind.PLAY_OFFLINE,
payload = json.encodeToString(PlayOfflinePayload.serializer(), payload),
),
)
suspend fun enqueuePlaybackErrorReport(payload: PlaybackErrorReportPayload): Long =
dao.insert(
CachedMutationEntity(
kind = MutationKind.PLAYBACK_ERROR_REPORT,
payload = json.encodeToString(PlaybackErrorReportPayload.serializer(), payload),
),
)
/**
* Durable close-by-id for an already-open server play row. Background
* path only (no user hint) — same as [enqueuePlayOffline].
*/
suspend fun enqueuePlayEnded(payload: PlayEndedPayload): Long =
dao.insert(
CachedMutationEntity(
kind = MutationKind.PLAY_ENDED,
payload = json.encodeToString(PlayEndedPayload.serializer(), payload),
),
)
private suspend fun insertUserDriven(
kind: String,
payload: String,
): Long {
val id = dao.insert(CachedMutationEntity(kind = kind, payload = payload))
_userEnqueueHints.tryEmit(QUEUED_MESSAGE)
return id
/**
* 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(
trackId: String,
reason: String,
notes: String,
): Long = insertUserDriven(
MutationKind.QUARANTINE_FLAG,
json.encodeToString(
QuarantineFlagPayload.serializer(),
QuarantineFlagPayload(trackId, reason, notes),
),
)
/** Queues the user's whole normalization preference for replay. */
suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long = insertUserDriven(
MutationKind.NORMALIZATION_SET,
json.encodeToString(NormalizationPrefs.serializer(), prefs),
)
suspend fun enqueueNotificationRead(id: String): Long = insertUserDriven(
MutationKind.NOTIFICATION_READ,
json.encodeToString(NotificationReadPayload.serializer(), NotificationReadPayload(id)),
)
suspend fun enqueueNotificationsReadAll(upToIso: String?): Long = insertUserDriven(
MutationKind.NOTIFICATIONS_READ_ALL,
json.encodeToString(
NotificationsReadAllPayload.serializer(),
NotificationsReadAllPayload(upToIso),
),
)
suspend fun enqueueNotificationSettingSet(payload: NotificationSettingPayload): Long =
insertUserDriven(
MutationKind.NOTIFICATION_SETTING_SET,
json.encodeToString(NotificationSettingPayload.serializer(), payload),
)
suspend fun enqueuePlayOffline(payload: PlayOfflinePayload): Long = dao.insert(
CachedMutationEntity(
kind = MutationKind.PLAY_OFFLINE,
payload = json.encodeToString(PlayOfflinePayload.serializer(), payload),
),
)
suspend fun enqueuePlaybackErrorReport(payload: PlaybackErrorReportPayload): Long = dao.insert(
CachedMutationEntity(
kind = MutationKind.PLAYBACK_ERROR_REPORT,
payload = json.encodeToString(PlaybackErrorReportPayload.serializer(), payload),
),
)
/**
* Durable close-by-id for an already-open server play row. Background
* path only (no user hint) — same as [enqueuePlayOffline].
*/
suspend fun enqueuePlayEnded(payload: PlayEndedPayload): Long = dao.insert(
CachedMutationEntity(
kind = MutationKind.PLAY_ENDED,
payload = json.encodeToString(PlayEndedPayload.serializer(), payload),
),
)
private suspend fun insertUserDriven(kind: String, payload: String): Long {
val id = dao.insert(CachedMutationEntity(kind = kind, payload = payload))
_userEnqueueHints.tryEmit(QUEUED_MESSAGE)
return id
}
}
/**
* Persisted payload for `MutationKind.QUARANTINE_UNFLAG` — the
* `DELETE /api/quarantine/{trackId}` call lost during a connectivity
* hiccup. The replayer just re-fires the DELETE; idempotent server-side.
*/
@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"
fun likeToggleKey(entityType: String, entityId: String): String = "$entityType:$entityId"
/**
* Persisted payload for `MutationKind.PLAYLIST_APPEND`: the track IDs to
@@ -352,9 +320,7 @@ data class PlaylistUpdatePayload(
/** Persisted payload for `MutationKind.PLAYLIST_DELETE`. */
@Serializable
data class PlaylistDeletePayload(
val playlistId: String,
)
data class PlaylistDeletePayload(val playlistId: String)
/**
* Persisted payload for `MutationKind.PLAYLIST_REMOVE_TRACK`. [trackId] is
@@ -439,9 +405,7 @@ data class PlaybackErrorReportPayload(
/** Persisted payload for `MutationKind.NOTIFICATION_READ`. */
@Serializable
data class NotificationReadPayload(
val id: String,
)
data class NotificationReadPayload(val id: String)
/**
* Persisted payload for `MutationKind.NOTIFICATIONS_READ_ALL`.
@@ -449,9 +413,7 @@ data class NotificationReadPayload(
* when the inbox was empty on the device, which marks everything.
*/
@Serializable
data class NotificationsReadAllPayload(
val upToIso: String?,
)
data class NotificationsReadAllPayload(val upToIso: String?)
/**
* Persisted payload for `MutationKind.NOTIFICATION_SETTING_SET`: one
@@ -9,24 +9,24 @@ import com.fabledsword.minstrel.api.endpoints.FlagRequest
import com.fabledsword.minstrel.api.endpoints.LikesApi
import com.fabledsword.minstrel.api.endpoints.MeApi
import com.fabledsword.minstrel.api.endpoints.NotificationsApi
import com.fabledsword.minstrel.api.endpoints.PutNotificationSettingsBody
import com.fabledsword.minstrel.api.endpoints.ReadAllBody
import com.fabledsword.minstrel.api.endpoints.PlaybackErrorReportRequest
import com.fabledsword.minstrel.api.endpoints.PlaybackErrorsApi
import com.fabledsword.minstrel.api.endpoints.PlaylistsApi
import com.fabledsword.minstrel.api.endpoints.PutNotificationSettingsBody
import com.fabledsword.minstrel.api.endpoints.QuarantineApi
import com.fabledsword.minstrel.api.endpoints.ReadAllBody
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.ServerHealth
import com.fabledsword.minstrel.models.wire.PlayEndedRequest
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
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.entities.CachedMutationEntity
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.di.ApplicationScope
import com.fabledsword.minstrel.likes.data.LikesRepository
import com.fabledsword.minstrel.models.wire.PlayEndedRequest
import com.fabledsword.minstrel.models.wire.PlayOfflineRequest
import com.fabledsword.minstrel.settings.data.NormalizationPrefs
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.distinctUntilChanged
@@ -35,6 +35,7 @@ import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.datetime.Clock
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
@@ -74,311 +75,296 @@ import javax.inject.Singleton
* forever.
*/
@Singleton
class MutationReplayer
@Inject
constructor(
private val dao: CachedMutationDao,
private val authStore: AuthStore,
private val accountCache: AccountCache,
private val json: Json,
@ApplicationScope private val scope: CoroutineScope,
networkStatus: NetworkStatusController,
retrofit: Retrofit,
) {
private val likesApi: LikesApi = retrofit.create()
private val quarantineApi: QuarantineApi = retrofit.create()
private val playlistsApi: PlaylistsApi = retrofit.create()
private val eventsApi: EventsApi = retrofit.create()
private val playbackErrorsApi: PlaybackErrorsApi = retrofit.create()
private val meApi: MeApi = retrofit.create()
private val notificationsApi: NotificationsApi = retrofit.create()
class MutationReplayer @Inject constructor(
private val dao: CachedMutationDao,
private val authStore: AuthStore,
private val accountCache: AccountCache,
private val json: Json,
@ApplicationScope private val scope: CoroutineScope,
networkStatus: NetworkStatusController,
retrofit: Retrofit,
) {
private val likesApi: LikesApi = retrofit.create()
private val quarantineApi: QuarantineApi = retrofit.create()
private val playlistsApi: PlaylistsApi = retrofit.create()
private val eventsApi: EventsApi = retrofit.create()
private val playbackErrorsApi: PlaybackErrorsApi = retrofit.create()
private val meApi: MeApi = retrofit.create()
private val notificationsApi: NotificationsApi = retrofit.create()
private val mutex = Mutex()
private val mutex = Mutex()
private enum class Outcome { SENT, DROP, RETRY }
private enum class Outcome { SENT, DROP, RETRY }
init {
scope.launch {
authStore.sessionCookie
.filterNotNull()
.distinctUntilChanged()
.collect { drainSafe() }
}
scope.launch {
accountCache.ownedBySignedInUser
.filter { it }
.collect { drainSafe() }
}
// Server-reachable-again: replay queued writes the moment the
// health signal recovers, so an offline→online transition mid-
// session doesn't wait for the next cold start / re-auth.
scope.launch {
networkStatus.state
.map { it == ServerHealth.Healthy }
.distinctUntilChanged()
.filter { it }
.collect { drainSafe() }
}
init {
scope.launch {
authStore.sessionCookie
.filterNotNull()
.distinctUntilChanged()
.collect { drainSafe() }
}
/** Public entry-point; coalesces concurrent triggers via a Mutex. */
suspend fun drainSafe() {
if (!mutex.tryLock()) return
try {
drain()
} finally {
mutex.unlock()
}
scope.launch {
accountCache.ownedBySignedInUser
.filter { it }
.collect { drainSafe() }
}
private suspend fun drain() {
// Another account's writes must not go out under this session.
if (!accountCache.ownedBySignedInUser.value) return
val rows = dao.getAll()
// Collapse superseded toggles (likes, settings): only the latest
// desired state per entity is replayed; older toggles for the same
// entity are dropped unsent. Without this, partial-failure +
// differential retry could replay an older toggle last and invert the
// final state — an unlike the user already made would be undone.
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) {
replayRow(row, superseded = row.id in superseded, waiting = waiting)
}
}
/**
* 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.RETRY -> {
dao.recordAttempt(row.id, Clock.System.now())
playlistId?.let(waiting::add)
}
}
}
}
private suspend fun outcomeFor(row: CachedMutationEntity): Outcome =
try {
dispatch(row)
} catch (e: HttpException) {
if (isPermanent(e.code())) Outcome.DROP else Outcome.RETRY
} catch (
@Suppress("SwallowedException") e: SerializationException,
) {
// Corrupt / schema-incompatible payload — permanent, drop it.
Outcome.DROP
} catch (
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
) {
// Transport / unknown — leave queued for the next pass.
Outcome.RETRY
}
/** A refusal that a replay would only get again ([isRetryableStatus]'s complement). */
private fun isPermanent(code: Int): Boolean = !isRetryableStatus(code)
/**
* Returns the outcome of replaying one row. SENT on a 2xx; DROP for an
* unknown kind/variant. Network / HTTP failures THROW and are classified
* by [outcomeFor] — dispatchers never swallow them.
*/
private suspend fun dispatch(row: CachedMutationEntity): Outcome =
when (row.kind) {
MutationKind.LIKE_TOGGLE -> dispatchLikeToggle(row.payload)
MutationKind.QUARANTINE_UNFLAG -> dispatchQuarantineUnflag(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.PLAY_OFFLINE -> dispatchPlayOffline(row.payload)
MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload)
MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload)
MutationKind.NORMALIZATION_SET -> dispatchNormalizationSet(row.payload)
MutationKind.NOTIFICATION_READ,
MutationKind.NOTIFICATIONS_READ_ALL,
MutationKind.NOTIFICATION_SETTING_SET,
-> dispatchNotification(row)
// Unknown kind — drop so a stale schema entry can't wedge the queue.
else -> Outcome.DROP
}
/** The notifications inbox's kinds, split out to keep [dispatch] simple. */
private suspend fun dispatchNotification(row: CachedMutationEntity): Outcome =
when (row.kind) {
MutationKind.NOTIFICATION_READ -> dispatchNotificationRead(row.payload)
MutationKind.NOTIFICATIONS_READ_ALL -> dispatchNotificationsReadAll(row.payload)
MutationKind.NOTIFICATION_SETTING_SET -> dispatchNotificationSettingSet(row.payload)
else -> Outcome.DROP
}
private suspend fun dispatchLikeToggle(payload: String): Outcome {
val decoded = json.decodeFromString(LikeTogglePayload.serializer(), payload)
val kindPath =
when (decoded.entityType) {
LikesRepository.ENTITY_ARTIST -> "artists"
LikesRepository.ENTITY_ALBUM -> "albums"
LikesRepository.ENTITY_TRACK -> "tracks"
else -> return Outcome.DROP
}
if (decoded.desiredState) {
likesApi.like(kindPath, decoded.entityId)
} else {
likesApi.unlike(kindPath, decoded.entityId)
}
return Outcome.SENT
}
private suspend fun dispatchQuarantineUnflag(payload: String): Outcome {
val decoded = json.decodeFromString(QuarantineUnflagPayload.serializer(), payload)
quarantineApi.unflag(decoded.trackId)
return Outcome.SENT
}
/**
* A listener's own playlists, split out to keep [dispatch] simple. A
* 404 or 409 is a 4xx, so DROP: the list is gone, or has changed since,
* and nothing is left to do.
*/
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
}
private suspend fun dispatchQuarantineFlag(payload: String): Outcome {
val decoded = json.decodeFromString(QuarantineFlagPayload.serializer(), payload)
quarantineApi.flag(
FlagRequest(
trackId = decoded.trackId,
reason = decoded.reason,
notes = decoded.notes,
),
)
return Outcome.SENT
}
private suspend fun dispatchPlayOffline(payload: String): Outcome {
val decoded = json.decodeFromString(PlayOfflinePayload.serializer(), payload)
eventsApi.playOffline(
PlayOfflineRequest(
trackId = decoded.trackId,
clientId = decoded.clientId,
at = decoded.atIso,
durationPlayedMs = decoded.durationPlayedMs,
source = decoded.source,
deviceClass = decoded.deviceClass,
),
)
return Outcome.SENT
}
private suspend fun dispatchPlayEnded(payload: String): Outcome {
val decoded = json.decodeFromString(PlayEndedPayload.serializer(), payload)
eventsApi.playEnded(
PlayEndedRequest(
playEventId = decoded.playEventId,
durationPlayedMs = decoded.durationPlayedMs,
),
)
return Outcome.SENT
}
/**
* Sends the queued normalization preference. The device already shows
* it, so the server's echo is not written back: a change made since the
* row was queued would be a newer row, and the collapse keeps only that.
*/
private suspend fun dispatchNormalizationSet(payload: String): Outcome {
meApi.putNormalization(json.decodeFromString(NormalizationPrefs.serializer(), payload))
return Outcome.SENT
}
/** A 404 (the notice was trimmed or already gone) is a 4xx, so DROP: nothing left to do. */
private suspend fun dispatchNotificationRead(payload: String): Outcome {
val decoded = json.decodeFromString(NotificationReadPayload.serializer(), payload)
notificationsApi.markRead(decoded.id)
return Outcome.SENT
}
private suspend fun dispatchNotificationsReadAll(payload: String): Outcome {
val decoded = json.decodeFromString(NotificationsReadAllPayload.serializer(), payload)
notificationsApi.readAll(ReadAllBody(upTo = decoded.upToIso))
return Outcome.SENT
}
/** An unknown channel can only come from a corrupt row: DROP it. */
private suspend fun dispatchNotificationSettingSet(payload: String): Outcome {
val decoded = json.decodeFromString(NotificationSettingPayload.serializer(), payload)
val change = notificationSettingChange(decoded) ?: return Outcome.DROP
notificationsApi.putSettings(PutNotificationSettingsBody(listOf(change)))
return Outcome.SENT
}
private suspend fun dispatchPlaybackErrorReport(payload: String): Outcome {
val decoded = json.decodeFromString(PlaybackErrorReportPayload.serializer(), payload)
playbackErrorsApi.report(
PlaybackErrorReportRequest(
trackId = decoded.trackId,
kind = decoded.kind,
detail = decoded.detail,
clientId = decoded.clientId,
),
)
return Outcome.SENT
// Server-reachable-again: replay queued writes the moment the
// health signal recovers, so an offline→online transition mid-
// session doesn't wait for the next cold start / re-auth.
scope.launch {
networkStatus.state
.map { it == ServerHealth.Healthy }
.distinctUntilChanged()
.filter { it }
.collect { drainSafe() }
}
}
/** Public entry-point; coalesces concurrent triggers via a Mutex. */
suspend fun drainSafe() {
if (!mutex.tryLock()) return
try {
drain()
} finally {
mutex.unlock()
}
}
private suspend fun drain() {
// Another account's writes must not go out under this session.
if (!accountCache.ownedBySignedInUser.value) return
val rows = dao.getAll()
// Collapse superseded toggles (likes, settings): only the latest
// desired state per entity is replayed; older toggles for the same
// entity are dropped unsent. Without this, partial-failure +
// differential retry could replay an older toggle last and invert the
// final state — an unlike the user already made would be undone.
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) {
replayRow(row, superseded = row.id in superseded, waiting = waiting)
}
}
/**
* 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.RETRY -> {
dao.recordAttempt(row.id, Clock.System.now())
playlistId?.let(waiting::add)
}
}
}
}
private suspend fun outcomeFor(row: CachedMutationEntity): Outcome = try {
dispatch(row)
} catch (e: HttpException) {
if (isPermanent(e.code())) Outcome.DROP else Outcome.RETRY
} catch (@Suppress("SwallowedException") e: SerializationException) {
// Corrupt / schema-incompatible payload — permanent, drop it.
Outcome.DROP
} catch (@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable) {
// Transport / unknown — leave queued for the next pass.
Outcome.RETRY
}
/** A refusal that a replay would only get again ([isRetryableStatus]'s complement). */
private fun isPermanent(code: Int): Boolean = !isRetryableStatus(code)
/**
* Returns the outcome of replaying one row. SENT on a 2xx; DROP for an
* unknown kind/variant. Network / HTTP failures THROW and are classified
* by [outcomeFor] — dispatchers never swallow them.
*/
private suspend fun dispatch(row: CachedMutationEntity): Outcome = when (row.kind) {
MutationKind.LIKE_TOGGLE -> dispatchLikeToggle(row.payload)
MutationKind.QUARANTINE_UNFLAG -> dispatchQuarantineUnflag(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.PLAY_OFFLINE -> dispatchPlayOffline(row.payload)
MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload)
MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload)
MutationKind.NORMALIZATION_SET -> dispatchNormalizationSet(row.payload)
MutationKind.NOTIFICATION_READ,
MutationKind.NOTIFICATIONS_READ_ALL,
MutationKind.NOTIFICATION_SETTING_SET,
-> dispatchNotification(row)
// Unknown kind — drop so a stale schema entry can't wedge the queue.
else -> Outcome.DROP
}
/** The notifications inbox's kinds, split out to keep [dispatch] simple. */
private suspend fun dispatchNotification(row: CachedMutationEntity): Outcome = when (row.kind) {
MutationKind.NOTIFICATION_READ -> dispatchNotificationRead(row.payload)
MutationKind.NOTIFICATIONS_READ_ALL -> dispatchNotificationsReadAll(row.payload)
MutationKind.NOTIFICATION_SETTING_SET -> dispatchNotificationSettingSet(row.payload)
else -> Outcome.DROP
}
private suspend fun dispatchLikeToggle(payload: String): Outcome {
val decoded = json.decodeFromString(LikeTogglePayload.serializer(), payload)
val kindPath = when (decoded.entityType) {
LikesRepository.ENTITY_ARTIST -> "artists"
LikesRepository.ENTITY_ALBUM -> "albums"
LikesRepository.ENTITY_TRACK -> "tracks"
else -> return Outcome.DROP
}
if (decoded.desiredState) {
likesApi.like(kindPath, decoded.entityId)
} else {
likesApi.unlike(kindPath, decoded.entityId)
}
return Outcome.SENT
}
private suspend fun dispatchQuarantineUnflag(payload: String): Outcome {
val decoded = json.decodeFromString(QuarantineUnflagPayload.serializer(), payload)
quarantineApi.unflag(decoded.trackId)
return Outcome.SENT
}
/**
* A listener's own playlists, split out to keep [dispatch] simple. A
* 404 or 409 is a 4xx, so DROP: the list is gone, or has changed since,
* and nothing is left to do.
*/
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
}
private suspend fun dispatchQuarantineFlag(payload: String): Outcome {
val decoded = json.decodeFromString(QuarantineFlagPayload.serializer(), payload)
quarantineApi.flag(
FlagRequest(
trackId = decoded.trackId,
reason = decoded.reason,
notes = decoded.notes,
),
)
return Outcome.SENT
}
private suspend fun dispatchPlayOffline(payload: String): Outcome {
val decoded = json.decodeFromString(PlayOfflinePayload.serializer(), payload)
eventsApi.playOffline(
PlayOfflineRequest(
trackId = decoded.trackId,
clientId = decoded.clientId,
at = decoded.atIso,
durationPlayedMs = decoded.durationPlayedMs,
source = decoded.source,
deviceClass = decoded.deviceClass,
),
)
return Outcome.SENT
}
private suspend fun dispatchPlayEnded(payload: String): Outcome {
val decoded = json.decodeFromString(PlayEndedPayload.serializer(), payload)
eventsApi.playEnded(
PlayEndedRequest(
playEventId = decoded.playEventId,
durationPlayedMs = decoded.durationPlayedMs,
),
)
return Outcome.SENT
}
/**
* Sends the queued normalization preference. The device already shows
* it, so the server's echo is not written back: a change made since the
* row was queued would be a newer row, and the collapse keeps only that.
*/
private suspend fun dispatchNormalizationSet(payload: String): Outcome {
meApi.putNormalization(json.decodeFromString(NormalizationPrefs.serializer(), payload))
return Outcome.SENT
}
/** A 404 (the notice was trimmed or already gone) is a 4xx, so DROP: nothing left to do. */
private suspend fun dispatchNotificationRead(payload: String): Outcome {
val decoded = json.decodeFromString(NotificationReadPayload.serializer(), payload)
notificationsApi.markRead(decoded.id)
return Outcome.SENT
}
private suspend fun dispatchNotificationsReadAll(payload: String): Outcome {
val decoded = json.decodeFromString(NotificationsReadAllPayload.serializer(), payload)
notificationsApi.readAll(ReadAllBody(upTo = decoded.upToIso))
return Outcome.SENT
}
/** An unknown channel can only come from a corrupt row: DROP it. */
private suspend fun dispatchNotificationSettingSet(payload: String): Outcome {
val decoded = json.decodeFromString(NotificationSettingPayload.serializer(), payload)
val change = notificationSettingChange(decoded) ?: return Outcome.DROP
notificationsApi.putSettings(PutNotificationSettingsBody(listOf(change)))
return Outcome.SENT
}
private suspend fun dispatchPlaybackErrorReport(payload: String): Outcome {
val decoded = json.decodeFromString(PlaybackErrorReportPayload.serializer(), payload)
playbackErrorsApi.report(
PlaybackErrorReportRequest(
trackId = decoded.trackId,
kind = decoded.kind,
detail = decoded.detail,
clientId = decoded.clientId,
),
)
return Outcome.SENT
}
}
/**
* 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
@@ -390,14 +376,10 @@ class MutationReplayer
* instance. [rows] must be ascending by id (FIFO), which is what
* `CachedMutationDao.getAll()` returns.
*/
internal fun supersededToggleIds(
rows: List<CachedMutationEntity>,
json: Json,
): Set<Long> {
internal fun supersededToggleIds(rows: List<CachedMutationEntity>, json: Json): Set<Long> {
val latestByEntity = HashMap<String, Long>()
val superseded = HashSet<Long>()
rows
.asSequence()
rows.asSequence()
.mapNotNull { row -> toggleKeyOf(row, json)?.let { key -> key to row.id } }
.forEach { (key, id) ->
// Ascending ids mean a prior entry for this key is always older.
@@ -415,58 +397,46 @@ internal fun supersededToggleIds(
* The kind is part of the key so two toggle kinds can never collide on the
* same entity id.
*/
private fun toggleKeyOf(
row: CachedMutationEntity,
json: Json,
): String? =
when (row.kind) {
MutationKind.LIKE_TOGGLE ->
runCatching {
json.decodeFromString(LikeTogglePayload.serializer(), row.payload)
}.getOrNull()?.let { "${row.kind}:${it.entityType}:${it.entityId}" }
private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when (row.kind) {
MutationKind.LIKE_TOGGLE -> runCatching {
json.decodeFromString(LikeTogglePayload.serializer(), row.payload)
}.getOrNull()?.let { "${row.kind}:${it.entityType}:${it.entityId}" }
MutationKind.NOTIFICATION_SETTING_SET ->
runCatching {
json.decodeFromString(NotificationSettingPayload.serializer(), row.payload)
}.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" }
MutationKind.NOTIFICATION_SETTING_SET -> runCatching {
json.decodeFromString(NotificationSettingPayload.serializer(), row.payload)
}.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}" }
// 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.
MutationKind.NORMALIZATION_SET ->
runCatching {
json.decodeFromString(NormalizationPrefs.serializer(), row.payload)
}.getOrNull()?.let { row.kind }
// One preference per user, so every normalization row shares one key.
MutationKind.NORMALIZATION_SET -> runCatching {
json.decodeFromString(NormalizationPrefs.serializer(), row.payload)
}.getOrNull()?.let { row.kind }
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()
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()
@@ -13,10 +13,8 @@ import javax.inject.Inject
* accessor. Mirrors PlaybackErrorViewModel.
*/
@HiltViewModel
class OfflineWriteHintViewModel
@Inject
constructor(
mutationQueue: MutationQueue,
) : ViewModel() {
val messages: Flow<String> = mutationQueue.userEnqueueHints
}
class OfflineWriteHintViewModel @Inject constructor(
mutationQueue: MutationQueue,
) : ViewModel() {
val messages: Flow<String> = mutationQueue.userEnqueueHints
}
@@ -3,6 +3,8 @@ package com.fabledsword.minstrel.cache.sync
import com.fabledsword.minstrel.api.ErrorCopy
import com.fabledsword.minstrel.api.endpoints.SyncApi
import com.fabledsword.minstrel.auth.AuthStore
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao
import com.fabledsword.minstrel.cache.db.dao.CachedArtistDao
import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao
@@ -11,8 +13,6 @@ import com.fabledsword.minstrel.cache.db.entities.CachedAlbumEntity
import com.fabledsword.minstrel.cache.db.entities.CachedArtistEntity
import com.fabledsword.minstrel.cache.db.entities.CachedTrackEntity
import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity
import com.fabledsword.minstrel.connectivity.NetworkStatusController
import com.fabledsword.minstrel.connectivity.ServerHealth
import com.fabledsword.minstrel.di.ApplicationScope
import com.fabledsword.minstrel.models.wire.SyncAlbumWire
import com.fabledsword.minstrel.models.wire.SyncArtistWire
@@ -50,204 +50,199 @@ import javax.inject.Singleton
* cursor to 0 and pulls the full entity set again (see [resetCursor]).
*/
@Singleton
class SyncController
@Inject
constructor(
private val syncMetadataDao: SyncMetadataDao,
private val artistDao: CachedArtistDao,
private val albumDao: CachedAlbumDao,
private val trackDao: CachedTrackDao,
private val authStore: AuthStore,
@ApplicationScope private val scope: CoroutineScope,
networkStatus: NetworkStatusController,
retrofit: Retrofit,
) {
private val api: SyncApi = retrofit.create()
class SyncController @Inject constructor(
private val syncMetadataDao: SyncMetadataDao,
private val artistDao: CachedArtistDao,
private val albumDao: CachedAlbumDao,
private val trackDao: CachedTrackDao,
private val authStore: AuthStore,
@ApplicationScope private val scope: CoroutineScope,
networkStatus: NetworkStatusController,
retrofit: Retrofit,
) {
private val api: SyncApi = retrofit.create()
// Single in-flight guard: the cookie + health-recovery triggers (and a
// pull-to-refresh) can fire concurrently; coalesce them into one pass.
private val mutex = Mutex()
// Single in-flight guard: the cookie + health-recovery triggers (and a
// pull-to-refresh) can fire concurrently; coalesce them into one pass.
private val mutex = Mutex()
private val lastSyncErrorInternal = MutableStateFlow<String?>(null)
private val lastSyncErrorInternal = MutableStateFlow<String?>(null)
/**
* Human copy for the most recent sync failure; null after any clean
* pass. Lets the Library screen distinguish "empty because the first
* sync failed" (show error + retry) from "genuinely empty library"
* (show welcome copy) — a failed sync over a populated cache stays
* silent, since the cached content is still the better surface.
*/
val lastSyncError: StateFlow<String?> = lastSyncErrorInternal.asStateFlow()
/**
* Human copy for the most recent sync failure; null after any clean
* pass. Lets the Library screen distinguish "empty because the first
* sync failed" (show error + retry) from "genuinely empty library"
* (show welcome copy) — a failed sync over a populated cache stays
* silent, since the cached content is still the better surface.
*/
val lastSyncError: StateFlow<String?> = lastSyncErrorInternal.asStateFlow()
init {
scope.launch {
authStore.sessionCookie
.filterNotNull()
.distinctUntilChanged()
.collect { syncSafe() }
}
// Re-sync when the server becomes reachable again mid-session, so a
// delta missed while offline lands without waiting for a cold start.
scope.launch {
networkStatus.state
.map { it == ServerHealth.Healthy }
.distinctUntilChanged()
.filter { it }
.collect { syncSafe() }
}
init {
scope.launch {
authStore.sessionCookie
.filterNotNull()
.distinctUntilChanged()
.collect { syncSafe() }
}
/** Public entry-point for "Sync now" affordances. Swallows errors into [lastSyncError]. */
suspend fun syncSafe() {
if (!mutex.tryLock()) return
try {
runCatching { sync() }
.onSuccess { lastSyncErrorInternal.value = null }
.onFailure { lastSyncErrorInternal.value = ErrorCopy.fromThrowable(it) }
} finally {
mutex.unlock()
}
}
/**
* Pulls pages until the server has nothing newer. The server returns
* at most 1000 changes a call, and a full library re-read adds tens
* of thousands, so one page per trigger would leave the cache behind:
* merge deletes would never arrive and the freshness sweep would keep
* asking for tracks that are gone. The cursor is stored after each
* page, so an interrupted pass resumes where it stopped.
*/
private suspend fun sync() {
repeat(MAX_PAGES_PER_PASS) {
if (!syncPage()) return
}
}
/** One page of the change log. True when the server may hold more. */
private suspend fun syncPage(): Boolean {
val meta = syncMetadataDao.get()
val cursor = meta?.cursor ?: 0L
val response = api.sync(cursor)
return when (response.code()) {
HTTP_NO_CONTENT -> {
touchLastSyncAt(cursor)
false
}
HTTP_GONE -> {
resetCursor()
true
}
HTTP_OK -> {
val body = response.body() ?: return false
applyDeltas(body.upserts.artist, body.upserts.album, body.upserts.track)
applyDeletes(body.deletes.artist, body.deletes.album, body.deletes.track)
syncMetadataDao.upsert(
SyncMetadataEntity(
id = 0,
cursor = body.cursor,
lastSyncAt = Clock.System.now(),
),
)
// A cursor that did not advance would ask for the same page
// again; stop rather than spin.
body.cursor > cursor
}
else -> {
// Unhandled status — treat as a no-op; the next
// app start retries from the same cursor.
false
}
}
}
private suspend fun applyDeltas(
artists: List<SyncArtistWire>,
albums: List<SyncAlbumWire>,
tracks: List<SyncTrackWire>,
) {
if (artists.isNotEmpty()) artistDao.upsertAll(artists.map { it.toEntity() })
if (albums.isNotEmpty()) albumDao.upsertAll(albums.map { it.toEntity() })
if (tracks.isNotEmpty()) trackDao.upsertAll(tracks.map { it.toEntity() })
}
private suspend fun applyDeletes(
artistIds: List<String>,
albumIds: List<String>,
trackIds: List<String>,
) {
if (artistIds.isNotEmpty()) artistDao.deleteByIds(artistIds)
if (albumIds.isNotEmpty()) albumDao.deleteByIds(albumIds)
if (trackIds.isNotEmpty()) trackDao.deleteByIds(trackIds)
}
private suspend fun touchLastSyncAt(cursor: Long) {
syncMetadataDao.upsert(
SyncMetadataEntity(id = 0, cursor = cursor, lastSyncAt = Clock.System.now()),
)
}
private suspend fun resetCursor() {
// The Library DAOs only expose deleteByIds; for the rare 410
// path the next page is requested with cursor=0 after
// resetting our cursor. The following pages carry the full
// entity set, which upsertAll overwrites the existing rows
// with — old rows for entities the server no longer knows
// about linger until MetadataProvider's refresh meets their
// 404 and drops them.
syncMetadataDao.upsert(
SyncMetadataEntity(id = 0, cursor = 0, lastSyncAt = null),
)
}
private companion object {
const val HTTP_OK = 200
const val HTTP_NO_CONTENT = 204
const val HTTP_GONE = 410
// A guard, not a budget: 1000 pages is a million changes, far past
// anything a library writes between two app starts.
const val MAX_PAGES_PER_PASS = 1000
// Re-sync when the server becomes reachable again mid-session, so a
// delta missed while offline lands without waiting for a cold start.
scope.launch {
networkStatus.state
.map { it == ServerHealth.Healthy }
.distinctUntilChanged()
.filter { it }
.collect { syncSafe() }
}
}
/** Public entry-point for "Sync now" affordances. Swallows errors into [lastSyncError]. */
suspend fun syncSafe() {
if (!mutex.tryLock()) return
try {
runCatching { sync() }
.onSuccess { lastSyncErrorInternal.value = null }
.onFailure { lastSyncErrorInternal.value = ErrorCopy.fromThrowable(it) }
} finally {
mutex.unlock()
}
}
/**
* Pulls pages until the server has nothing newer. The server returns
* at most 1000 changes a call, and a full library re-read adds tens
* of thousands, so one page per trigger would leave the cache behind:
* merge deletes would never arrive and the freshness sweep would keep
* asking for tracks that are gone. The cursor is stored after each
* page, so an interrupted pass resumes where it stopped.
*/
private suspend fun sync() {
repeat(MAX_PAGES_PER_PASS) {
if (!syncPage()) return
}
}
/** One page of the change log. True when the server may hold more. */
private suspend fun syncPage(): Boolean {
val meta = syncMetadataDao.get()
val cursor = meta?.cursor ?: 0L
val response = api.sync(cursor)
return when (response.code()) {
HTTP_NO_CONTENT -> {
touchLastSyncAt(cursor)
false
}
HTTP_GONE -> {
resetCursor()
true
}
HTTP_OK -> {
val body = response.body() ?: return false
applyDeltas(body.upserts.artist, body.upserts.album, body.upserts.track)
applyDeletes(body.deletes.artist, body.deletes.album, body.deletes.track)
syncMetadataDao.upsert(
SyncMetadataEntity(
id = 0,
cursor = body.cursor,
lastSyncAt = Clock.System.now(),
),
)
// A cursor that did not advance would ask for the same page
// again; stop rather than spin.
body.cursor > cursor
}
else -> {
// Unhandled status — treat as a no-op; the next
// app start retries from the same cursor.
false
}
}
}
private suspend fun applyDeltas(
artists: List<SyncArtistWire>,
albums: List<SyncAlbumWire>,
tracks: List<SyncTrackWire>,
) {
if (artists.isNotEmpty()) artistDao.upsertAll(artists.map { it.toEntity() })
if (albums.isNotEmpty()) albumDao.upsertAll(albums.map { it.toEntity() })
if (tracks.isNotEmpty()) trackDao.upsertAll(tracks.map { it.toEntity() })
}
private suspend fun applyDeletes(
artistIds: List<String>,
albumIds: List<String>,
trackIds: List<String>,
) {
if (artistIds.isNotEmpty()) artistDao.deleteByIds(artistIds)
if (albumIds.isNotEmpty()) albumDao.deleteByIds(albumIds)
if (trackIds.isNotEmpty()) trackDao.deleteByIds(trackIds)
}
private suspend fun touchLastSyncAt(cursor: Long) {
syncMetadataDao.upsert(
SyncMetadataEntity(id = 0, cursor = cursor, lastSyncAt = Clock.System.now()),
)
}
private suspend fun resetCursor() {
// The Library DAOs only expose deleteByIds; for the rare 410
// path the next page is requested with cursor=0 after
// resetting our cursor. The following pages carry the full
// entity set, which upsertAll overwrites the existing rows
// with — old rows for entities the server no longer knows
// about linger until MetadataProvider's refresh meets their
// 404 and drops them.
syncMetadataDao.upsert(
SyncMetadataEntity(id = 0, cursor = 0, lastSyncAt = null),
)
}
private companion object {
const val HTTP_OK = 200
const val HTTP_NO_CONTENT = 204
const val HTTP_GONE = 410
// A guard, not a budget: 1000 pages is a million changes, far past
// anything a library writes between two app starts.
const val MAX_PAGES_PER_PASS = 1000
}
}
// ── Mappers (file-internal — sync wire types stay out of UI) ──
private fun SyncArtistWire.toEntity(): CachedArtistEntity =
CachedArtistEntity(
id = id,
name = name,
sortName = sortName,
mbid = mbid,
artistThumbPath = artistThumbPath,
artistFanartPath = artistFanartPath,
)
private fun SyncArtistWire.toEntity(): CachedArtistEntity = CachedArtistEntity(
id = id,
name = name,
sortName = sortName,
mbid = mbid,
artistThumbPath = artistThumbPath,
artistFanartPath = artistFanartPath,
)
private fun SyncAlbumWire.toEntity(): CachedAlbumEntity =
CachedAlbumEntity(
id = id,
artistId = artistId,
title = title,
sortTitle = sortTitle,
releaseDate = releaseDate,
coverPath = coverArtPath,
mbid = mbid,
albumGain = albumGain,
albumPeak = albumPeak,
)
private fun SyncAlbumWire.toEntity(): CachedAlbumEntity = CachedAlbumEntity(
id = id,
artistId = artistId,
title = title,
sortTitle = sortTitle,
releaseDate = releaseDate,
coverPath = coverArtPath,
mbid = mbid,
albumGain = albumGain,
albumPeak = albumPeak,
)
private fun SyncTrackWire.toEntity(): CachedTrackEntity =
CachedTrackEntity(
id = id,
albumId = albumId,
artistId = artistId,
title = title,
durationMs = durationMs,
trackNumber = trackNumber,
discNumber = discNumber,
filePath = filePath,
fileFormat = fileFormat,
genre = genre,
missing = missing,
trackGain = trackGain,
trackPeak = trackPeak,
)
private fun SyncTrackWire.toEntity(): CachedTrackEntity = CachedTrackEntity(
id = id,
albumId = albumId,
artistId = artistId,
title = title,
durationMs = durationMs,
trackNumber = trackNumber,
discNumber = discNumber,
filePath = filePath,
fileFormat = fileFormat,
genre = genre,
missing = missing,
trackGain = trackGain,
trackPeak = trackPeak,
)
@@ -36,87 +36,76 @@ import javax.inject.Singleton
* repositories can also collect this to gate retry loops.
*/
@Singleton
class ConnectivityObserver
@Inject
constructor(
@ApplicationContext context: Context,
) {
private val cm = context.getSystemService(ConnectivityManager::class.java)
class ConnectivityObserver @Inject constructor(
@ApplicationContext context: Context,
) {
private val cm = context.getSystemService(ConnectivityManager::class.java)
val online: Flow<Boolean> =
callbackFlow {
val request =
NetworkRequest
.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
val callback =
object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
trySend(hasActiveNetwork())
}
override fun onLost(network: Network) {
trySend(hasActiveNetwork())
}
override fun onCapabilitiesChanged(
network: Network,
capabilities: NetworkCapabilities,
) {
// INTERNET only -- NOT VALIDATED. A WAN/validation flicker
// must not read as "device offline" when the LAN (and the
// Minstrel server on it) is still reachable. /healthz is the
// authority on server reachability.
trySend(
capabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_INTERNET,
),
)
}
}
cm.registerNetworkCallback(request, callback)
// Seed the initial value so the banner doesn't flash before the
// first capability callback fires.
val online: Flow<Boolean> = callbackFlow {
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
val callback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
trySend(hasActiveNetwork())
awaitClose { cm.unregisterNetworkCallback(callback) }
}.distinctUntilChanged()
/**
* Whether the network the device is using now is unmetered: Wi-Fi or
* Ethernet, but not mobile data or a hotspot Android marks metered.
* Downloads the user did not start (the liked-song downloads) wait for
* this.
*/
val unmetered: Flow<Boolean> =
callbackFlow {
val callback =
object : ConnectivityManager.NetworkCallback() {
override fun onCapabilitiesChanged(
network: Network,
capabilities: NetworkCapabilities,
) {
trySend(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED))
}
override fun onLost(network: Network) {
trySend(false)
}
}
cm.registerDefaultNetworkCallback(callback)
trySend(isActiveNetworkUnmetered())
awaitClose { cm.unregisterNetworkCallback(callback) }
}.distinctUntilChanged()
private fun isActiveNetworkUnmetered(): Boolean {
val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) }
return caps != null &&
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
}
override fun onLost(network: Network) {
trySend(hasActiveNetwork())
}
override fun onCapabilitiesChanged(
network: Network,
capabilities: NetworkCapabilities,
) {
// INTERNET only -- NOT VALIDATED. A WAN/validation flicker
// must not read as "device offline" when the LAN (and the
// Minstrel server on it) is still reachable. /healthz is the
// authority on server reachability.
trySend(
capabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_INTERNET,
),
)
}
}
cm.registerNetworkCallback(request, callback)
// Seed the initial value so the banner doesn't flash before the
// first capability callback fires.
trySend(hasActiveNetwork())
awaitClose { cm.unregisterNetworkCallback(callback) }
}.distinctUntilChanged()
private fun hasActiveNetwork(): Boolean {
val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) }
return caps != null &&
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
/**
* Whether the network the device is using now is unmetered: Wi-Fi or
* Ethernet, but not mobile data or a hotspot Android marks metered.
* Downloads the user did not start (the liked-song downloads) wait for
* this.
*/
val unmetered: Flow<Boolean> = callbackFlow {
val callback = object : ConnectivityManager.NetworkCallback() {
override fun onCapabilitiesChanged(
network: Network,
capabilities: NetworkCapabilities,
) {
trySend(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED))
}
override fun onLost(network: Network) {
trySend(false)
}
}
cm.registerDefaultNetworkCallback(callback)
trySend(isActiveNetworkUnmetered())
awaitClose { cm.unregisterNetworkCallback(callback) }
}.distinctUntilChanged()
private fun isActiveNetworkUnmetered(): Boolean {
val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) }
return caps != null &&
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
}
private fun hasActiveNetwork(): Boolean {
val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) }
return caps != null &&
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
}
}
@@ -55,155 +55,140 @@ private const val ARBITRATE_MIN_GAP_MS = 2_000L
* [com.fabledsword.minstrel.MinstrelApplication].
*/
@Singleton
class NetworkStatusController
@Inject
constructor(
@ApplicationScope private val scope: CoroutineScope,
connectivity: ConnectivityObserver,
private val authStore: AuthStore,
retrofit: Retrofit,
) : DefaultLifecycleObserver {
private val api: HealthzApi = retrofit.create(HealthzApi::class.java)
private val machine = ReachabilityMachine()
private val lastProbeAtMs = AtomicLong(0)
class NetworkStatusController @Inject constructor(
@ApplicationScope private val scope: CoroutineScope,
connectivity: ConnectivityObserver,
private val authStore: AuthStore,
retrofit: Retrofit,
) : DefaultLifecycleObserver {
private val api: HealthzApi = retrofit.create(HealthzApi::class.java)
private val machine = ReachabilityMachine()
private val lastProbeAtMs = AtomicLong(0)
private val stateInternal = MutableStateFlow(ServerHealth.Healthy)
val state: StateFlow<ServerHealth> = stateInternal.asStateFlow()
private val stateInternal = MutableStateFlow(ServerHealth.Healthy)
val state: StateFlow<ServerHealth> = stateInternal.asStateFlow()
private val versionInternal = MutableStateFlow(VersionResult.SKIPPED)
val versionResult: StateFlow<VersionResult> = versionInternal.asStateFlow()
private val versionInternal = MutableStateFlow(VersionResult.SKIPPED)
val versionResult: StateFlow<VersionResult> = versionInternal.asStateFlow()
private sealed interface Intent {
data class Link(
val up: Boolean,
) : Intent
private sealed interface Intent {
data class Link(val up: Boolean) : Intent
data class Probe(val resp: HealthzResponse?) : Intent
object OpSuccess : Intent
object OpFailure : Intent
}
data class Probe(
val resp: HealthzResponse?,
) : Intent
private val intents = Channel<Intent>(Channel.UNLIMITED)
object OpSuccess : Intent
object OpFailure : Intent
}
private val intents = Channel<Intent>(Channel.UNLIMITED)
init {
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
scope.launch { reduceLoop() }
scope.launch {
connectivity.online.collect { up ->
intents.trySend(Intent.Link(up))
if (up) probeOnce()
}
}
scope.launch { pollLoop() }
}
/** A real server op verifiably succeeded — self-proving recovery. Cheap; safe on hot paths. */
fun reportSuccess() {
if (stateInternal.value != ServerHealth.Healthy) intents.trySend(Intent.OpSuccess)
}
/** A real network op failed — triggers /healthz arbitration. No-op when already Offline. */
fun reportFailure() {
if (stateInternal.value == ServerHealth.Offline) return
intents.trySend(Intent.OpFailure)
}
/** One-shot recheck for pull-to-refresh and the banner. */
fun recheck() {
scope.launch { probeOnce(force = true) }
}
/**
* App returned to the foreground — probe now rather than waiting for the
* poll loop.
*
* The link-return probe in `init` does NOT cover this: it fires on a
* connectivity *change*, and an app backgrounded on stable Wi-Fi sees none.
* force = true so this also bypasses the ARBITRATE_MIN_GAP_MS throttle —
* a user bringing the app up is exactly when a stale banner and a refused
* track are most visible, and it's a once-per-foreground cost.
*/
override fun onStart(owner: LifecycleOwner) {
recheck()
}
private suspend fun reduceLoop() {
for (intent in intents) {
val now = System.currentTimeMillis()
when (intent) {
is Intent.Link -> machine.onLinkChange(intent.up)
is Intent.Probe -> applyProbe(intent.resp, now)
Intent.OpSuccess -> machine.onSuccess()
Intent.OpFailure -> {
machine.onOpFailure(now)
// Arbitrate off the reducer thread: awaiting a stalled
// /healthz here would block a concurrent self-proving
// success from snapping us straight back to Healthy.
scope.launch { probeOnce() }
}
}
emit(machine.health())
init {
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
scope.launch { reduceLoop() }
scope.launch {
connectivity.online.collect { up ->
intents.trySend(Intent.Link(up))
if (up) probeOnce()
}
}
scope.launch { pollLoop() }
}
private fun applyProbe(
resp: HealthzResponse?,
now: Long,
) {
if (resp == null) {
machine.onProbeFailure(now)
} else {
machine.onSuccess()
versionInternal.value = versionResultFor(resp)
}
}
/** A real server op verifiably succeeded — self-proving recovery. Cheap; safe on hot paths. */
fun reportSuccess() {
if (stateInternal.value != ServerHealth.Healthy) intents.trySend(Intent.OpSuccess)
}
private fun emit(next: ServerHealth) {
if (stateInternal.value != next) {
Timber.w("NetworkStatus -> %s", next)
stateInternal.value = next
}
}
/** A real network op failed — triggers /healthz arbitration. No-op when already Offline. */
fun reportFailure() {
if (stateInternal.value == ServerHealth.Offline) return
intents.trySend(Intent.OpFailure)
}
private suspend fun pollLoop() {
probeOnce()
while (true) {
val interval =
if (stateInternal.value == ServerHealth.Healthy) {
POLL_HEALTHY_MS
} else {
POLL_DEGRADED_MS
}
delay(interval)
probeOnce()
}
}
/** One-shot recheck for pull-to-refresh and the banner. */
fun recheck() {
scope.launch { probeOnce(force = true) }
}
private suspend fun probeOnce(force: Boolean = false) {
// Startup guard: don't poll the localhost placeholder before AuthStore
// hydrates the real base URL — that false failure would flash the banner.
if (authStore.baseUrl.value == AuthStore.DEFAULT_BASE_URL) return
/**
* App returned to the foreground — probe now rather than waiting for the
* poll loop.
*
* The link-return probe in `init` does NOT cover this: it fires on a
* connectivity *change*, and an app backgrounded on stable Wi-Fi sees none.
* force = true so this also bypasses the ARBITRATE_MIN_GAP_MS throttle —
* a user bringing the app up is exactly when a stale banner and a refused
* track are most visible, and it's a once-per-foreground cost.
*/
override fun onStart(owner: LifecycleOwner) {
recheck()
}
private suspend fun reduceLoop() {
for (intent in intents) {
val now = System.currentTimeMillis()
if (!force && now - lastProbeAtMs.get() < ARBITRATE_MIN_GAP_MS) return
lastProbeAtMs.set(now)
val resp = runCatching { api.check() }.getOrNull()
intents.trySend(Intent.Probe(resp))
}
private fun versionResultFor(resp: HealthzResponse): VersionResult {
val min = resp.minClientVersion
return when {
min.isEmpty() -> VersionResult.SKIPPED
isVersionNewer(min, BuildConfig.VERSION_NAME) -> VersionResult.TOO_OLD
else -> VersionResult.OK
when (intent) {
is Intent.Link -> machine.onLinkChange(intent.up)
is Intent.Probe -> applyProbe(intent.resp, now)
Intent.OpSuccess -> machine.onSuccess()
Intent.OpFailure -> {
machine.onOpFailure(now)
// Arbitrate off the reducer thread: awaiting a stalled
// /healthz here would block a concurrent self-proving
// success from snapping us straight back to Healthy.
scope.launch { probeOnce() }
}
}
emit(machine.health())
}
}
private fun applyProbe(resp: HealthzResponse?, now: Long) {
if (resp == null) {
machine.onProbeFailure(now)
} else {
machine.onSuccess()
versionInternal.value = versionResultFor(resp)
}
}
private fun emit(next: ServerHealth) {
if (stateInternal.value != next) {
Timber.w("NetworkStatus -> %s", next)
stateInternal.value = next
}
}
private suspend fun pollLoop() {
probeOnce()
while (true) {
val interval =
if (stateInternal.value == ServerHealth.Healthy) POLL_HEALTHY_MS
else POLL_DEGRADED_MS
delay(interval)
probeOnce()
}
}
private suspend fun probeOnce(force: Boolean = false) {
// Startup guard: don't poll the localhost placeholder before AuthStore
// hydrates the real base URL — that false failure would flash the banner.
if (authStore.baseUrl.value == AuthStore.DEFAULT_BASE_URL) return
val now = System.currentTimeMillis()
if (!force && now - lastProbeAtMs.get() < ARBITRATE_MIN_GAP_MS) return
lastProbeAtMs.set(now)
val resp = runCatching { api.check() }.getOrNull()
intents.trySend(Intent.Probe(resp))
}
private fun versionResultFor(resp: HealthzResponse): VersionResult {
val min = resp.minClientVersion
return when {
min.isEmpty() -> VersionResult.SKIPPED
isVersionNewer(min, BuildConfig.VERSION_NAME) -> VersionResult.TOO_OLD
else -> VersionResult.OK
}
}
}
/**
* Reactive [ServerHealth] snapshot provided once at the app root. Lets leaf
* composables (TrackRow gating, write-affordance disabling) branch on health
@@ -41,6 +41,7 @@ internal const val CORROBORATION_MIN_SPACING_MS = 3_000L
* sustained-time backstop.
*/
class ReachabilityMachine {
private enum class Reachability { Reachable, Unstable, Unreachable }
private var linkUp = true
@@ -88,13 +89,12 @@ class ReachabilityMachine {
}
}
fun health(): ServerHealth =
when {
!linkUp -> ServerHealth.Offline
reachability == Reachability.Reachable -> ServerHealth.Healthy
reachability == Reachability.Unstable -> ServerHealth.Unstable
else -> ServerHealth.ServerDown
}
fun health(): ServerHealth = when {
!linkUp -> ServerHealth.Offline
reachability == Reachability.Reachable -> ServerHealth.Healthy
reachability == Reachability.Unstable -> ServerHealth.Unstable
else -> ServerHealth.ServerDown
}
private fun shouldEscalate(nowMs: Long): Boolean {
val corroborated = recentOpFailures.size >= CORROBORATION_OP_THRESHOLD
@@ -29,23 +29,21 @@ private const val HEALTHZ_PATH = "/healthz"
* already constructed (construct-the-singleton trick in MinstrelApplication).
*/
@Singleton
class ReachabilityReportingInterceptor
@Inject
constructor(
private val networkStatus: Lazy<NetworkStatusController>,
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val isMinstrel = request.url.host == PLACEHOLDER_HOST
val isHealthz = request.url.encodedPath.endsWith(HEALTHZ_PATH)
if (!isMinstrel || isHealthz) return chain.proceed(request)
return try {
val response = chain.proceed(request)
if (response.isSuccessful) networkStatus.get().reportSuccess()
response
} catch (e: IOException) {
networkStatus.get().reportFailure()
throw e
}
class ReachabilityReportingInterceptor @Inject constructor(
private val networkStatus: Lazy<NetworkStatusController>,
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val isMinstrel = request.url.host == PLACEHOLDER_HOST
val isHealthz = request.url.encodedPath.endsWith(HEALTHZ_PATH)
if (!isMinstrel || isHealthz) return chain.proceed(request)
return try {
val response = chain.proceed(request)
if (response.isSuccessful) networkStatus.get().reportSuccess()
response
} catch (e: IOException) {
networkStatus.get().reportFailure()
throw e
}
}
}
@@ -19,10 +19,9 @@ import kotlinx.coroutines.flow.map
* heals itself the moment connectivity returns instead of sitting in the
* failed state until a manual pull-to-refresh.
*/
fun NetworkStatusController.recoveries(): Flow<Unit> =
state
.map { it == ServerHealth.Healthy }
.distinctUntilChanged()
.drop(1)
.filter { it }
.map { }
fun NetworkStatusController.recoveries(): Flow<Unit> = state
.map { it == ServerHealth.Healthy }
.distinctUntilChanged()
.drop(1)
.filter { it }
.map { }
@@ -43,14 +43,12 @@ private const val BACK_ONLINE_FLASH_MS = 2_000L
* re-wrapping StateFlow — the controller's is already app-scoped and warm.
*/
@HiltViewModel
class ConnectivityBannerViewModel
@Inject
constructor(
networkStatus: NetworkStatusController,
@Suppress("UnusedPrivateProperty") savedStateHandle: SavedStateHandle,
) : ViewModel() {
val health: StateFlow<ServerHealth> = networkStatus.state
}
class ConnectivityBannerViewModel @Inject constructor(
networkStatus: NetworkStatusController,
@Suppress("UnusedPrivateProperty") savedStateHandle: SavedStateHandle,
) : ViewModel() {
val health: StateFlow<ServerHealth> = networkStatus.state
}
/**
* Shell banner. Tells the user *why* they're degraded — no link vs server-down
@@ -59,7 +57,9 @@ class ConnectivityBannerViewModel
* recovery is unmistakable. Sentence case, understated voice (design system).
*/
@Composable
fun ConnectionErrorBanner(viewModel: ConnectivityBannerViewModel = hiltViewModel()) {
fun ConnectionErrorBanner(
viewModel: ConnectivityBannerViewModel = hiltViewModel(),
) {
val health by viewModel.health.collectAsStateWithLifecycle()
var showBackOnline by remember { mutableStateOf(false) }
var wasDown by remember { mutableStateOf(false) }
@@ -89,10 +89,7 @@ fun ConnectionErrorBanner(viewModel: ConnectivityBannerViewModel = hiltViewModel
}
@Composable
private fun BannerContent(
health: ServerHealth,
backOnline: Boolean,
) {
private fun BannerContent(health: ServerHealth, backOnline: Boolean) {
val scheme = MaterialTheme.colorScheme
val background: Color
val foreground: Color
@@ -111,11 +108,10 @@ private fun BannerContent(
}
}
Row(
modifier =
Modifier
.fillMaxWidth()
.background(background)
.padding(horizontal = 16.dp, vertical = 10.dp),
modifier = Modifier
.fillMaxWidth()
.background(background)
.padding(horizontal = 16.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
@@ -128,15 +124,11 @@ private fun BannerContent(
}
}
private fun bannerText(
health: ServerHealth,
backOnline: Boolean,
): String =
when {
backOnline -> "Back online."
health == ServerHealth.Offline -> "No connection — check Wi-Fi or mobile data."
health == ServerHealth.ServerDown ->
"Server unreachable — your cached content is still available."
health == ServerHealth.Unstable -> "Reconnecting…"
else -> ""
}
private fun bannerText(health: ServerHealth, backOnline: Boolean): String = when {
backOnline -> "Back online."
health == ServerHealth.Offline -> "No connection — check Wi-Fi or mobile data."
health == ServerHealth.ServerDown ->
"Server unreachable — your cached content is still available."
health == ServerHealth.Unstable -> "Reconnecting…"
else -> ""
}
@@ -20,12 +20,11 @@ annotation class ApplicationScope
object AppModule {
@Provides
@Singleton
fun provideJson(): Json =
Json {
ignoreUnknownKeys = true
explicitNulls = false
coerceInputValues = true
}
fun provideJson(): Json = Json {
ignoreUnknownKeys = true
explicitNulls = false
coerceInputValues = true
}
@Provides
@Singleton
@@ -5,9 +5,9 @@ import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.PowerManager
import androidx.core.content.ContextCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.core.content.ContextCompat
import androidx.lifecycle.ProcessLifecycleOwner
import com.fabledsword.minstrel.auth.AuthController
import com.fabledsword.minstrel.auth.AuthStore
@@ -52,388 +52,338 @@ import javax.inject.Singleton
*/
@Suppress("TooManyFunctions") // one collector + one (un)register pair per signal; cohesive
@Singleton
class DiagnosticsReporter
@Inject
constructor(
@ApplicationContext private val context: Context,
@ApplicationScope private val scope: CoroutineScope,
private val dao: DiagnosticEventDao,
private val authController: AuthController,
private val authStore: AuthStore,
private val connectivity: ConnectivityObserver,
private val networkStatus: NetworkStatusController,
private val playerController: PlayerController,
private val outputPicker: OutputPickerController,
private val remoteState: RemotePlayerState,
private val json: Json,
) {
@Volatile private var enabled = false
private var collectorJob: Job? = null
private var powerReceiver: BroadcastReceiver? = null
private var lifecycleObserver: DefaultLifecycleObserver? = null
class DiagnosticsReporter @Inject constructor(
@ApplicationContext private val context: Context,
@ApplicationScope private val scope: CoroutineScope,
private val dao: DiagnosticEventDao,
private val authController: AuthController,
private val authStore: AuthStore,
private val connectivity: ConnectivityObserver,
private val networkStatus: NetworkStatusController,
private val playerController: PlayerController,
private val outputPicker: OutputPickerController,
private val remoteState: RemotePlayerState,
private val json: Json,
) {
@Volatile private var enabled = false
private var collectorJob: Job? = null
private var powerReceiver: BroadcastReceiver? = null
private var lifecycleObserver: DefaultLifecycleObserver? = null
init {
// Gate = account flag (currentUser.debugModeEnabled) AND not the
// per-device local opt-out.
scope.launch {
combine(authController.currentUser, authStore.diagnosticsOptOut) { user, optOut ->
(user?.debugModeEnabled == true) && !optOut
}.distinctUntilChanged().collect { setEnabled(it) }
}
// Periodically re-pull /me so a remote admin flip propagates
// without a re-login or app restart.
scope.launch {
while (true) {
delay(GATE_REFRESH_MS)
authController.refreshProfile()
}
init {
// Gate = account flag (currentUser.debugModeEnabled) AND not the
// per-device local opt-out.
scope.launch {
combine(authController.currentUser, authStore.diagnosticsOptOut) { user, optOut ->
(user?.debugModeEnabled == true) && !optOut
}.distinctUntilChanged().collect { setEnabled(it) }
}
// Periodically re-pull /me so a remote admin flip propagates
// without a re-login or app restart.
scope.launch {
while (true) {
delay(GATE_REFRESH_MS)
authController.refreshProfile()
}
}
}
private fun setEnabled(value: Boolean) {
if (value == enabled) return
enabled = value
if (value) start() else stop()
private fun setEnabled(value: Boolean) {
if (value == enabled) return
enabled = value
if (value) start() else stop()
}
private fun start() {
registerPowerReceiver()
registerLifecycleObserver()
collectorJob = scope.launch {
record("lifecycle", buildJsonObject { put("event", "reporting_started") })
launch { collectConnectivity() }
launch { collectServerHealth() }
launch { collectUpnpDrops() }
launch { collectPlayerState() }
launch { collectTrackChanges() }
launch { collectTransportFlap() }
launch { collectRoutes() }
launch { heartbeatLoop() }
}
}
private fun start() {
registerPowerReceiver()
registerLifecycleObserver()
collectorJob =
scope.launch {
record("lifecycle", buildJsonObject { put("event", "reporting_started") })
launch { collectConnectivity() }
launch { collectServerHealth() }
launch { collectUpnpDrops() }
launch { collectPlayerState() }
launch { collectTrackChanges() }
launch { collectTransportFlap() }
launch { collectRoutes() }
launch { heartbeatLoop() }
}
private fun stop() {
collectorJob?.cancel()
collectorJob = null
unregisterPowerReceiver()
unregisterLifecycleObserver()
// Off means off: drop any unsent buffer (honors the user OFF
// intent and avoids leaking data captured before disable).
scope.launch { runCatching { dao.clear() } }
}
private suspend fun collectConnectivity() {
connectivity.online.distinctUntilChanged().collect { online ->
record("connectivity", buildJsonObject {
put("event", "online_changed")
put("online", online)
})
}
}
private fun stop() {
collectorJob?.cancel()
collectorJob = null
unregisterPowerReceiver()
unregisterLifecycleObserver()
// Off means off: drop any unsent buffer (honors the user OFF
// intent and avoids leaking data captured before disable).
scope.launch { runCatching { dao.clear() } }
private suspend fun collectServerHealth() {
// state is a StateFlow — already conflated/distinct, so no
// distinctUntilChanged (it's a deprecation warning = build error).
networkStatus.state.collect { s ->
record("connectivity", buildJsonObject {
put("event", "server_health")
put("state", s.name)
})
}
}
private suspend fun collectConnectivity() {
connectivity.online.distinctUntilChanged().collect { online ->
record(
"connectivity",
buildJsonObject {
put("event", "online_changed")
put("online", online)
},
)
private suspend fun collectUpnpDrops() {
playerController.dropEvents.collect { msg ->
record("upnp_sync", buildJsonObject {
put("event", "drop")
put("message", msg)
})
}
}
private suspend fun collectPlayerState() {
// 'playback', not 'upnp_sync' — player state applies to every output
// route (phone speaker, Bluetooth, UPnP), not just casting.
playerController.uiState
.map { Triple(it.currentSource, it.isUpnpLoading, it.playbackError) }
.distinctUntilChanged()
.collect { (source, upnpLoading, err) ->
record("playback", buildJsonObject {
put("event", "player_state")
put("source", source ?: "")
put("upnp_loading", upnpLoading)
if (err != null) put("error", err)
})
}
}
}
private suspend fun collectServerHealth() {
// state is a StateFlow — already conflated/distinct, so no
// distinctUntilChanged (it's a deprecation warning = build error).
networkStatus.state.collect { s ->
record(
"connectivity",
buildJsonObject {
put("event", "server_health")
put("state", s.name)
},
)
}
}
private suspend fun collectUpnpDrops() {
playerController.dropEvents.collect { msg ->
record(
"upnp_sync",
buildJsonObject {
put("event", "drop")
put("message", msg)
},
)
}
}
private suspend fun collectPlayerState() {
// 'playback', not 'upnp_sync' — player state applies to every output
// route (phone speaker, Bluetooth, UPnP), not just casting.
playerController.uiState
.map { Triple(it.currentSource, it.isUpnpLoading, it.playbackError) }
.distinctUntilChanged()
.collect { (source, upnpLoading, err) ->
record(
"playback",
buildJsonObject {
put("event", "player_state")
put("source", source ?: "")
put("upnp_loading", upnpLoading)
if (err != null) put("error", err)
},
)
}
}
// Emit a snapshot at each track/queue-index change — captures a
// skip-induced local↔Sonos desync at the INSTANT it happens, which the
// 45s heartbeat misses. Note: uiState is a conflated StateFlow, so a
// very rapid skip burst may coalesce intermediate indices (we still get
// the boundaries + the local-vs-Sonos snapshot).
private suspend fun collectTrackChanges() {
playerController.uiState
.map { it.queueIndex to it.currentTrack?.id }
.distinctUntilChanged()
.collect { (index, _) ->
val ui = playerController.uiState.value
val casting =
outputPicker.routesState.value.current.protocol !=
OutputRoute.Protocol.SYSTEM
record(
"playback",
buildJsonObject {
put("event", "track_change")
put("local_index", index)
// Track IDENTITY, not just index — indices wobble across
// re-casts, so the id + Sonos URI make a desync unambiguous.
put("local_track_id", ui.currentTrack?.id ?: "")
put("local_pos_ms", ui.positionMs)
putSonos(this, casting)
put("upnp_loading", ui.isUpnpLoading)
put("server_health", networkStatus.state.value.name)
put("route", outputPicker.routesState.value.current.name)
},
)
}
}
/**
* Catch the renderer rapidly leaving and re-entering PLAYING.
*
* The symptom: a Sonos rapidly play-pause-play-pausing, about every half
* second, usually as a track starts, cleared by a manual pause or skip.
* No other collector sees it: `player_state` carries
* source/loading/error but not playing, `track_change` needs the index
* to move, and the heartbeat samples once per 45s.
*
* Records every raw transport change (cheap — steady playback produces
* a couple per track) and, when they come in a burst, one summary event
* carrying the whole sequence. The summary is the useful artefact: it
* pairs the renderer's states with local-vs-Sonos track and position, so
* an episode says whether the app and the renderer disagreed about which
* track was playing, or agreed while the renderer rebuffered.
*
* See [TransportObservation] on the 1 Hz sampling limit.
*/
private suspend fun collectTransportFlap() {
val detector = TransportFlapDetector()
playerController.transportEvents.collect { obs ->
record(
"upnp_sync",
buildJsonObject {
put("event", "transport")
put("state", obs.state)
put("status_ok", obs.statusOk)
put("sonos_track", obs.trackNumber)
put("sonos_pos_ms", obs.positionMs)
put("play_intent", obs.playIntent)
},
)
detector.onChange(obs)?.let { recordFlapSummary(it) }
}
}
private suspend fun recordFlapSummary(recent: List<TransportObservation>) {
val ui = playerController.uiState.value
val casting =
outputPicker.routesState.value.current.protocol !=
// Emit a snapshot at each track/queue-index change — captures a
// skip-induced local↔Sonos desync at the INSTANT it happens, which the
// 45s heartbeat misses. Note: uiState is a conflated StateFlow, so a
// very rapid skip burst may coalesce intermediate indices (we still get
// the boundaries + the local-vs-Sonos snapshot).
private suspend fun collectTrackChanges() {
playerController.uiState
.map { it.queueIndex to it.currentTrack?.id }
.distinctUntilChanged()
.collect { (index, _) ->
val ui = playerController.uiState.value
val casting = outputPicker.routesState.value.current.protocol !=
OutputRoute.Protocol.SYSTEM
val spanMs = recent.last().atElapsedMs - recent.first().atElapsedMs
record(
"upnp_sync",
buildJsonObject {
put("event", "transport_flap")
put("changes", recent.size)
put("window_ms", spanMs)
// The sequence itself, e.g. "PLAYING>TRANSITIONING>STOPPED>PLAYING".
// Whether STOPPED appears at all is the first question to ask of a
// captured episode.
put("sequence", recent.joinToString(">") { it.state })
put("sonos_positions_ms", recent.joinToString(",") { it.positionMs.toString() })
put("sonos_tracks", recent.joinToString(",") { it.trackNumber.toString() })
put("local_index", ui.queueIndex)
record("playback", buildJsonObject {
put("event", "track_change")
put("local_index", index)
// Track IDENTITY, not just index — indices wobble across
// re-casts, so the id + Sonos URI make a desync unambiguous.
put("local_track_id", ui.currentTrack?.id ?: "")
put("local_pos_ms", ui.positionMs)
putSonos(this, casting)
put("upnp_loading", ui.isUpnpLoading)
put("server_health", networkStatus.state.value.name)
put("route", outputPicker.routesState.value.current.name)
addPowerFields(this)
},
)
}
private suspend fun collectRoutes() {
// 'playback' — route changes happen for all outputs. This only ever
// logs the ACTIVE route (routesState.current), so no "connected" flag.
outputPicker.routesState.map { it.current }.distinctUntilChanged().collect { r ->
record(
"playback",
buildJsonObject {
put("event", "route")
put("id", r.id)
put("name", r.name)
put("kind", r.kind.name)
put("protocol", r.protocol.name)
},
)
})
}
}
}
private suspend fun heartbeatLoop() {
while (true) {
delay(HEARTBEAT_MS)
val ui = playerController.uiState.value
val route = outputPicker.routesState.value.current
val routeActive = route.protocol != OutputRoute.Protocol.SYSTEM
// Idle = nothing worth sampling. Skip to keep the buffer lean.
if (!ui.isPlaying && !routeActive) continue
record(
"heartbeat",
buildJsonObject {
put("server_health", networkStatus.state.value.name)
put("is_playing", ui.isPlaying)
put("source", ui.currentSource ?: "")
put("local_index", ui.queueIndex)
put("local_track_id", ui.currentTrack?.id ?: "")
put("local_pos_ms", ui.positionMs)
put("route", route.name)
put("route_protocol", route.protocol.name)
putSonos(this, routeActive)
addPowerFields(this)
},
)
}
}
// --- power + lifecycle taps -------------------------------------------
private fun registerPowerReceiver() {
if (powerReceiver != null) return
val receiver =
object : BroadcastReceiver() {
override fun onReceive(
c: Context?,
intent: Intent?,
) {
val action = intent?.action ?: return
if (!enabled) return
scope.launch { record("power", powerEvent(action)) }
}
}
val filter =
IntentFilter().apply {
addAction(Intent.ACTION_SCREEN_ON)
addAction(Intent.ACTION_SCREEN_OFF)
addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED)
}
// System-protected broadcasts, but pass NOT_EXPORTED explicitly so
// the API 34+ registerReceiver flag requirement is satisfied.
ContextCompat.registerReceiver(
context,
receiver,
filter,
ContextCompat.RECEIVER_NOT_EXPORTED,
)
powerReceiver = receiver
}
private fun unregisterPowerReceiver() {
powerReceiver?.let { runCatching { context.unregisterReceiver(it) } }
powerReceiver = null
}
private fun registerLifecycleObserver() {
if (lifecycleObserver != null) return
val obs =
object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) = logLifecycle("app_foreground")
override fun onStop(owner: LifecycleOwner) = logLifecycle("app_background")
}
lifecycleObserver = obs
scope.launch(Dispatchers.Main) {
ProcessLifecycleOwner.get().lifecycle.addObserver(obs)
}
}
private fun unregisterLifecycleObserver() {
val obs = lifecycleObserver ?: return
lifecycleObserver = null
scope.launch(Dispatchers.Main) {
ProcessLifecycleOwner.get().lifecycle.removeObserver(obs)
}
}
private fun logLifecycle(event: String) {
if (!enabled) return
scope.launch { record("lifecycle", buildJsonObject { put("event", event) }) }
}
private fun powerEvent(action: String): JsonObject =
buildJsonObject {
put("event", action.substringAfterLast('.'))
addPowerFields(this)
}
// Sonos/UPnP remote-vs-local desync fields. Only meaningful while a
// remote route is active; zeroed otherwise so a stale RemotePlayerState
// from a just-ended cast can't masquerade as live Sonos data (the
// cast→phone handoff artifact). currentTrackUri is the desync ground
// truth — it carries the track the speaker is actually streaming.
private fun putSonos(
builder: kotlinx.serialization.json.JsonObjectBuilder,
casting: Boolean,
) {
builder.put("sonos_track", if (casting) remoteState.trackNumber else 0)
builder.put("sonos_pos_ms", if (casting) remoteState.positionMs else 0)
builder.put("sonos_playing", casting && remoteState.isPlaying)
if (casting) builder.put("sonos_uri", remoteState.currentTrackUri)
}
private fun addPowerFields(builder: kotlinx.serialization.json.JsonObjectBuilder) {
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
builder.put("doze", pm.isDeviceIdleMode)
builder.put("screen_on", pm.isInteractive)
builder.put("battery_opt_ignored", pm.isIgnoringBatteryOptimizations(context.packageName))
}
private suspend fun record(
kind: String,
payload: JsonObject,
) {
runCatching {
val id =
dao.insert(
DiagnosticEventEntity(
kind = kind,
occurredAtMillis = System.currentTimeMillis(),
payloadJson = json.encodeToString(JsonObject.serializer(), payload),
),
)
if (id % TRIM_INTERVAL == 0L) dao.trimToNewest(MAX_BUFFER)
}
}
private companion object {
const val HEARTBEAT_MS = 45_000L
const val GATE_REFRESH_MS = 300_000L // re-pull /me every 5 min
const val MAX_BUFFER = 5_000 // ring-buffer ceiling, oldest dropped
const val TRIM_INTERVAL = 50L // trim every N inserts, not every one
/**
* Catch the renderer rapidly leaving and re-entering PLAYING.
*
* The symptom: a Sonos rapidly play-pause-play-pausing, about every half
* second, usually as a track starts, cleared by a manual pause or skip.
* No other collector sees it: `player_state` carries
* source/loading/error but not playing, `track_change` needs the index
* to move, and the heartbeat samples once per 45s.
*
* Records every raw transport change (cheap — steady playback produces
* a couple per track) and, when they come in a burst, one summary event
* carrying the whole sequence. The summary is the useful artefact: it
* pairs the renderer's states with local-vs-Sonos track and position, so
* an episode says whether the app and the renderer disagreed about which
* track was playing, or agreed while the renderer rebuffered.
*
* See [TransportObservation] on the 1 Hz sampling limit.
*/
private suspend fun collectTransportFlap() {
val detector = TransportFlapDetector()
playerController.transportEvents.collect { obs ->
record("upnp_sync", buildJsonObject {
put("event", "transport")
put("state", obs.state)
put("status_ok", obs.statusOk)
put("sonos_track", obs.trackNumber)
put("sonos_pos_ms", obs.positionMs)
put("play_intent", obs.playIntent)
})
detector.onChange(obs)?.let { recordFlapSummary(it) }
}
}
private suspend fun recordFlapSummary(recent: List<TransportObservation>) {
val ui = playerController.uiState.value
val casting = outputPicker.routesState.value.current.protocol !=
OutputRoute.Protocol.SYSTEM
val spanMs = recent.last().atElapsedMs - recent.first().atElapsedMs
record("upnp_sync", buildJsonObject {
put("event", "transport_flap")
put("changes", recent.size)
put("window_ms", spanMs)
// The sequence itself, e.g. "PLAYING>TRANSITIONING>STOPPED>PLAYING".
// Whether STOPPED appears at all is the first question to ask of a
// captured episode.
put("sequence", recent.joinToString(">") { it.state })
put("sonos_positions_ms", recent.joinToString(",") { it.positionMs.toString() })
put("sonos_tracks", recent.joinToString(",") { it.trackNumber.toString() })
put("local_index", ui.queueIndex)
put("local_track_id", ui.currentTrack?.id ?: "")
put("local_pos_ms", ui.positionMs)
putSonos(this, casting)
put("upnp_loading", ui.isUpnpLoading)
put("server_health", networkStatus.state.value.name)
put("route", outputPicker.routesState.value.current.name)
addPowerFields(this)
})
}
private suspend fun collectRoutes() {
// 'playback' — route changes happen for all outputs. This only ever
// logs the ACTIVE route (routesState.current), so no "connected" flag.
outputPicker.routesState.map { it.current }.distinctUntilChanged().collect { r ->
record("playback", buildJsonObject {
put("event", "route")
put("id", r.id)
put("name", r.name)
put("kind", r.kind.name)
put("protocol", r.protocol.name)
})
}
}
private suspend fun heartbeatLoop() {
while (true) {
delay(HEARTBEAT_MS)
val ui = playerController.uiState.value
val route = outputPicker.routesState.value.current
val routeActive = route.protocol != OutputRoute.Protocol.SYSTEM
// Idle = nothing worth sampling. Skip to keep the buffer lean.
if (!ui.isPlaying && !routeActive) continue
record("heartbeat", buildJsonObject {
put("server_health", networkStatus.state.value.name)
put("is_playing", ui.isPlaying)
put("source", ui.currentSource ?: "")
put("local_index", ui.queueIndex)
put("local_track_id", ui.currentTrack?.id ?: "")
put("local_pos_ms", ui.positionMs)
put("route", route.name)
put("route_protocol", route.protocol.name)
putSonos(this, routeActive)
addPowerFields(this)
})
}
}
// --- power + lifecycle taps -------------------------------------------
private fun registerPowerReceiver() {
if (powerReceiver != null) return
val receiver = object : BroadcastReceiver() {
override fun onReceive(c: Context?, intent: Intent?) {
val action = intent?.action ?: return
if (!enabled) return
scope.launch { record("power", powerEvent(action)) }
}
}
val filter = IntentFilter().apply {
addAction(Intent.ACTION_SCREEN_ON)
addAction(Intent.ACTION_SCREEN_OFF)
addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED)
}
// System-protected broadcasts, but pass NOT_EXPORTED explicitly so
// the API 34+ registerReceiver flag requirement is satisfied.
ContextCompat.registerReceiver(
context, receiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED,
)
powerReceiver = receiver
}
private fun unregisterPowerReceiver() {
powerReceiver?.let { runCatching { context.unregisterReceiver(it) } }
powerReceiver = null
}
private fun registerLifecycleObserver() {
if (lifecycleObserver != null) return
val obs = object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) = logLifecycle("app_foreground")
override fun onStop(owner: LifecycleOwner) = logLifecycle("app_background")
}
lifecycleObserver = obs
scope.launch(Dispatchers.Main) {
ProcessLifecycleOwner.get().lifecycle.addObserver(obs)
}
}
private fun unregisterLifecycleObserver() {
val obs = lifecycleObserver ?: return
lifecycleObserver = null
scope.launch(Dispatchers.Main) {
ProcessLifecycleOwner.get().lifecycle.removeObserver(obs)
}
}
private fun logLifecycle(event: String) {
if (!enabled) return
scope.launch { record("lifecycle", buildJsonObject { put("event", event) }) }
}
private fun powerEvent(action: String): JsonObject = buildJsonObject {
put("event", action.substringAfterLast('.'))
addPowerFields(this)
}
// Sonos/UPnP remote-vs-local desync fields. Only meaningful while a
// remote route is active; zeroed otherwise so a stale RemotePlayerState
// from a just-ended cast can't masquerade as live Sonos data (the
// cast→phone handoff artifact). currentTrackUri is the desync ground
// truth — it carries the track the speaker is actually streaming.
private fun putSonos(builder: kotlinx.serialization.json.JsonObjectBuilder, casting: Boolean) {
builder.put("sonos_track", if (casting) remoteState.trackNumber else 0)
builder.put("sonos_pos_ms", if (casting) remoteState.positionMs else 0)
builder.put("sonos_playing", casting && remoteState.isPlaying)
if (casting) builder.put("sonos_uri", remoteState.currentTrackUri)
}
private fun addPowerFields(builder: kotlinx.serialization.json.JsonObjectBuilder) {
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
builder.put("doze", pm.isDeviceIdleMode)
builder.put("screen_on", pm.isInteractive)
builder.put("battery_opt_ignored", pm.isIgnoringBatteryOptimizations(context.packageName))
}
private suspend fun record(kind: String, payload: JsonObject) {
runCatching {
val id = dao.insert(
DiagnosticEventEntity(
kind = kind,
occurredAtMillis = System.currentTimeMillis(),
payloadJson = json.encodeToString(JsonObject.serializer(), payload),
),
)
if (id % TRIM_INTERVAL == 0L) dao.trimToNewest(MAX_BUFFER)
}
}
private companion object {
const val HEARTBEAT_MS = 45_000L
const val GATE_REFRESH_MS = 300_000L // re-pull /me every 5 min
const val MAX_BUFFER = 5_000 // ring-buffer ceiling, oldest dropped
const val TRIM_INTERVAL = 50L // trim every N inserts, not every one
}
}
@@ -38,93 +38,84 @@ import javax.inject.Singleton
* uploader treats as success so the buffer drains either way.
*/
@Singleton
class DiagnosticsUploader
@Inject
constructor(
private val dao: DiagnosticEventDao,
private val authStore: AuthStore,
private val json: Json,
@ApplicationScope private val scope: CoroutineScope,
networkStatus: NetworkStatusController,
retrofit: Retrofit,
) {
private val api: DiagnosticsApi = retrofit.create()
private val mutex = Mutex()
class DiagnosticsUploader @Inject constructor(
private val dao: DiagnosticEventDao,
private val authStore: AuthStore,
private val json: Json,
@ApplicationScope private val scope: CoroutineScope,
networkStatus: NetworkStatusController,
retrofit: Retrofit,
) {
private val api: DiagnosticsApi = retrofit.create()
private val mutex = Mutex()
init {
scope.launch {
while (true) {
delay(UPLOAD_INTERVAL_MS)
drainSafe()
}
}
scope.launch {
authStore.sessionCookie
.filterNotNull()
.distinctUntilChanged()
.collect { drainSafe() }
}
scope.launch {
networkStatus.state
.map { it == ServerHealth.Healthy }
.distinctUntilChanged()
.filter { it }
.collect { drainSafe() }
init {
scope.launch {
while (true) {
delay(UPLOAD_INTERVAL_MS)
drainSafe()
}
}
/** Coalesces concurrent triggers via tryLock — a drain in flight wins. */
private suspend fun drainSafe() {
// A trigger at launch can fire before the stored login has loaded;
// wait for it, so a signed-in user is not read as signed out.
authStore.awaitSessionHydrated()
val clientId = authStore.clientId.value
// Signed out / no client id yet → nothing to do. Single guard keeps
// the return count within the detekt gate.
if (authStore.sessionCookie.value.isNullOrEmpty() || clientId == null) return
if (!mutex.tryLock()) return
try {
drain(clientId)
} finally {
mutex.unlock()
}
scope.launch {
authStore.sessionCookie.filterNotNull().distinctUntilChanged().collect { drainSafe() }
}
private suspend fun drain(clientId: String) {
var more = true
while (more) {
val batch = runCatching { dao.takeBatch(BATCH_SIZE) }.getOrNull().orEmpty()
val sent = batch.isNotEmpty() && runCatching { upload(clientId, batch) }.isSuccess
if (sent) runCatching { dao.deleteByIds(batch.map { it.id }) }
// Keep going only while a full batch sent cleanly; otherwise stop
// (empty buffer, or a failure to retry on the next trigger).
more = sent && batch.size >= BATCH_SIZE
}
}
private suspend fun upload(
clientId: String,
batch: List<DiagnosticEventEntity>,
) {
api.report(
DiagnosticsReportRequest(
clientId = clientId,
appVersion = BuildConfig.VERSION_NAME,
osVersion = "Android ${Build.VERSION.RELEASE} (${Build.MODEL})",
events =
batch.map { row ->
DiagnosticEventWire(
kind = row.kind,
occurredAt = row.occurredAtMillis,
payload = json.parseToJsonElement(row.payloadJson),
)
},
),
)
}
private companion object {
const val UPLOAD_INTERVAL_MS = 60_000L
const val BATCH_SIZE = 100
scope.launch {
networkStatus.state
.map { it == ServerHealth.Healthy }
.distinctUntilChanged()
.filter { it }
.collect { drainSafe() }
}
}
/** Coalesces concurrent triggers via tryLock — a drain in flight wins. */
private suspend fun drainSafe() {
// A trigger at launch can fire before the stored login has loaded;
// wait for it, so a signed-in user is not read as signed out.
authStore.awaitSessionHydrated()
val clientId = authStore.clientId.value
// Signed out / no client id yet → nothing to do. Single guard keeps
// the return count within the detekt gate.
if (authStore.sessionCookie.value.isNullOrEmpty() || clientId == null) return
if (!mutex.tryLock()) return
try {
drain(clientId)
} finally {
mutex.unlock()
}
}
private suspend fun drain(clientId: String) {
var more = true
while (more) {
val batch = runCatching { dao.takeBatch(BATCH_SIZE) }.getOrNull().orEmpty()
val sent = batch.isNotEmpty() && runCatching { upload(clientId, batch) }.isSuccess
if (sent) runCatching { dao.deleteByIds(batch.map { it.id }) }
// Keep going only while a full batch sent cleanly; otherwise stop
// (empty buffer, or a failure to retry on the next trigger).
more = sent && batch.size >= BATCH_SIZE
}
}
private suspend fun upload(clientId: String, batch: List<DiagnosticEventEntity>) {
api.report(
DiagnosticsReportRequest(
clientId = clientId,
appVersion = BuildConfig.VERSION_NAME,
osVersion = "Android ${Build.VERSION.RELEASE} (${Build.MODEL})",
events = batch.map { row ->
DiagnosticEventWire(
kind = row.kind,
occurredAt = row.occurredAtMillis,
payload = json.parseToJsonElement(row.payloadJson),
)
},
),
)
}
private companion object {
const val UPLOAD_INTERVAL_MS = 60_000L
const val BATCH_SIZE = 100
}
}
@@ -63,171 +63,157 @@ private const val EVENTS_BUFFER_CAPACITY = 64
* needing a separate path through here.
*/
@Singleton
class EventsStream
@Inject
constructor(
private val authStore: AuthStore,
@ApplicationScope private val scope: CoroutineScope,
private val okHttpClient: OkHttpClient,
private val json: Json,
private val connectivity: ConnectivityObserver,
) {
private val factory = EventSources.createFactory(okHttpClient)
class EventsStream @Inject constructor(
private val authStore: AuthStore,
@ApplicationScope private val scope: CoroutineScope,
private val okHttpClient: OkHttpClient,
private val json: Json,
private val connectivity: ConnectivityObserver,
) {
private val factory = EventSources.createFactory(okHttpClient)
private val emitter =
MutableSharedFlow<LiveEvent>(
replay = 0,
extraBufferCapacity = EVENTS_BUFFER_CAPACITY,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
val events: SharedFlow<LiveEvent> = emitter.asSharedFlow()
private val emitter = MutableSharedFlow<LiveEvent>(
replay = 0,
extraBufferCapacity = EVENTS_BUFFER_CAPACITY,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
val events: SharedFlow<LiveEvent> = emitter.asSharedFlow()
private val connectedState = MutableStateFlow(false)
val connected: StateFlow<Boolean> = connectedState.asStateFlow()
private val connectedState = MutableStateFlow(false)
val connected: StateFlow<Boolean> = connectedState.asStateFlow()
private var currentSource: EventSource? = null
private var currentSource: EventSource? = null
@Volatile private var signedIn = false
private var reconnectJob: Job? = null
private var backoffMs = ReconnectBackoff.BASE_MS
@Volatile private var signedIn = false
private var reconnectJob: Job? = null
private var backoffMs = ReconnectBackoff.BASE_MS
init {
scope.launch {
authStore.sessionCookie
.map { !it.isNullOrEmpty() }
.distinctUntilChanged()
.collect { isSignedIn ->
signedIn = isSignedIn
if (isSignedIn) {
backoffMs = ReconnectBackoff.BASE_MS
connect()
} else {
disconnect()
}
init {
scope.launch {
authStore.sessionCookie
.map { !it.isNullOrEmpty() }
.distinctUntilChanged()
.collect { isSignedIn ->
signedIn = isSignedIn
if (isSignedIn) {
backoffMs = ReconnectBackoff.BASE_MS
connect()
} else {
disconnect()
}
}
scope.launch {
connectivity.online.collect { up -> if (up) reconnectNow() }
}
}
/**
* Cuts a pending backoff short: reconnects at once and starts the ladder
* over. For a network that has just come up, or the app coming to the
* foreground, where waiting out a five-minute backoff would leave the
* server unheard from for nothing. Does nothing while a stream is open or
* opening.
*/
@Synchronized
fun reconnectNow() {
if (!signedIn || reconnectJob?.isActive != true) return
backoffMs = ReconnectBackoff.BASE_MS
connect()
}
@Synchronized
private fun connect() {
reconnectJob?.cancel()
currentSource?.cancel()
currentSource = openSubscription()
}
@Synchronized
private fun disconnect() {
reconnectJob?.cancel()
currentSource?.cancel()
currentSource = null
connectedState.value = false
}
/**
* Schedule a reconnect after the current backoff, jittered, then
* double it (capped). No-op when signed out — sign-out's [disconnect]
* cancels the pending job. A successful [Listener.onOpen] resets
* the backoff to the floor.
*/
@Synchronized
private fun scheduleReconnect() {
connectedState.value = false
if (!signedIn) return
reconnectJob?.cancel()
val waitMs = ReconnectBackoff.jittered(backoffMs)
backoffMs = ReconnectBackoff.next(backoffMs)
reconnectJob =
scope.launch {
delay(waitMs)
if (signedIn) connect()
}
}
private fun openSubscription(): EventSource {
val request =
Request
.Builder()
.url("http://placeholder.invalid$SSE_PATH")
.header("Accept", "text/event-stream")
.build()
return factory.newEventSource(request, Listener())
scope.launch {
connectivity.online.collect { up -> if (up) reconnectNow() }
}
private inner class Listener : EventSourceListener() {
override fun onOpen(
eventSource: EventSource,
response: Response,
) {
backoffMs = ReconnectBackoff.BASE_MS
connectedState.value = true
}
override fun onEvent(
eventSource: EventSource,
id: String?,
type: String?,
data: String,
) {
parseFrame(kind = type, data = data)?.let(emitter::tryEmit)
}
override fun onClosed(eventSource: EventSource) {
scheduleReconnect()
}
override fun onFailure(
eventSource: EventSource,
t: Throwable?,
response: Response?,
) {
scheduleReconnect()
}
}
/**
* Parses one SSE frame into a [LiveEvent]. The SSE `event:` field
* carries the kind; the `data:` field is a JSON object with
* `kind`/`user_id`/`data` (the kind in the payload is redundant
* with the SSE event field — we prefer the SSE field, falling
* back to the payload field). Heartbeat comment frames don't
* reach here (okhttp-sse filters them).
*/
private fun parseFrame(
kind: String?,
data: String,
): LiveEvent? =
try {
val payload = json.parseToJsonElement(data).jsonObject
val resolvedKind = kind ?: payload["kind"]?.jsonPrimitive?.contentOrNull
if (resolvedKind.isNullOrEmpty()) {
null
} else {
LiveEvent(
kind = resolvedKind,
userId = payload["user_id"]?.jsonPrimitive?.contentOrNull.orEmpty(),
data = (payload["data"] as? JsonObject) ?: JsonObject(emptyMap()),
)
}
} catch (
@Suppress("TooGenericExceptionCaught") _: Throwable,
) {
null
}
}
/**
* Cuts a pending backoff short: reconnects at once and starts the ladder
* over. For a network that has just come up, or the app coming to the
* foreground, where waiting out a five-minute backoff would leave the
* server unheard from for nothing. Does nothing while a stream is open or
* opening.
*/
@Synchronized
fun reconnectNow() {
if (!signedIn || reconnectJob?.isActive != true) return
backoffMs = ReconnectBackoff.BASE_MS
connect()
}
@Synchronized
private fun connect() {
reconnectJob?.cancel()
currentSource?.cancel()
currentSource = openSubscription()
}
@Synchronized
private fun disconnect() {
reconnectJob?.cancel()
currentSource?.cancel()
currentSource = null
connectedState.value = false
}
/**
* Schedule a reconnect after the current backoff, jittered, then
* double it (capped). No-op when signed out — sign-out's [disconnect]
* cancels the pending job. A successful [Listener.onOpen] resets
* the backoff to the floor.
*/
@Synchronized
private fun scheduleReconnect() {
connectedState.value = false
if (!signedIn) return
reconnectJob?.cancel()
val waitMs = ReconnectBackoff.jittered(backoffMs)
backoffMs = ReconnectBackoff.next(backoffMs)
reconnectJob = scope.launch {
delay(waitMs)
if (signedIn) connect()
}
}
private fun openSubscription(): EventSource {
val request = Request.Builder()
.url("http://placeholder.invalid$SSE_PATH")
.header("Accept", "text/event-stream")
.build()
return factory.newEventSource(request, Listener())
}
private inner class Listener : EventSourceListener() {
override fun onOpen(eventSource: EventSource, response: Response) {
backoffMs = ReconnectBackoff.BASE_MS
connectedState.value = true
}
override fun onEvent(
eventSource: EventSource,
id: String?,
type: String?,
data: String,
) {
parseFrame(kind = type, data = data)?.let(emitter::tryEmit)
}
override fun onClosed(eventSource: EventSource) {
scheduleReconnect()
}
override fun onFailure(
eventSource: EventSource,
t: Throwable?,
response: Response?,
) {
scheduleReconnect()
}
}
/**
* Parses one SSE frame into a [LiveEvent]. The SSE `event:` field
* carries the kind; the `data:` field is a JSON object with
* `kind`/`user_id`/`data` (the kind in the payload is redundant
* with the SSE event field — we prefer the SSE field, falling
* back to the payload field). Heartbeat comment frames don't
* reach here (okhttp-sse filters them).
*/
private fun parseFrame(kind: String?, data: String): LiveEvent? = try {
val payload = json.parseToJsonElement(data).jsonObject
val resolvedKind = kind ?: payload["kind"]?.jsonPrimitive?.contentOrNull
if (resolvedKind.isNullOrEmpty()) {
null
} else {
LiveEvent(
kind = resolvedKind,
userId = payload["user_id"]?.jsonPrimitive?.contentOrNull.orEmpty(),
data = (payload["data"] as? JsonObject) ?: JsonObject(emptyMap()),
)
}
} catch (
@Suppress("TooGenericExceptionCaught") _: Throwable,
) {
null
}
}
@@ -28,58 +28,57 @@ import javax.inject.Singleton
* stream reconnects and the re-refresh avoids stale data flashing.
*/
@Singleton
class LiveEventsDispatcher
@Inject
constructor(
private val eventsStream: EventsStream,
private val likes: LikesRepository,
private val notifications: NotificationsRepository,
@ApplicationScope private val scope: CoroutineScope,
) : DefaultLifecycleObserver {
init {
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
scope.launch {
eventsStream.events.collect { e -> handle(e) }
}
}
class LiveEventsDispatcher @Inject constructor(
private val eventsStream: EventsStream,
private val likes: LikesRepository,
private val notifications: NotificationsRepository,
@ApplicationScope private val scope: CoroutineScope,
) : DefaultLifecycleObserver {
private fun handle(event: LiveEvent) {
when (event.kind) {
"track.liked",
"track.unliked",
"album.liked",
"album.unliked",
"artist.liked",
"artist.unliked",
-> refreshLikes()
// a contentless nudge; the inbox refetches its newest page.
"notification.created" -> refreshNotifications()
}
// Other kinds (playlist.*, quarantine.*, request.status_changed,
// scan.*) reach screen-scoped subscribers via EventsStream
// directly. Add cross-screen cases here only when a new
// Repository-level refresh becomes available.
}
override fun onStart(owner: LifecycleOwner) {
// App returned to the foreground. SSE will catch up but might
// not have reconnected yet (it may be deep in its backoff, so it
// is told to try now); flush the cross-screen refreshes
// defensively.
eventsStream.reconnectNow()
refreshLikes()
refreshNotifications()
}
private fun refreshNotifications() {
scope.launch {
runCatching { notifications.refresh() }
}
}
private fun refreshLikes() {
scope.launch {
runCatching { likes.refreshIds() }
}
init {
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
scope.launch {
eventsStream.events.collect { e -> handle(e) }
}
}
private fun handle(event: LiveEvent) {
when (event.kind) {
"track.liked",
"track.unliked",
"album.liked",
"album.unliked",
"artist.liked",
"artist.unliked",
-> refreshLikes()
// a contentless nudge; the inbox refetches its newest page.
"notification.created" -> refreshNotifications()
}
// Other kinds (playlist.*, quarantine.*, request.status_changed,
// scan.*) reach screen-scoped subscribers via EventsStream
// directly. Add cross-screen cases here only when a new
// Repository-level refresh becomes available.
}
override fun onStart(owner: LifecycleOwner) {
// App returned to the foreground. SSE will catch up but might
// not have reconnected yet (it may be deep in its backoff, so it
// is told to try now); flush the cross-screen refreshes
// defensively.
eventsStream.reconnectNow()
refreshLikes()
refreshNotifications()
}
private fun refreshNotifications() {
scope.launch {
runCatching { notifications.refresh() }
}
}
private fun refreshLikes() {
scope.launch {
runCatching { likes.refreshIds() }
}
}
}
@@ -24,10 +24,7 @@ internal object ReconnectBackoff {
fun next(currentMs: Long): Long = (currentMs * 2).coerceAtMost(MAX_MS)
/** [ms] moved by up to a quarter either way. */
fun jittered(
ms: Long,
random: Random = Random.Default,
): Long {
fun jittered(ms: Long, random: Random = Random.Default): Long {
val spread = ms * JITTER
return (ms + random.nextDouble(-spread, spread)).toLong()
}
@@ -49,33 +49,29 @@ data class HistoryPage(
* ordering/paging bookkeeping for no UX gain.
*/
@Singleton
class HistoryRepository
@Inject
constructor(
private val snapshotDao: CachedHistorySnapshotDao,
private val json: Json,
retrofit: Retrofit,
) {
private val api: HistoryApi = retrofit.create()
class HistoryRepository @Inject constructor(
private val snapshotDao: CachedHistorySnapshotDao,
private val json: Json,
retrofit: Retrofit,
) {
private val api: HistoryApi = retrofit.create()
fun observeHistory(): Flow<HistoryPage?> =
snapshotDao.observe().map { row ->
row?.let { json.decodeFromString<HistoryPageWire>(it.json).toDomain() }
}
/** Fetch the latest history and overwrite the cached snapshot. */
suspend fun refresh() {
val wire = api.getHistory()
val blob = json.encodeToString(HistoryPageWire.serializer(), wire)
snapshotDao.upsert(CachedHistorySnapshotEntity(json = blob))
fun observeHistory(): Flow<HistoryPage?> =
snapshotDao.observe().map { row ->
row?.let { json.decodeFromString<HistoryPageWire>(it.json).toDomain() }
}
}
private fun HistoryPageWire.toDomain(): HistoryPage =
HistoryPage(
entries =
events.map {
HistoryEntry(id = it.id, playedAt = it.playedAt, track = it.track.toDomain())
},
hasMore = hasMore,
)
/** Fetch the latest history and overwrite the cached snapshot. */
suspend fun refresh() {
val wire = api.getHistory()
val blob = json.encodeToString(HistoryPageWire.serializer(), wire)
snapshotDao.upsert(CachedHistorySnapshotEntity(json = blob))
}
}
private fun HistoryPageWire.toDomain(): HistoryPage = HistoryPage(
entries = events.map {
HistoryEntry(id = it.id, playedAt = it.playedAt, track = it.track.toDomain())
},
hasMore = hasMore,
)
@@ -1,7 +1,10 @@
package com.fabledsword.minstrel.history.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.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.HorizontalDivider
@@ -23,12 +26,12 @@ import com.fabledsword.minstrel.history.data.HistoryRepository
import com.fabledsword.minstrel.models.TrackRef
import com.fabledsword.minstrel.player.PlayerController
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.widgets.TrackRow
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.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.TrackCoverThumb
import com.fabledsword.minstrel.shared.widgets.TrackRow
import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
@@ -53,58 +56,56 @@ private const val SHARE_STOP_TIMEOUT_MS = 5_000L
// ─── ViewModel ───────────────────────────────────────────────────────
@HiltViewModel
class HistoryTabViewModel
@Inject
constructor(
private val repository: HistoryRepository,
private val player: PlayerController,
networkStatus: NetworkStatusController,
) : ViewModel() {
private val refreshError = MutableStateFlow<String?>(null)
class HistoryTabViewModel @Inject constructor(
private val repository: HistoryRepository,
private val player: PlayerController,
networkStatus: NetworkStatusController,
) : ViewModel() {
/**
* Cache-first: emits the cached snapshot instantly (paints from
* disk on cold open), then SWR-refreshes underneath. Shows Error
* only when there's nothing cached AND the refresh failed — a
* failed refresh over a populated cache stays silent.
*/
val uiState: StateFlow<UiState<List<HistoryEntry>>> =
combine(repository.observeHistory(), refreshError) { page, err ->
when {
page != null && page.entries.isNotEmpty() -> UiState.Success(page.entries)
page != null -> UiState.Empty
err != null -> UiState.Error(err)
else -> UiState.Loading
}
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
initialValue = UiState.Loading,
)
private val refreshError = MutableStateFlow<String?>(null)
init {
refresh()
// Screen-level auto-recovery: re-pull when server
// health returns, so a load that failed offline heals unprompted.
viewModelScope.launch {
networkStatus.recoveries().collect { refresh() }
/**
* Cache-first: emits the cached snapshot instantly (paints from
* disk on cold open), then SWR-refreshes underneath. Shows Error
* only when there's nothing cached AND the refresh failed — a
* failed refresh over a populated cache stays silent.
*/
val uiState: StateFlow<UiState<List<HistoryEntry>>> =
combine(repository.observeHistory(), refreshError) { page, err ->
when {
page != null && page.entries.isNotEmpty() -> UiState.Success(page.entries)
page != null -> UiState.Empty
err != null -> UiState.Error(err)
else -> UiState.Loading
}
}
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
initialValue = UiState.Loading,
)
fun refresh(): Job =
viewModelScope.launch {
refreshError.value = null
runCatching { repository.refresh() }
.onFailure { refreshError.value = ErrorCopy.fromThrowable(it) }
}
/** Plays the tapped track on its own. */
fun playTrack(track: TrackRef) {
if (track.streamUrl.isEmpty()) return
player.setQueue(listOf(track), initialIndex = 0, source = "history")
init {
refresh()
// Screen-level auto-recovery: re-pull when server
// health returns, so a load that failed offline heals unprompted.
viewModelScope.launch {
networkStatus.recoveries().collect { refresh() }
}
}
fun refresh(): Job = viewModelScope.launch {
refreshError.value = null
runCatching { repository.refresh() }
.onFailure { refreshError.value = ErrorCopy.fromThrowable(it) }
}
/** Plays the tapped track on its own. */
fun playTrack(track: TrackRef) {
if (track.streamUrl.isEmpty()) return
player.setQueue(listOf(track), initialIndex = 0, source = "history")
}
}
// ─── Composable ──────────────────────────────────────────────────────
@Composable
@@ -120,25 +121,22 @@ fun HistoryTab(
PullToRefreshScaffold(onRefresh = { viewModel.refresh().join() }) {
when (val s = state) {
UiState.Loading -> LoadingCentered()
UiState.Empty ->
EmptyState(
title = "No listening history yet",
body = "Play something — your recent plays will show up here.",
)
is UiState.Error ->
ErrorRetry(
title = "Couldn't load history",
message = s.message,
onRetry = { viewModel.refresh() },
)
is UiState.Success ->
HistoryList(
entries = s.data,
playingTrackId = playingTrackId,
onPlay = viewModel::playTrack,
onNavigateToAlbum = onNavigateToAlbum,
onNavigateToArtist = onNavigateToArtist,
)
UiState.Empty -> EmptyState(
title = "No listening history yet",
body = "Play something — your recent plays will show up here.",
)
is UiState.Error -> ErrorRetry(
title = "Couldn't load history",
message = s.message,
onRetry = { viewModel.refresh() },
)
is UiState.Success -> HistoryList(
entries = s.data,
playingTrackId = playingTrackId,
onPlay = viewModel::playTrack,
onNavigateToAlbum = onNavigateToAlbum,
onNavigateToArtist = onNavigateToArtist,
)
}
}
}
@@ -217,9 +215,8 @@ private const val DAYS_PER_WEEK = 7L
* up the row over malformed timestamps.
*/
private fun relativeTime(iso: String): String {
val parsed =
runCatching { OffsetDateTime.parse(iso) }.getOrNull()
?: return iso
val parsed = runCatching { OffsetDateTime.parse(iso) }.getOrNull()
?: return iso
val local = parsed.atZoneSameInstant(ZoneId.systemDefault())
val now = OffsetDateTime.now(ZoneId.systemDefault())
val minutes = ChronoUnit.MINUTES.between(local, now)
@@ -44,167 +44,163 @@ import javax.inject.Singleton
// Per-section observe accessors (one per Home row) inflate the function
// count past detekt's 11 default — accessor density, not complexity.
@Suppress("TooManyFunctions")
class HomeRepository
@Inject
constructor(
private val homeIndexDao: CachedHomeIndexDao,
private val metadataProvider: MetadataProvider,
private val prewarmer: HomeArtistPrewarmer,
retrofit: Retrofit,
) {
private val api: HomeApi = retrofit.create()
private val meApi: MeApi = retrofit.create()
class HomeRepository @Inject constructor(
private val homeIndexDao: CachedHomeIndexDao,
private val metadataProvider: MetadataProvider,
private val prewarmer: HomeArtistPrewarmer,
retrofit: Retrofit,
) {
private val api: HomeApi = retrofit.create()
private val meApi: MeApi = retrofit.create()
/**
* Caller's system-playlist build state for the Home placeholder
* cards. One-shot GET; the caller refreshes alongside the index.
*/
suspend fun getSystemPlaylistsStatus(): SystemPlaylistsStatus =
meApi.getSystemPlaylistsStatus().let {
SystemPlaylistsStatus(
inFlight = it.inFlight,
lastRunAt = it.lastRunAt,
lastError = it.lastError,
)
}
fun observeRecentlyAddedAlbums(): Flow<List<HomeTile<AlbumRef>>> =
observeAlbumSection(SECTION_RECENTLY_ADDED_ALBUMS)
fun observeRediscoverAlbums(): Flow<List<HomeTile<AlbumRef>>> = observeAlbumSection(SECTION_REDISCOVER_ALBUMS)
fun observeRediscoverArtists(): Flow<List<HomeTile<ArtistRef>>> =
observeArtistSection(SECTION_REDISCOVER_ARTISTS)
fun observeMostPlayedTracks(): Flow<List<HomeTile<TrackRef>>> = observeTrackSection(SECTION_MOST_PLAYED_TRACKS)
fun observeLastPlayedArtists(): Flow<List<HomeTile<ArtistRef>>> =
observeArtistSection(SECTION_LAST_PLAYED_ARTISTS)
fun observeYouMightLikeAlbums(): Flow<List<HomeTile<AlbumRef>>> =
observeAlbumSection(SECTION_YOU_MIGHT_LIKE_ALBUMS)
fun observeYouMightLikeArtists(): Flow<List<HomeTile<ArtistRef>>> =
observeArtistSection(SECTION_YOU_MIGHT_LIKE_ARTISTS)
/** True when the index cache already has content on screen to protect. */
suspend fun hasCachedIndex(): Boolean = homeIndexDao.hasAny()
/**
* Pulls /api/home/index and swaps every cached_home_index section in
* a single transaction, then pre-warms the top artists. Missing
* entity rows hydrate via the on-miss path.
*
* One transaction for all seven sections is deliberate: Room notifies
* observers once, on commit, so Home swaps from the old content to
* the new in a single emission. Per-section, un-transacted writes
* would make every row visibly collapse to empty and refill, one
* after another.
*/
suspend fun refreshIndex() {
val wire = api.getHomeIndex()
homeIndexDao.replaceSections(
sections = ALL_SECTIONS,
rows =
rowsFor(SECTION_RECENTLY_ADDED_ALBUMS, "album", wire.recentlyAddedAlbums) +
rowsFor(SECTION_REDISCOVER_ALBUMS, "album", wire.rediscoverAlbums) +
rowsFor(SECTION_REDISCOVER_ARTISTS, "artist", wire.rediscoverArtists) +
rowsFor(SECTION_MOST_PLAYED_TRACKS, "track", wire.mostPlayedTracks) +
rowsFor(SECTION_LAST_PLAYED_ARTISTS, "artist", wire.lastPlayedArtists) +
rowsFor(SECTION_YOU_MIGHT_LIKE_ALBUMS, "album", wire.youMightLikeAlbums) +
rowsFor(SECTION_YOU_MIGHT_LIKE_ARTISTS, "artist", wire.youMightLikeArtists),
)
prewarmer.warm(
wire.rediscoverArtists + wire.lastPlayedArtists + wire.youMightLikeArtists,
/**
* Caller's system-playlist build state for the Home placeholder
* cards. One-shot GET; the caller refreshes alongside the index.
*/
suspend fun getSystemPlaylistsStatus(): SystemPlaylistsStatus =
meApi.getSystemPlaylistsStatus().let {
SystemPlaylistsStatus(
inFlight = it.inFlight,
lastRunAt = it.lastRunAt,
lastError = it.lastError,
)
}
private fun rowsFor(
section: String,
entityType: String,
ids: List<String>,
): List<CachedHomeIndexEntity> =
ids.mapIndexed { index, id ->
CachedHomeIndexEntity(
section = section,
position = index,
entityType = entityType,
entityId = id,
)
}
fun observeRecentlyAddedAlbums(): Flow<List<HomeTile<AlbumRef>>> =
observeAlbumSection(SECTION_RECENTLY_ADDED_ALBUMS)
/**
* The section's ordered entity ids, deduplicated.
*
* Room re-runs the query on every write to `cached_home_index` — and
* `CachedHomeIndexEntity.fetchedAt` is stamped fresh each time — so
* comparing whole rows would call every rewrite a change. Comparing
* the id list instead means a section whose contents didn't actually
* move never restarts the `flatMapLatest` below, which would
* otherwise tear down and rebuild all of its tiles' hydration flows
* and flicker unchanged tiles.
*/
private fun observeSectionIds(section: String): Flow<List<String>> =
homeIndexDao
.observeBySection(section)
.map { rows -> rows.map { it.entityId } }
.distinctUntilChanged()
fun observeRediscoverAlbums(): Flow<List<HomeTile<AlbumRef>>> =
observeAlbumSection(SECTION_REDISCOVER_ALBUMS)
@OptIn(ExperimentalCoroutinesApi::class)
private fun observeAlbumSection(section: String): Flow<List<HomeTile<AlbumRef>>> =
observeSectionIds(section).flatMapLatest { ids ->
if (ids.isEmpty()) {
flowOf(emptyList())
} else {
combine(ids.map { metadataProvider.observeAlbum(it) }) { refs ->
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
}
}
}
fun observeRediscoverArtists(): Flow<List<HomeTile<ArtistRef>>> =
observeArtistSection(SECTION_REDISCOVER_ARTISTS)
@OptIn(ExperimentalCoroutinesApi::class)
private fun observeArtistSection(section: String): Flow<List<HomeTile<ArtistRef>>> =
observeSectionIds(section).flatMapLatest { ids ->
if (ids.isEmpty()) {
flowOf(emptyList())
} else {
combine(ids.map { metadataProvider.observeArtist(it) }) { refs ->
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
}
}
}
fun observeMostPlayedTracks(): Flow<List<HomeTile<TrackRef>>> =
observeTrackSection(SECTION_MOST_PLAYED_TRACKS)
@OptIn(ExperimentalCoroutinesApi::class)
private fun observeTrackSection(section: String): Flow<List<HomeTile<TrackRef>>> =
observeSectionIds(section).flatMapLatest { ids ->
if (ids.isEmpty()) {
flowOf(emptyList())
} else {
combine(ids.map { metadataProvider.observeTrack(it) }) { refs ->
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
}
}
}
fun observeLastPlayedArtists(): Flow<List<HomeTile<ArtistRef>>> =
observeArtistSection(SECTION_LAST_PLAYED_ARTISTS)
companion object {
const val SECTION_RECENTLY_ADDED_ALBUMS = "recently_added_albums"
const val SECTION_REDISCOVER_ALBUMS = "rediscover_albums"
const val SECTION_REDISCOVER_ARTISTS = "rediscover_artists"
const val SECTION_MOST_PLAYED_TRACKS = "most_played_tracks"
const val SECTION_LAST_PLAYED_ARTISTS = "last_played_artists"
const val SECTION_YOU_MIGHT_LIKE_ALBUMS = "you_might_like_albums"
const val SECTION_YOU_MIGHT_LIKE_ARTISTS = "you_might_like_artists"
fun observeYouMightLikeAlbums(): Flow<List<HomeTile<AlbumRef>>> =
observeAlbumSection(SECTION_YOU_MIGHT_LIKE_ALBUMS)
/** Every section [refreshIndex] owns — the unit of one atomic swap. */
val ALL_SECTIONS =
listOf(
SECTION_RECENTLY_ADDED_ALBUMS,
SECTION_REDISCOVER_ALBUMS,
SECTION_REDISCOVER_ARTISTS,
SECTION_MOST_PLAYED_TRACKS,
SECTION_LAST_PLAYED_ARTISTS,
SECTION_YOU_MIGHT_LIKE_ALBUMS,
SECTION_YOU_MIGHT_LIKE_ARTISTS,
)
}
fun observeYouMightLikeArtists(): Flow<List<HomeTile<ArtistRef>>> =
observeArtistSection(SECTION_YOU_MIGHT_LIKE_ARTISTS)
/** True when the index cache already has content on screen to protect. */
suspend fun hasCachedIndex(): Boolean = homeIndexDao.hasAny()
/**
* Pulls /api/home/index and swaps every cached_home_index section in
* a single transaction, then pre-warms the top artists. Missing
* entity rows hydrate via the on-miss path.
*
* One transaction for all seven sections is deliberate: Room notifies
* observers once, on commit, so Home swaps from the old content to
* the new in a single emission. Per-section, un-transacted writes
* would make every row visibly collapse to empty and refill, one
* after another.
*/
suspend fun refreshIndex() {
val wire = api.getHomeIndex()
homeIndexDao.replaceSections(
sections = ALL_SECTIONS,
rows = rowsFor(SECTION_RECENTLY_ADDED_ALBUMS, "album", wire.recentlyAddedAlbums) +
rowsFor(SECTION_REDISCOVER_ALBUMS, "album", wire.rediscoverAlbums) +
rowsFor(SECTION_REDISCOVER_ARTISTS, "artist", wire.rediscoverArtists) +
rowsFor(SECTION_MOST_PLAYED_TRACKS, "track", wire.mostPlayedTracks) +
rowsFor(SECTION_LAST_PLAYED_ARTISTS, "artist", wire.lastPlayedArtists) +
rowsFor(SECTION_YOU_MIGHT_LIKE_ALBUMS, "album", wire.youMightLikeAlbums) +
rowsFor(SECTION_YOU_MIGHT_LIKE_ARTISTS, "artist", wire.youMightLikeArtists),
)
prewarmer.warm(
wire.rediscoverArtists + wire.lastPlayedArtists + wire.youMightLikeArtists,
)
}
private fun rowsFor(
section: String,
entityType: String,
ids: List<String>,
): List<CachedHomeIndexEntity> = ids.mapIndexed { index, id ->
CachedHomeIndexEntity(
section = section,
position = index,
entityType = entityType,
entityId = id,
)
}
/**
* The section's ordered entity ids, deduplicated.
*
* Room re-runs the query on every write to `cached_home_index` — and
* `CachedHomeIndexEntity.fetchedAt` is stamped fresh each time — so
* comparing whole rows would call every rewrite a change. Comparing
* the id list instead means a section whose contents didn't actually
* move never restarts the `flatMapLatest` below, which would
* otherwise tear down and rebuild all of its tiles' hydration flows
* and flicker unchanged tiles.
*/
private fun observeSectionIds(section: String): Flow<List<String>> =
homeIndexDao.observeBySection(section)
.map { rows -> rows.map { it.entityId } }
.distinctUntilChanged()
@OptIn(ExperimentalCoroutinesApi::class)
private fun observeAlbumSection(section: String): Flow<List<HomeTile<AlbumRef>>> =
observeSectionIds(section).flatMapLatest { ids ->
if (ids.isEmpty()) {
flowOf(emptyList())
} else {
combine(ids.map { metadataProvider.observeAlbum(it) }) { refs ->
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
}
}
}
@OptIn(ExperimentalCoroutinesApi::class)
private fun observeArtistSection(section: String): Flow<List<HomeTile<ArtistRef>>> =
observeSectionIds(section).flatMapLatest { ids ->
if (ids.isEmpty()) {
flowOf(emptyList())
} else {
combine(ids.map { metadataProvider.observeArtist(it) }) { refs ->
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
}
}
}
@OptIn(ExperimentalCoroutinesApi::class)
private fun observeTrackSection(section: String): Flow<List<HomeTile<TrackRef>>> =
observeSectionIds(section).flatMapLatest { ids ->
if (ids.isEmpty()) {
flowOf(emptyList())
} else {
combine(ids.map { metadataProvider.observeTrack(it) }) { refs ->
ids.mapIndexed { i, id -> HomeTile(id, refs[i]) }
}
}
}
companion object {
const val SECTION_RECENTLY_ADDED_ALBUMS = "recently_added_albums"
const val SECTION_REDISCOVER_ALBUMS = "rediscover_albums"
const val SECTION_REDISCOVER_ARTISTS = "rediscover_artists"
const val SECTION_MOST_PLAYED_TRACKS = "most_played_tracks"
const val SECTION_LAST_PLAYED_ARTISTS = "last_played_artists"
const val SECTION_YOU_MIGHT_LIKE_ALBUMS = "you_might_like_albums"
const val SECTION_YOU_MIGHT_LIKE_ARTISTS = "you_might_like_artists"
/** Every section [refreshIndex] owns — the unit of one atomic swap. */
val ALL_SECTIONS = listOf(
SECTION_RECENTLY_ADDED_ALBUMS,
SECTION_REDISCOVER_ALBUMS,
SECTION_REDISCOVER_ARTISTS,
SECTION_MOST_PLAYED_TRACKS,
SECTION_LAST_PLAYED_ARTISTS,
SECTION_YOU_MIGHT_LIKE_ALBUMS,
SECTION_YOU_MIGHT_LIKE_ARTISTS,
)
}
}
File diff suppressed because it is too large Load Diff
@@ -17,11 +17,6 @@ import retrofit2.create
import javax.inject.Inject
import javax.inject.Singleton
// LibraryRepository owns reads + refreshes for three entity families
// (artists / albums / tracks) plus shuffle. Function count scales with
// entity-family count; splitting into per-family repos would
// scatter the shared dao + retrofit plumbing for no real gain.
/**
* Cache-first reads of artists/albums/tracks. The Room DAOs are the
* source of truth ViewModels observe; refresh* methods pull from the
@@ -32,202 +27,183 @@ import javax.inject.Singleton
* own their interfaces (see NetworkModule), so there is no @Provides
* per endpoint — fewer Hilt bindings, locality of reference.
*/
// LibraryRepository owns reads + refreshes for three entity families
// (artists / albums / tracks) plus shuffle. Function count scales with
// entity-family count; splitting into per-family repos would
// scatter the shared dao + retrofit plumbing for no real gain.
@Suppress("TooManyFunctions")
@Singleton
class LibraryRepository
@Inject
constructor(
private val artistDao: CachedArtistDao,
private val albumDao: CachedAlbumDao,
private val trackDao: CachedTrackDao,
retrofit: Retrofit,
) {
private val api: LibraryApi = retrofit.create()
class LibraryRepository @Inject constructor(
private val artistDao: CachedArtistDao,
private val albumDao: CachedAlbumDao,
private val trackDao: CachedTrackDao,
retrofit: Retrofit,
) {
private val api: LibraryApi = retrofit.create()
// ---- Reads (Flow, cache-first; the cache is the source of truth) ----
// ---- Reads (Flow, cache-first; the cache is the source of truth) ----
// Joins each artist to its first cached album (by sort title) so the
// tile cover derives from /api/albums/{id}/cover — cached_artists
// stores no cover and sync carries none.
fun observeArtists(): Flow<List<ArtistRef>> =
combine(artistDao.observeAll(), albumDao.observeAll()) { artists, albums ->
val firstAlbumByArtist =
albums
.groupBy { it.artistId }
.mapValues { (_, list) -> list.minByOrNull { it.sortTitle }?.id ?: "" }
artists.map { it.toDomain(coverAlbumId = firstAlbumByArtist[it.id] ?: "") }
}
fun observeAlbums(): Flow<List<AlbumRef>> = albumDao.observeAll().map { rows -> rows.map { it.toDomain() } }
fun observeAlbumsForArtist(artistId: String): Flow<List<AlbumRef>> =
albumDao.observeByArtist(artistId).map { rows -> rows.map { it.toDomain() } }
fun observeTracksForAlbum(albumId: String): Flow<List<TrackRef>> =
trackDao.observeByAlbum(albumId).map { rows -> rows.map { it.toDomain() } }
// ---- Single-shot lookups ----
suspend fun getArtist(id: String): ArtistRef? = artistDao.getById(id)?.toDomain()
suspend fun getAlbum(id: String): AlbumRef? = albumDao.getById(id)?.toDomain()
suspend fun getTrack(id: String): TrackRef? = trackDao.getById(id)?.toDomain()
// ---- Server refreshes (sync-style writes; errors propagate) ----
/**
* Pulls the full artist detail (ArtistRef + albums), persists both,
* and returns the in-memory snapshot. Lets the ArtistDetail screen
* render from the wire response without the Room round-trip.
*/
suspend fun refreshArtistDetail(id: String): ArtistDetailRef {
val wire = api.getArtistDetail(id)
artistDao.upsertAll(listOf(wire.toArtistEntity()))
albumDao.upsertAll(wire.albums.map { it.toEntity() })
return ArtistDetailRef(
artist =
ArtistRef(
id = wire.id,
name = wire.name,
sortName = wire.sortName,
albumCount = wire.albumCount,
coverUrl = wire.coverUrl,
),
albums = wire.albums.map { it.toDomain() },
)
// Joins each artist to its first cached album (by sort title) so the
// tile cover derives from /api/albums/{id}/cover — cached_artists
// stores no cover and sync carries none.
fun observeArtists(): Flow<List<ArtistRef>> =
combine(artistDao.observeAll(), albumDao.observeAll()) { artists, albums ->
val firstAlbumByArtist = albums
.groupBy { it.artistId }
.mapValues { (_, list) -> list.minByOrNull { it.sortTitle }?.id ?: "" }
artists.map { it.toDomain(coverAlbumId = firstAlbumByArtist[it.id] ?: "") }
}
/**
* Pulls every track for an artist (across all their albums). Used
* by the "Play artist" button on the ArtistDetail header. No
* persistence — the response is consumed straight into a player
* queue.
*/
suspend fun fetchArtistTracks(id: String): List<TrackRef> = api.getArtistTracks(id).map { it.toDomain() }
fun observeAlbums(): Flow<List<AlbumRef>> =
albumDao.observeAll().map { rows -> rows.map { it.toDomain() } }
/**
* Pulls related artists for the ArtistDetail "Similar artists"
* strip. Network-only — non-critical UI, callers swallow failures
* and render nothing rather than blocking the screen.
*/
suspend fun fetchSimilarArtists(id: String): List<ArtistRef> = api.getSimilarArtists(id).map { it.toDomain() }
fun observeAlbumsForArtist(artistId: String): Flow<List<AlbumRef>> =
albumDao.observeByArtist(artistId).map { rows -> rows.map { it.toDomain() } }
/**
* Pulls the artist's top tracks for the ArtistDetail "Top tracks"
* panel. Network-only; tapping a row plays this exact list as a
* queue, so no persistence is needed.
*/
suspend fun fetchArtistTopTracks(id: String): List<TrackRef> = api.getArtistTopTracks(id).map { it.toDomain() }
fun observeTracksForAlbum(albumId: String): Flow<List<TrackRef>> =
trackDao.observeByAlbum(albumId).map { rows -> rows.map { it.toDomain() } }
/**
* Pulls the album detail (AlbumRef + tracks), persists both, and
* returns the in-memory snapshot. Lets the AlbumDetail screen
* render immediately from the wire response without waiting for
* the Room round-trip.
*/
suspend fun refreshAlbumDetail(id: String): AlbumDetailRef {
val wire = api.getAlbumDetail(id)
albumDao.upsertAll(listOf(wire.toAlbumEntity()))
trackDao.upsertAll(wire.tracks.map { it.toEntity() })
return AlbumDetailRef(
album =
AlbumRef(
id = wire.id,
title = wire.title,
artistId = wire.artistId,
sortTitle = wire.sortTitle,
artistName = wire.artistName,
year = wire.year,
trackCount = wire.trackCount,
durationSec = wire.durationSec,
coverUrl = wire.coverUrl,
),
tracks = wire.tracks.map { it.toDomain() },
)
}
// ---- Single-shot lookups ----
/** Track detail — single track, mainly for the hydration queue. */
suspend fun refreshTrack(id: String) {
val wire = api.getTrack(id)
trackDao.upsertAll(listOf(wire.toEntity()))
}
suspend fun getArtist(id: String): ArtistRef? = artistDao.getById(id)?.toDomain()
/**
* "Shuffle all" — server picks random tracks across the entire
* library. Backs the Library AppBar Shuffle button. No cache hit;
* the user-facing semantics are "give me something fresh".
*/
suspend fun shuffleLibrary(limit: Int = SHUFFLE_DEFAULT_LIMIT): List<TrackRef> =
api.shuffleLibrary(limit = limit).map { it.toDomain() }
suspend fun getAlbum(id: String): AlbumRef? = albumDao.getById(id)?.toDomain()
// ---- Browse axes ----
//
// Server-backed rather than cache-first, unlike everything above: the
// server's index leaves out tracks whose files are missing and is the
// one the web client shows. See LibraryApi for why the cache's own
// missing mark is not used to build it locally.
suspend fun getTrack(id: String): TrackRef? = trackDao.getById(id)?.toDomain()
/** Genre index, ordered by track count then name (server order). */
suspend fun genres(): List<GenreCount> =
api.getGenres().map {
GenreCount(genre = it.genre, trackCount = it.trackCount)
}
// ---- Server refreshes (sync-style writes; errors propagate) ----
/** Year index, newest first. Albums with no release date are absent. */
suspend fun albumYears(): List<YearCount> =
api.getAlbumYears().map {
YearCount(year = it.year, albumCount = it.albumCount)
}
/** One page of albums carrying [genre] on any track. */
suspend fun albumsByGenre(
genre: String,
limit: Int,
offset: Int,
): AlbumPage {
val page = api.getAlbumsByGenre(genre = genre, limit = limit, offset = offset)
return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total)
}
/** One page of albums released in [year]. */
suspend fun albumsByYear(
year: Int,
limit: Int,
offset: Int,
): AlbumPage {
val page =
api.getAlbumsByYear(
yearFrom = year,
yearTo = year,
limit = limit,
offset = offset,
)
return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total)
}
private companion object {
const val SHUFFLE_DEFAULT_LIMIT = 100
}
/**
* Pulls the full artist detail (ArtistRef + albums), persists both,
* and returns the in-memory snapshot. Lets the ArtistDetail screen
* render from the wire response without the Room round-trip.
*/
suspend fun refreshArtistDetail(id: String): ArtistDetailRef {
val wire = api.getArtistDetail(id)
artistDao.upsertAll(listOf(wire.toArtistEntity()))
albumDao.upsertAll(wire.albums.map { it.toEntity() })
return ArtistDetailRef(
artist = ArtistRef(
id = wire.id,
name = wire.name,
sortName = wire.sortName,
albumCount = wire.albumCount,
coverUrl = wire.coverUrl,
),
albums = wire.albums.map { it.toDomain() },
)
}
/**
* Pulls every track for an artist (across all their albums). Used
* by the "Play artist" button on the ArtistDetail header. No
* persistence — the response is consumed straight into a player
* queue.
*/
suspend fun fetchArtistTracks(id: String): List<TrackRef> =
api.getArtistTracks(id).map { it.toDomain() }
/**
* Pulls related artists for the ArtistDetail "Similar artists"
* strip. Network-only — non-critical UI, callers swallow failures
* and render nothing rather than blocking the screen.
*/
suspend fun fetchSimilarArtists(id: String): List<ArtistRef> =
api.getSimilarArtists(id).map { it.toDomain() }
/**
* Pulls the artist's top tracks for the ArtistDetail "Top tracks"
* panel. Network-only; tapping a row plays this exact list as a
* queue, so no persistence is needed.
*/
suspend fun fetchArtistTopTracks(id: String): List<TrackRef> =
api.getArtistTopTracks(id).map { it.toDomain() }
/**
* Pulls the album detail (AlbumRef + tracks), persists both, and
* returns the in-memory snapshot. Lets the AlbumDetail screen
* render immediately from the wire response without waiting for
* the Room round-trip.
*/
suspend fun refreshAlbumDetail(id: String): AlbumDetailRef {
val wire = api.getAlbumDetail(id)
albumDao.upsertAll(listOf(wire.toAlbumEntity()))
trackDao.upsertAll(wire.tracks.map { it.toEntity() })
return AlbumDetailRef(
album = AlbumRef(
id = wire.id,
title = wire.title,
artistId = wire.artistId,
sortTitle = wire.sortTitle,
artistName = wire.artistName,
year = wire.year,
trackCount = wire.trackCount,
durationSec = wire.durationSec,
coverUrl = wire.coverUrl,
),
tracks = wire.tracks.map { it.toDomain() },
)
}
/** Track detail — single track, mainly for the hydration queue. */
suspend fun refreshTrack(id: String) {
val wire = api.getTrack(id)
trackDao.upsertAll(listOf(wire.toEntity()))
}
/**
* "Shuffle all" — server picks random tracks across the entire
* library. Backs the Library AppBar Shuffle button. No cache hit;
* the user-facing semantics are "give me something fresh".
*/
suspend fun shuffleLibrary(limit: Int = SHUFFLE_DEFAULT_LIMIT): List<TrackRef> =
api.shuffleLibrary(limit = limit).map { it.toDomain() }
// ---- Browse axes ----
//
// Server-backed rather than cache-first, unlike everything above: the
// server's index leaves out tracks whose files are missing and is the
// one the web client shows. See LibraryApi for why the cache's own
// missing mark is not used to build it locally.
/** Genre index, ordered by track count then name (server order). */
suspend fun genres(): List<GenreCount> =
api.getGenres().map { GenreCount(genre = it.genre, trackCount = it.trackCount) }
/** Year index, newest first. Albums with no release date are absent. */
suspend fun albumYears(): List<YearCount> =
api.getAlbumYears().map { YearCount(year = it.year, albumCount = it.albumCount) }
/** One page of albums carrying [genre] on any track. */
suspend fun albumsByGenre(genre: String, limit: Int, offset: Int): AlbumPage {
val page = api.getAlbumsByGenre(genre = genre, limit = limit, offset = offset)
return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total)
}
/** One page of albums released in [year]. */
suspend fun albumsByYear(year: Int, limit: Int, offset: Int): AlbumPage {
val page = api.getAlbumsByYear(
yearFrom = year,
yearTo = year,
limit = limit,
offset = offset,
)
return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total)
}
private companion object {
const val SHUFFLE_DEFAULT_LIMIT = 100
}
}
/** One row of the genre index. */
data class GenreCount(
val genre: String,
val trackCount: Int,
)
data class GenreCount(val genre: String, val trackCount: Int)
/** One row of the year index. */
data class YearCount(
val year: Int,
val albumCount: Int,
)
data class YearCount(val year: Int, val albumCount: Int)
/**
* A page of albums plus the server's total for the whole filter, which is
* what lets the UI say how many are left rather than just offering "more".
*/
data class AlbumPage(
val items: List<AlbumRef>,
val total: Int,
)
data class AlbumPage(val items: List<AlbumRef>, val total: Int)
@@ -2,7 +2,6 @@
package com.fabledsword.minstrel.library.ui
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
@@ -13,6 +12,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
@@ -29,6 +29,7 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
@@ -50,12 +51,12 @@ 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.TrackRow
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LikeButton
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.SkeletonTrackRow
import com.fabledsword.minstrel.shared.widgets.TrackRow
import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton
@OptIn(ExperimentalMaterial3Api::class)
@@ -94,12 +95,11 @@ fun AlbumDetailScreen(
}
}
private fun titleFor(state: AlbumDetailUiState): String =
when (state) {
is AlbumDetailUiState.Success -> state.detail.album.title
is AlbumDetailUiState.Loading -> state.seed?.title ?: "Album"
is AlbumDetailUiState.Error -> "Album"
}
private fun titleFor(state: AlbumDetailUiState): String = when (state) {
is AlbumDetailUiState.Success -> state.detail.album.title
is AlbumDetailUiState.Loading -> state.seed?.title ?: "Album"
is AlbumDetailUiState.Error -> "Album"
}
@Composable
private fun AlbumDetailStateContent(
@@ -115,12 +115,11 @@ private fun AlbumDetailStateContent(
when (val s = state) {
is AlbumDetailUiState.Loading ->
if (s.seed != null) SeededAlbumLoading(s.seed) else SkeletonTrackList()
is AlbumDetailUiState.Error ->
ErrorRetry(
title = "Couldn't load album",
message = s.message,
onRetry = { viewModel.refresh() },
)
is AlbumDetailUiState.Error -> ErrorRetry(
title = "Couldn't load album",
message = s.message,
onRetry = { viewModel.refresh() },
)
is AlbumDetailUiState.Success -> {
val albumLiked by viewModel.albumLiked.collectAsStateWithLifecycle()
val likedTrackIds by viewModel.likedTrackIds
@@ -210,10 +209,9 @@ private fun AlbumHeader(
onToggleAlbumLike: () -> Unit,
) {
Column(
modifier =
Modifier
.fillMaxWidth()
.padding(16.dp),
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Row(
@@ -28,126 +28,112 @@ import javax.inject.Inject
private const val SHARE_STOP_TIMEOUT_MS = 5_000L
sealed interface AlbumDetailUiState {
data class Loading(
val seed: AlbumRef? = null,
) : AlbumDetailUiState
data class Success(
val detail: AlbumDetailRef,
) : AlbumDetailUiState
data class Error(
val message: String,
) : AlbumDetailUiState
data class Loading(val seed: AlbumRef? = null) : AlbumDetailUiState
data class Success(val detail: AlbumDetailRef) : AlbumDetailUiState
data class Error(val message: String) : AlbumDetailUiState
}
@HiltViewModel
class AlbumDetailViewModel
@Inject
constructor(
private val repository: LibraryRepository,
private val likes: LikesRepository,
private val player: PlayerController,
private val seedCache: DetailSeedCache,
networkStatus: NetworkStatusController,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val route: AlbumDetail = savedStateHandle.toRoute()
val albumId: String = route.id
class AlbumDetailViewModel @Inject constructor(
private val repository: LibraryRepository,
private val likes: LikesRepository,
private val player: PlayerController,
private val seedCache: DetailSeedCache,
networkStatus: NetworkStatusController,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val internal =
MutableStateFlow<AlbumDetailUiState>(AlbumDetailUiState.Loading())
val uiState: StateFlow<AlbumDetailUiState> = internal.asStateFlow()
private val route: AlbumDetail = savedStateHandle.toRoute()
val albumId: String = route.id
val albumLiked: StateFlow<Boolean> =
likes
.observeIsLiked(LikesRepository.ENTITY_ALBUM, albumId)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
initialValue = false,
)
private val internal =
MutableStateFlow<AlbumDetailUiState>(AlbumDetailUiState.Loading())
val uiState: StateFlow<AlbumDetailUiState> = internal.asStateFlow()
val likedTrackIds: StateFlow<Set<String>> =
likes
.observeLikedTrackIds()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
initialValue = emptySet(),
)
init {
refresh()
// Screen-level auto-recovery: a detail that failed to
// load while the server was unreachable re-fetches when health
// returns, so coming back to the screen shows content, not an error.
viewModelScope.launch {
networkStatus.recoveries().collect {
if (internal.value is AlbumDetailUiState.Error) refresh()
}
}
}
fun refresh(): Job =
viewModelScope.launch {
val carried =
when (val cur = internal.value) {
is AlbumDetailUiState.Loading -> cur.seed
is AlbumDetailUiState.Success -> cur.detail.album
is AlbumDetailUiState.Error -> null
}
internal.value = AlbumDetailUiState.Loading(carried ?: seedCache.peekAlbum(albumId))
try {
val detail = repository.refreshAlbumDetail(albumId)
internal.value = AlbumDetailUiState.Success(detail)
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = AlbumDetailUiState.Error(ErrorCopy.fromThrowable(e))
}
}
/** Play the album starting at [startTrackId] (or the first track when null). */
fun play(startTrackId: String?) {
val detail = (internal.value as? AlbumDetailUiState.Success)?.detail ?: return
if (detail.tracks.isEmpty()) return
val startIndex =
detail.tracks
.indexOfFirst { it.id == startTrackId }
.coerceAtLeast(0)
player.setQueue(
tracks = detail.tracks,
initialIndex = startIndex,
source = "album:${detail.album.id}",
val albumLiked: StateFlow<Boolean> =
likes.observeIsLiked(LikesRepository.ENTITY_ALBUM, albumId)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
initialValue = false,
)
}
/**
* Play the album in shuffled order. Pre-shuffles the list and hands
* the result to the player — matches the PlaylistDetail shuffle
* pattern. A future refinement could use Media3's
* `setShuffleModeEnabled` for play-then-shuffle without disturbing
* the original queue ordering.
*/
fun shuffle() {
val detail = (internal.value as? AlbumDetailUiState.Success)?.detail ?: return
if (detail.tracks.isEmpty()) return
player.setQueue(
tracks = detail.tracks.shuffled(),
initialIndex = 0,
source = "album:${detail.album.id}",
val likedTrackIds: StateFlow<Set<String>> =
likes.observeLikedTrackIds()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
initialValue = emptySet(),
)
}
fun toggleLikeAlbum() {
val desired = !albumLiked.value
viewModelScope.launch {
likes.toggleLike(LikesRepository.ENTITY_ALBUM, albumId, desired)
init {
refresh()
// Screen-level auto-recovery: a detail that failed to
// load while the server was unreachable re-fetches when health
// returns, so coming back to the screen shows content, not an error.
viewModelScope.launch {
networkStatus.recoveries().collect {
if (internal.value is AlbumDetailUiState.Error) refresh()
}
}
fun toggleLikeTrack(trackId: String) {
viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) }
}
}
fun refresh(): Job = viewModelScope.launch {
val carried = when (val cur = internal.value) {
is AlbumDetailUiState.Loading -> cur.seed
is AlbumDetailUiState.Success -> cur.detail.album
is AlbumDetailUiState.Error -> null
}
internal.value = AlbumDetailUiState.Loading(carried ?: seedCache.peekAlbum(albumId))
try {
val detail = repository.refreshAlbumDetail(albumId)
internal.value = AlbumDetailUiState.Success(detail)
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = AlbumDetailUiState.Error(ErrorCopy.fromThrowable(e))
}
}
/** Play the album starting at [startTrackId] (or the first track when null). */
fun play(startTrackId: String?) {
val detail = (internal.value as? AlbumDetailUiState.Success)?.detail ?: return
if (detail.tracks.isEmpty()) return
val startIndex = detail.tracks
.indexOfFirst { it.id == startTrackId }
.coerceAtLeast(0)
player.setQueue(
tracks = detail.tracks,
initialIndex = startIndex,
source = "album:${detail.album.id}",
)
}
/**
* Play the album in shuffled order. Pre-shuffles the list and hands
* the result to the player — matches the PlaylistDetail shuffle
* pattern. A future refinement could use Media3's
* `setShuffleModeEnabled` for play-then-shuffle without disturbing
* the original queue ordering.
*/
fun shuffle() {
val detail = (internal.value as? AlbumDetailUiState.Success)?.detail ?: return
if (detail.tracks.isEmpty()) return
player.setQueue(
tracks = detail.tracks.shuffled(),
initialIndex = 0,
source = "album:${detail.album.id}",
)
}
fun toggleLikeAlbum() {
val desired = !albumLiked.value
viewModelScope.launch {
likes.toggleLike(LikesRepository.ENTITY_ALBUM, albumId, desired)
}
}
fun toggleLikeTrack(trackId: String) {
viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) }
}
}
@@ -20,15 +20,16 @@ import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items as lazyItems
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
@@ -57,15 +58,14 @@ import com.fabledsword.minstrel.nav.ArtistDetail
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.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow
import com.fabledsword.minstrel.shared.widgets.LikeButton
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold
import com.fabledsword.minstrel.shared.widgets.ServerImage
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile
import com.fabledsword.minstrel.shared.widgets.TrackRow
import androidx.compose.foundation.lazy.items as lazyItems
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -111,12 +111,11 @@ fun ArtistDetailScreen(
} else {
SkeletonArtistAlbumsGrid()
}
is ArtistDetailUiState.Error ->
ErrorRetry(
title = "Couldn't load artist",
message = s.message,
onRetry = { viewModel.refresh() },
)
is ArtistDetailUiState.Error -> ErrorRetry(
title = "Couldn't load artist",
message = s.message,
onRetry = { viewModel.refresh() },
)
is ArtistDetailUiState.Success ->
ArtistSuccessBody(s, viewModel, playerViewModel, navController)
}
@@ -146,12 +145,11 @@ private fun ArtistSuccessBody(
)
}
private fun titleFor(state: ArtistDetailUiState): String =
when (state) {
is ArtistDetailUiState.Success -> state.detail.artist.name
is ArtistDetailUiState.Loading -> state.seed?.name ?: "Artist"
is ArtistDetailUiState.Error -> "Artist"
}
private fun titleFor(state: ArtistDetailUiState): String = when (state) {
is ArtistDetailUiState.Success -> state.detail.artist.name
is ArtistDetailUiState.Loading -> state.seed?.name ?: "Artist"
is ArtistDetailUiState.Error -> "Artist"
}
@Composable
private fun ArtistBody(
@@ -280,10 +278,9 @@ private fun ArtistHeader(
onToggleLike: () -> Unit,
) {
Row(
modifier =
Modifier
.fillMaxWidth()
.padding(16.dp),
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
@@ -314,25 +311,20 @@ private fun ArtistHeader(
}
@Composable
private fun ArtistAvatar(
artist: ArtistRef,
fallbackAlbumId: String? = null,
) {
private fun ArtistAvatar(artist: ArtistRef, fallbackAlbumId: String? = null) {
// Server coverUrl wins; otherwise use the first loaded album's
// cover, the same rule the server applies. Bare Lucide.User only
// when neither exists.
val model =
when {
artist.coverUrl.isNotEmpty() -> artist.coverUrl
fallbackAlbumId != null -> albumCoverPath(fallbackAlbumId)
else -> null
}
val model = when {
artist.coverUrl.isNotEmpty() -> artist.coverUrl
fallbackAlbumId != null -> albumCoverPath(fallbackAlbumId)
else -> null
}
Box(
modifier =
Modifier
.size(96.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.surfaceVariant),
modifier = Modifier
.size(96.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.surfaceVariant),
contentAlignment = Alignment.Center,
) {
ServerImage(
@@ -343,15 +335,15 @@ private fun ArtistAvatar(
}
}
private fun albumCountLine(artist: ArtistRef): String = plural(artist.albumCount, "album", "albums")
private fun albumCountLine(artist: ArtistRef): String =
plural(artist.albumCount, "album", "albums")
@Composable
private fun EmptyAlbumsHint() {
Column(
modifier =
Modifier
.fillMaxWidth()
.padding(24.dp),
modifier = Modifier
.fillMaxWidth()
.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
@@ -33,146 +33,136 @@ import javax.inject.Inject
private const val SHARE_STOP_TIMEOUT_MS = 5_000L
sealed interface ArtistDetailUiState {
data class Loading(
val seed: ArtistRef? = null,
) : ArtistDetailUiState
data class Loading(val seed: ArtistRef? = null) : ArtistDetailUiState
data class Success(
val detail: ArtistDetailRef,
val similarArtists: List<ArtistRef> = emptyList(),
val topTracks: List<TrackRef> = emptyList(),
) : ArtistDetailUiState
data class Error(
val message: String,
) : ArtistDetailUiState
data class Error(val message: String) : ArtistDetailUiState
}
@HiltViewModel
class ArtistDetailViewModel
@Inject
constructor(
private val repository: LibraryRepository,
private val likes: LikesRepository,
private val player: PlayerController,
private val seedCache: DetailSeedCache,
networkStatus: NetworkStatusController,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val route: ArtistDetail = savedStateHandle.toRoute()
val artistId: String = route.id
class ArtistDetailViewModel @Inject constructor(
private val repository: LibraryRepository,
private val likes: LikesRepository,
private val player: PlayerController,
private val seedCache: DetailSeedCache,
networkStatus: NetworkStatusController,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val internal =
MutableStateFlow<ArtistDetailUiState>(ArtistDetailUiState.Loading())
val uiState: StateFlow<ArtistDetailUiState> = internal.asStateFlow()
private val route: ArtistDetail = savedStateHandle.toRoute()
val artistId: String = route.id
/** Transient one-shot messages for the screen-level snackbar (e.g. Play-button failure). */
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED)
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
private val internal =
MutableStateFlow<ArtistDetailUiState>(ArtistDetailUiState.Loading())
val uiState: StateFlow<ArtistDetailUiState> = internal.asStateFlow()
val artistLiked: StateFlow<Boolean> =
likes
.observeIsLiked(LikesRepository.ENTITY_ARTIST, artistId)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
initialValue = false,
)
/** Transient one-shot messages for the screen-level snackbar (e.g. Play-button failure). */
private val transientMessagesChannel = Channel<String>(Channel.BUFFERED)
val transientMessages: Flow<String> = transientMessagesChannel.receiveAsFlow()
init {
refresh()
// Screen-level auto-recovery. From Error, redo the
// whole load; from Success, re-pull just the secondary sections —
// their fetch failures are swallowed to emptyList, so a dead zone
// during the first load leaves them permanently absent otherwise.
viewModelScope.launch {
networkStatus.recoveries().collect {
when (internal.value) {
is ArtistDetailUiState.Error -> refresh()
is ArtistDetailUiState.Success -> loadSecondarySections()
is ArtistDetailUiState.Loading -> Unit
}
}
}
}
fun toggleLikeArtist() {
val desired = !artistLiked.value
viewModelScope.launch {
likes.toggleLike(LikesRepository.ENTITY_ARTIST, artistId, desired)
}
}
fun refresh(): Job =
viewModelScope.launch {
val carried =
when (val cur = internal.value) {
is ArtistDetailUiState.Loading -> cur.seed
is ArtistDetailUiState.Success -> cur.detail.artist
is ArtistDetailUiState.Error -> null
}
internal.value = ArtistDetailUiState.Loading(carried ?: seedCache.peekArtist(artistId))
try {
val detail = repository.refreshArtistDetail(artistId)
internal.value = ArtistDetailUiState.Success(detail)
loadSecondarySections()
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = ArtistDetailUiState.Error(ErrorCopy.fromThrowable(e))
}
}
/**
* Pulls the non-critical "Similar artists" + "Top tracks" sections
* and folds them into the live Success state. Each failure is
* swallowed (logged only) — these sections render absent rather than
* blocking, so the core artist view never depends on them.
*/
private suspend fun loadSecondarySections() {
val similar = sectionOrEmpty { repository.fetchSimilarArtists(artistId) }
val top = sectionOrEmpty { repository.fetchArtistTopTracks(artistId) }
val current = internal.value
if (current is ArtistDetailUiState.Success) {
internal.value = current.copy(similarArtists = similar, topTracks = top)
}
}
private inline fun <T> sectionOrEmpty(block: () -> List<T>): List<T> =
try {
block()
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
Timber.w(e, "Artist secondary section fetch failed for %s", artistId)
emptyList()
}
/**
* Pull every track across the artist's albums, shuffle, and start
* playing. Pressing Play on an artist means "shuffle this artist",
* not "play album by album in tracklist order". One network
* round-trip per click; fine because the user explicitly tapped Play.
*/
fun playArtist() {
viewModelScope.launch {
shufflePlayArtist(artistId, repository, player) { transientMessagesChannel.trySend(it) }
}
}
/**
* Plays the loaded "Top tracks" list starting at [index] — the top
* tracks are themselves the playable queue (mirrors the web client's
* sectionTracks = top-tracks behaviour). No network round-trip; the
* list is already in the Success state.
*/
fun playTopTracks(index: Int) {
val tracks = (internal.value as? ArtistDetailUiState.Success)?.topTracks.orEmpty()
if (tracks.isEmpty()) return
player.setQueue(
tracks = tracks,
initialIndex = index.coerceIn(0, tracks.lastIndex),
source = "artist-top:$artistId",
val artistLiked: StateFlow<Boolean> =
likes.observeIsLiked(LikesRepository.ENTITY_ARTIST, artistId)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
initialValue = false,
)
init {
refresh()
// Screen-level auto-recovery. From Error, redo the
// whole load; from Success, re-pull just the secondary sections —
// their fetch failures are swallowed to emptyList, so a dead zone
// during the first load leaves them permanently absent otherwise.
viewModelScope.launch {
networkStatus.recoveries().collect {
when (internal.value) {
is ArtistDetailUiState.Error -> refresh()
is ArtistDetailUiState.Success -> loadSecondarySections()
is ArtistDetailUiState.Loading -> Unit
}
}
}
}
fun toggleLikeArtist() {
val desired = !artistLiked.value
viewModelScope.launch {
likes.toggleLike(LikesRepository.ENTITY_ARTIST, artistId, desired)
}
}
fun refresh(): Job = viewModelScope.launch {
val carried = when (val cur = internal.value) {
is ArtistDetailUiState.Loading -> cur.seed
is ArtistDetailUiState.Success -> cur.detail.artist
is ArtistDetailUiState.Error -> null
}
internal.value = ArtistDetailUiState.Loading(carried ?: seedCache.peekArtist(artistId))
try {
val detail = repository.refreshArtistDetail(artistId)
internal.value = ArtistDetailUiState.Success(detail)
loadSecondarySections()
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
internal.value = ArtistDetailUiState.Error(ErrorCopy.fromThrowable(e))
}
}
/**
* Pulls the non-critical "Similar artists" + "Top tracks" sections
* and folds them into the live Success state. Each failure is
* swallowed (logged only) — these sections render absent rather than
* blocking, so the core artist view never depends on them.
*/
private suspend fun loadSecondarySections() {
val similar = sectionOrEmpty { repository.fetchSimilarArtists(artistId) }
val top = sectionOrEmpty { repository.fetchArtistTopTracks(artistId) }
val current = internal.value
if (current is ArtistDetailUiState.Success) {
internal.value = current.copy(similarArtists = similar, topTracks = top)
}
}
private inline fun <T> sectionOrEmpty(block: () -> List<T>): List<T> =
try {
block()
} catch (
@Suppress("TooGenericExceptionCaught") e: Throwable,
) {
Timber.w(e, "Artist secondary section fetch failed for %s", artistId)
emptyList()
}
/**
* Pull every track across the artist's albums, shuffle, and start
* playing. Pressing Play on an artist means "shuffle this artist",
* not "play album by album in tracklist order". One network
* round-trip per click; fine because the user explicitly tapped Play.
*/
fun playArtist() {
viewModelScope.launch {
shufflePlayArtist(artistId, repository, player) { transientMessagesChannel.trySend(it) }
}
}
/**
* Plays the loaded "Top tracks" list starting at [index] — the top
* tracks are themselves the playable queue (mirrors the web client's
* sectionTracks = top-tracks behaviour). No network round-trip; the
* list is already in the Success state.
*/
fun playTopTracks(index: Int) {
val tracks = (internal.value as? ArtistDetailUiState.Success)?.topTracks.orEmpty()
if (tracks.isEmpty()) return
player.setQueue(
tracks = tracks,
initialIndex = index.coerceIn(0, tracks.lastIndex),
source = "artist-top:$artistId",
)
}
}
@@ -41,11 +41,6 @@ data class AlbumBrowseState(
val remaining: Int get() = (total - albums.size).coerceAtLeast(0)
}
// Two browse axes, each with an index, a filter/sort or grouping, a
// drill-down and a pager. The function count is two axes' worth of a
// cohesive surface; splitting into GenresViewModel + YearsViewModel would
// duplicate the shared paging body for no gain.
/**
* Backs the Genres and Years tabs, the same browse axes the web client has.
*
@@ -54,184 +49,172 @@ data class AlbumBrowseState(
* missing and matches the web client's. These two tabs therefore need a
* connection; the empty states say so rather than looking broken.
*/
// Two browse axes, each with an index, a filter/sort or grouping, a
// drill-down and a pager. The function count is two axes' worth of a
// cohesive surface; splitting into GenresViewModel + YearsViewModel would
// duplicate the shared paging body for no gain.
@Suppress("TooManyFunctions")
@HiltViewModel
class BrowseViewModel
@Inject
constructor(
private val repository: LibraryRepository,
) : ViewModel() {
private val genresInternal = MutableStateFlow<UiState<List<GenreCount>>>(UiState.Loading)
val genres: StateFlow<UiState<List<GenreCount>>> = genresInternal.asStateFlow()
class BrowseViewModel @Inject constructor(
private val repository: LibraryRepository,
) : ViewModel() {
private val yearsInternal = MutableStateFlow<UiState<List<YearCount>>>(UiState.Loading)
val years: StateFlow<UiState<List<YearCount>>> = yearsInternal.asStateFlow()
private val genresInternal = MutableStateFlow<UiState<List<GenreCount>>>(UiState.Loading)
val genres: StateFlow<UiState<List<GenreCount>>> = genresInternal.asStateFlow()
private val genreFilterInternal = MutableStateFlow("")
val genreFilter: StateFlow<String> = genreFilterInternal.asStateFlow()
private val yearsInternal = MutableStateFlow<UiState<List<YearCount>>>(UiState.Loading)
val years: StateFlow<UiState<List<YearCount>>> = yearsInternal.asStateFlow()
private val genreSortInternal = MutableStateFlow(GenreSort.COUNT)
val genreSort: StateFlow<GenreSort> = genreSortInternal.asStateFlow()
private val genreFilterInternal = MutableStateFlow("")
val genreFilter: StateFlow<String> = genreFilterInternal.asStateFlow()
private val selectedGenreInternal = MutableStateFlow<String?>(null)
val selectedGenre: StateFlow<String?> = selectedGenreInternal.asStateFlow()
private val genreSortInternal = MutableStateFlow(GenreSort.COUNT)
val genreSort: StateFlow<GenreSort> = genreSortInternal.asStateFlow()
private val selectedYearInternal = MutableStateFlow<Int?>(null)
val selectedYear: StateFlow<Int?> = selectedYearInternal.asStateFlow()
private val selectedGenreInternal = MutableStateFlow<String?>(null)
val selectedGenre: StateFlow<String?> = selectedGenreInternal.asStateFlow()
private val genreAlbumsInternal = MutableStateFlow(AlbumBrowseState())
val genreAlbums: StateFlow<AlbumBrowseState> = genreAlbumsInternal.asStateFlow()
private val selectedYearInternal = MutableStateFlow<Int?>(null)
val selectedYear: StateFlow<Int?> = selectedYearInternal.asStateFlow()
private val yearAlbumsInternal = MutableStateFlow(AlbumBrowseState())
val yearAlbums: StateFlow<AlbumBrowseState> = yearAlbumsInternal.asStateFlow()
private val genreAlbumsInternal = MutableStateFlow(AlbumBrowseState())
val genreAlbums: StateFlow<AlbumBrowseState> = genreAlbumsInternal.asStateFlow()
// Guards against a slow response for a previously-selected genre/year
// landing after the user has moved on and painting over the new list.
// One counter per axis, since the two drill-downs are independent.
private var genreRequestToken = 0
private var yearRequestToken = 0
private val yearAlbumsInternal = MutableStateFlow(AlbumBrowseState())
val yearAlbums: StateFlow<AlbumBrowseState> = yearAlbumsInternal.asStateFlow()
init {
loadGenres()
loadYears()
}
// Guards against a slow response for a previously-selected genre/year
// landing after the user has moved on and painting over the new list.
// One counter per axis, since the two drill-downs are independent.
private var genreRequestToken = 0
private var yearRequestToken = 0
fun loadGenres() {
viewModelScope.launch {
genresInternal.value = UiState.Loading
genresInternal.value =
runCatching { repository.genres() }.fold(
onSuccess = { if (it.isEmpty()) UiState.Empty else UiState.Success(it) },
onFailure = { UiState.Error(ErrorCopy.fromThrowable(it)) },
)
}
}
init {
loadGenres()
loadYears()
}
fun loadYears() {
viewModelScope.launch {
yearsInternal.value = UiState.Loading
yearsInternal.value =
runCatching { repository.albumYears() }.fold(
onSuccess = { if (it.isEmpty()) UiState.Empty else UiState.Success(it) },
onFailure = { UiState.Error(ErrorCopy.fromThrowable(it)) },
)
}
}
fun setGenreFilter(value: String) {
genreFilterInternal.value = value
}
fun setGenreSort(sort: GenreSort) {
genreSortInternal.value = sort
}
/** Drill into [genre], or pass null to go back to the index. */
fun selectGenre(genre: String?) {
selectedGenreInternal.value = genre
genreRequestToken += 1
genreAlbumsInternal.value = AlbumBrowseState()
if (genre == null) return
fetchGenrePage(genre, offset = 0, token = genreRequestToken)
}
fun loadMoreGenreAlbums() {
val genre = selectedGenreInternal.value ?: return
val state = genreAlbumsInternal.value
if (state.loading || !state.hasMore) return
fetchGenrePage(genre, offset = state.albums.size, token = genreRequestToken)
}
fun retryGenreAlbums() {
selectedGenreInternal.value?.let { selectGenre(it) }
}
/** Drill into [year], or pass null to go back to the index. */
fun selectYear(year: Int?) {
selectedYearInternal.value = year
yearRequestToken += 1
yearAlbumsInternal.value = AlbumBrowseState()
if (year == null) return
fetchYearPage(year, offset = 0, token = yearRequestToken)
}
fun loadMoreYearAlbums() {
val year = selectedYearInternal.value ?: return
val state = yearAlbumsInternal.value
if (state.loading || !state.hasMore) return
fetchYearPage(year, offset = state.albums.size, token = yearRequestToken)
}
fun retryYearAlbums() {
selectedYearInternal.value?.let { selectYear(it) }
}
private fun fetchGenrePage(
genre: String,
offset: Int,
token: Int,
) {
fetchPage(
state = genreAlbumsInternal,
offset = offset,
isCurrent = { token == genreRequestToken },
fetch = { repository.albumsByGenre(genre, PAGE_SIZE, offset) },
fun loadGenres() {
viewModelScope.launch {
genresInternal.value = UiState.Loading
genresInternal.value = runCatching { repository.genres() }.fold(
onSuccess = { if (it.isEmpty()) UiState.Empty else UiState.Success(it) },
onFailure = { UiState.Error(ErrorCopy.fromThrowable(it)) },
)
}
private fun fetchYearPage(
year: Int,
offset: Int,
token: Int,
) {
fetchPage(
state = yearAlbumsInternal,
offset = offset,
isCurrent = { token == yearRequestToken },
fetch = { repository.albumsByYear(year, PAGE_SIZE, offset) },
)
}
/**
* The paging body both axes share: append on success, and drop the result
* entirely if the selection moved while the request was in flight.
*/
private fun fetchPage(
state: MutableStateFlow<AlbumBrowseState>,
offset: Int,
isCurrent: () -> Boolean,
fetch: suspend () -> AlbumPage,
) {
viewModelScope.launch {
state.value = state.value.copy(loading = true, failed = false)
runCatching { fetch() }.fold(
onSuccess = { page ->
if (!isCurrent()) return@launch
val merged =
if (offset == 0) page.items else state.value.albums + page.items
state.value =
AlbumBrowseState(
albums = merged,
total = page.total,
loading = false,
failed = false,
)
},
onFailure = {
if (!isCurrent()) return@launch
state.value = state.value.copy(loading = false, failed = true)
},
)
}
}
private companion object {
// Matches the web client's BROWSE_PAGE_SIZE so "Load more (N left)"
// steps at the same rate on both clients.
const val PAGE_SIZE = 50
}
}
fun loadYears() {
viewModelScope.launch {
yearsInternal.value = UiState.Loading
yearsInternal.value = runCatching { repository.albumYears() }.fold(
onSuccess = { if (it.isEmpty()) UiState.Empty else UiState.Success(it) },
onFailure = { UiState.Error(ErrorCopy.fromThrowable(it)) },
)
}
}
fun setGenreFilter(value: String) { genreFilterInternal.value = value }
fun setGenreSort(sort: GenreSort) { genreSortInternal.value = sort }
/** Drill into [genre], or pass null to go back to the index. */
fun selectGenre(genre: String?) {
selectedGenreInternal.value = genre
genreRequestToken += 1
genreAlbumsInternal.value = AlbumBrowseState()
if (genre == null) return
fetchGenrePage(genre, offset = 0, token = genreRequestToken)
}
fun loadMoreGenreAlbums() {
val genre = selectedGenreInternal.value ?: return
val state = genreAlbumsInternal.value
if (state.loading || !state.hasMore) return
fetchGenrePage(genre, offset = state.albums.size, token = genreRequestToken)
}
fun retryGenreAlbums() {
selectedGenreInternal.value?.let { selectGenre(it) }
}
/** Drill into [year], or pass null to go back to the index. */
fun selectYear(year: Int?) {
selectedYearInternal.value = year
yearRequestToken += 1
yearAlbumsInternal.value = AlbumBrowseState()
if (year == null) return
fetchYearPage(year, offset = 0, token = yearRequestToken)
}
fun loadMoreYearAlbums() {
val year = selectedYearInternal.value ?: return
val state = yearAlbumsInternal.value
if (state.loading || !state.hasMore) return
fetchYearPage(year, offset = state.albums.size, token = yearRequestToken)
}
fun retryYearAlbums() {
selectedYearInternal.value?.let { selectYear(it) }
}
private fun fetchGenrePage(genre: String, offset: Int, token: Int) {
fetchPage(
state = genreAlbumsInternal,
offset = offset,
isCurrent = { token == genreRequestToken },
fetch = { repository.albumsByGenre(genre, PAGE_SIZE, offset) },
)
}
private fun fetchYearPage(year: Int, offset: Int, token: Int) {
fetchPage(
state = yearAlbumsInternal,
offset = offset,
isCurrent = { token == yearRequestToken },
fetch = { repository.albumsByYear(year, PAGE_SIZE, offset) },
)
}
/**
* The paging body both axes share: append on success, and drop the result
* entirely if the selection moved while the request was in flight.
*/
private fun fetchPage(
state: MutableStateFlow<AlbumBrowseState>,
offset: Int,
isCurrent: () -> Boolean,
fetch: suspend () -> AlbumPage,
) {
viewModelScope.launch {
state.value = state.value.copy(loading = true, failed = false)
runCatching { fetch() }.fold(
onSuccess = { page ->
if (!isCurrent()) return@launch
val merged =
if (offset == 0) page.items else state.value.albums + page.items
state.value = AlbumBrowseState(
albums = merged,
total = page.total,
loading = false,
failed = false,
)
},
onFailure = {
if (!isCurrent()) return@launch
state.value = state.value.copy(loading = false, failed = true)
},
)
}
}
private companion object {
// Matches the web client's BROWSE_PAGE_SIZE so "Load more (N left)"
// steps at the same rate on both clients.
const val PAGE_SIZE = 50
}
}
/**
* Apply the current filter and sort to a genre index.
*
@@ -274,12 +257,12 @@ data class DecadeGroup(
* same reason as [visibleGenres].
*/
fun groupByDecade(years: List<YearCount>): List<DecadeGroup> =
years
.groupBy { (it.year / YEARS_PER_DECADE) * YEARS_PER_DECADE }
years.groupBy { (it.year / YEARS_PER_DECADE) * YEARS_PER_DECADE }
.map { (decade, entries) ->
DecadeGroup(
decade = decade,
years = entries.sortedByDescending { it.year },
albumCount = entries.sumOf { it.albumCount },
)
}.sortedByDescending { it.decade }
}
.sortedByDescending { it.decade }
@@ -10,11 +10,11 @@ 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.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
@@ -32,8 +32,8 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.composables.icons.lucide.ArrowLeft
import com.composables.icons.lucide.LibraryBig
import com.composables.icons.lucide.Lucide
import com.composables.icons.lucide.LibraryBig
import com.fabledsword.minstrel.library.widgets.AlbumCard
import com.fabledsword.minstrel.models.AlbumRef
import com.fabledsword.minstrel.shared.UiState
@@ -74,26 +74,22 @@ private fun GenreIndex(viewModel: BrowseViewModel) {
val sort by viewModel.genreSort.collectAsStateWithLifecycle()
when (val s = state) {
UiState.Loading ->
EmptyState(
title = "Reading your genres…",
body = "",
icon = Lucide.LibraryBig,
)
UiState.Empty ->
EmptyState(
title = "No genres found",
body =
"Genres come from the genre tag on your audio files. If your " +
"library is tagged but this is empty, try a rescan from the admin " +
"screen.",
icon = Lucide.LibraryBig,
)
is UiState.Error ->
ErrorRetry(
message = s.message,
onRetry = viewModel::loadGenres,
)
UiState.Loading -> EmptyState(
title = "Reading your genres…",
body = "",
icon = Lucide.LibraryBig,
)
UiState.Empty -> EmptyState(
title = "No genres found",
body = "Genres come from the genre tag on your audio files. If your " +
"library is tagged but this is empty, try a rescan from the admin " +
"screen.",
icon = Lucide.LibraryBig,
)
is UiState.Error -> ErrorRetry(
message = s.message,
onRetry = viewModel::loadGenres,
)
is UiState.Success -> {
val visible = visibleGenres(s.data, filter, sort)
Column(modifier = Modifier.fillMaxSize()) {
@@ -165,12 +161,11 @@ private fun GenreIndexControls(
label = { Text("A–Z") },
)
Text(
text =
if (filter.isBlank()) {
"$total genres"
} else {
"$shown of $total"
},
text = if (filter.isBlank()) {
"$total genres"
} else {
"$shown of $total"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
@@ -179,17 +174,12 @@ private fun GenreIndexControls(
}
@Composable
private fun GenreRow(
genre: String,
trackCount: Int,
onClick: () -> Unit,
) {
private fun GenreRow(genre: String, trackCount: Int, onClick: () -> Unit) {
Row(
modifier =
Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 14.dp),
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 14.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
@@ -273,23 +263,20 @@ fun BrowseAlbumResults(
}
when {
state.failed && state.albums.isEmpty() ->
ErrorRetry(
message = "Couldn't load albums.",
onRetry = onRetry,
)
state.loading && state.albums.isEmpty() ->
EmptyState(
title = "Loading…",
body = "",
)
state.failed && state.albums.isEmpty() -> ErrorRetry(
message = "Couldn't load albums.",
onRetry = onRetry,
)
state.loading && state.albums.isEmpty() -> EmptyState(
title = "Loading…",
body = "",
)
state.albums.isEmpty() -> EmptyState(title = emptyTitle, body = emptyBody)
else ->
BrowseAlbumGrid(
state = state,
onLoadMore = onLoadMore,
onAlbumClick = onAlbumClick,
)
else -> BrowseAlbumGrid(
state = state,
onLoadMore = onLoadMore,
onAlbumClick = onAlbumClick,
)
}
}
}
@@ -347,13 +334,8 @@ private fun BrowseAlbumGrid(
* is still in flight — a count that appears as 0 and then corrects itself reads
* as a bug.
*/
internal fun albumCountLabel(
total: Int,
loading: Boolean,
loaded: Int,
): String =
when {
loading && loaded == 0 -> ""
total == 1 -> "1 album"
else -> "$total albums"
}
internal fun albumCountLabel(total: Int, loading: Boolean, loaded: Int): String = when {
loading && loaded == 0 -> ""
total == 1 -> "1 album"
else -> "$total albums"
}

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